i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and i have tried diffrent solutions to fix this
views.py
def register(request):
reviews = Review.objects.filter(status='published')
info = Announcements.objects.all()
categories = Category.objects.all()
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
obj = request.user
get_membership = Membership.objects.get(membership_type='Free')
# error is showing "instance" is not access using visual studio code
instance = UserMembership.objects.create(user=obj, membership=get_membership)
messages.success(request, f'Account Successfully created for {username}! You can Login In Now')
return redirect('userauths:login')
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
context = {
'reviews': reviews,
'form': form,
'info': info,
'categories': categories
}
return render(request, 'userauths/register.html', context)
indentation error here:
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
You only need to tab once. Not twice.
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
Related
I am making a library system with signup pages (admin and user), so when I make an admin user I want to make it in staff, so how can I use (is_staff)?
this is my registration function...
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
context = {'form':form}
return render(request, 'pages/register.html', context)
You can alter the .instance wrapped in the form before saving it to the database:
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.instance.is_staff = True
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
return render(request, 'pages/register.html', {'form':form})
I want to restrict users to access the payment and checkout pages by typing the url in address bar like "home/shop/checkout/" and "home/shop/payment/"
I want to make these pages accessible only if either buy_now form is valid or items_buy_now form is valid
urls.py
path('payment/',views.payment,name='payment'),
path('checkout/', views.checkout, name="checkout"),
views.py
def checkout(request):
request.session.pop('data', None)
messages.success(request,'Done.Thanks for using our services.')
return redirect("shop:mycart")
def payment(request):
return render(request,'shop/payment.html')
def buy_now(request,slug):
if not request.user.is_authenticated:
messages.info(request, 'You have to logged in first.')
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
product = Product.objects.get(active=True, slug=slug)
if request.method == "POST":
form = BuyerDeliveryForm(request.POST)
if form.is_valid():
buyer = form.save(commit=False)
buyer.save()
return redirect('shop:payment')
else:
form = BuyerDeliveryForm()
return render(request, 'shop/delivery_form.html', {'form': form, 'products': product})
def items_buy_now(request):
if not request.user.is_authenticated:
messages.info(request, 'You have to logged in first.')
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
if request.method == "POST":
form = BuyerDeliveryForm(request.POST)
if form.is_valid():
buyer = form.save(commit=False)
buyer.save()
return redirect('shop:payment')
else:
form = BuyerDeliveryForm()
return render(request, 'shop/delivery_form.html', {'form': form})
The best way to do it is to :
Create a Mixin that manager either items_buy or items_buy
For all the views that have to handle the restriction, subclass it from the respective mixin.
In the get function of the subclass call the method to check if the user has the authorization to access to that page.
how to add an error message to be displayed if the user tried to add an entry that is already on the table
forms.py
class AddCatForm(ModelForm):
class Meta:
model = Categories
fields = ['category_name']
labels = {
'category_name': ('إسم الفئة الجديدة')
}
error_messages = {
'category_name': {
'unique': ('الفئة موجودة بالفعل')
}
}
views.py
def add_cat(request):
if request.method == "POST":
form = AddCatForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('/')
else:
form = AddCatForm()
return render(request, "add_cat.html", {'form': form})
When i add an entry that is already there , it just does nothing , i want it to view an error
You might be getting an error which you will not see because of your indentation. Amend it to:
def add_cat(request):
if request.method == "POST":
form = AddCatForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('/')
else:
form = AddCatForm()
return render(request, "add_cat.html", {'form': form})
I'm reading the documentation on how to display a message to the user with Django messages. It says that in order to add a message in your views to call:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
I'm not sure where to put the second the second line, this is my view:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
return HttpResponse('Thank you')
else:
return HttpResponse('That text is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
I want the message to appear and thank the user for signing up and display their input as well.
Bearing, in mind that it's customary to redirect to a success url on valid form submission, your code ought to look like this:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
messages.add_message(request, messages.INFO, 'Hello world.')
return HttpResponseRedirect('/thank-you-page/')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
note that this also results in the user being told why exactly his form is invalid (assuming that you have set up the template propertly). It's always good to say what the problem is rather than to say there is a problem.
You can put the second line in view with example:
def contact(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
textarea = request.POST.get('textarea')
contact = Contact(name = name,email = email,password = password,textarea = textarea,date=datetime.today())
contact.save()
messages.success(request, 'Form has submitted')
return render(request,"contact.html")
I have created an invoice and items in it using Modelform and inlineforset_factory.
Now I am trying to create edit form, but I am getting MultiValueDictKeyError when I try to edit those inline fields. If I just create new inlineformsets I can edit Modelform just fine. After one hour of googling I am no closer to finding any solution.
maxItems = 20
ItemFormSet = inlineformset_factory(Invoice, Item, can_delete=True, extra=maxItems)
Creating of new invoice (working perfectly)
def new_invoice(request):
if request.method == "POST":
form = InvoiceForm(request.POST)
if form.is_valid():
invoice = form.save(commit=False)
item_formset = ItemFormSet(request.POST,instance=invoice)
if item_formset.is_valid():
invoice.dateCreated = datetime.datetime.now()
invoice.save()
item_formset.save()
return redirect('list/new0')
else:
form = InvoiceForm()
item_formset = ItemFormSet(instance=Invoice())
return render(request, "form.html", {"form": form, "item_formset": item_formset })
Editing invoice (MultiValueDictKeyError)
def edit_invoice(request, invoice_id):
invoicer = get_object_or_404(Invoice, pk=invoice_id)
if request.method == "POST":
form = InvoiceForm(request.POST, instance=invoicer)
if form.is_valid():
invoice = form.save(commit=False)
item_formset = ItemFormSet(request.POST,instance=invoice)
if item_formset.is_valid():
invoice.dateCreated = datetime.datetime.now()
invoice.save()
item_formset.save()
return redirect('list/new0')
else:
form = InvoiceForm(instance=invoicer)
item_formset = ItemFormSet(instance=invoicer)
return render(request, "form.html", {"form": form, "item_formset": item_formset })
You have two variables, invoicer and invoice that I assume are different instances of the same object. Try re-writing your edit view like this:
def edit_invoice(request, invoice_id):
invoice = get_object_or_404(Invoice, pk=invoice_id)
if request.method == 'POST':
form = InvoiceForm(request.POST, instance=invoice)
formset = ItemFormSet(request.POST, instance=invoice)
if form.is_valid() and formset.is_valid():
invoice = form.save()
invoice.dateCreated = datetime.datetime.now()
invoice.save()
formset.save()
return redirect('list/new0')
else:
form = InvoiceForm(instance=invoice)
formset = ItemFormSet(instance=invoice)
context = {
'form': form,
'formset': formset,
}
return render(request, 'form.html', context)
Let me know if that works for you.
Ok, so I've found that problem was not in the views.py nor in forms.py, but in template. Because I've built the template without using {{form.as_p/table/...}} The form had some extra inputs - DELETE,ID and foreignKey... after adding them to my for loop, everything works fine :)