How to make new accounts(object) in Django? - python

#views.py
def signup(request):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
*new_user = Profile.objects.create_user(**form.cleaned_data)*
login(request, new_user)
return HttpResponse('signup success.')
else:
form = ProfileForm()
return render(request, 'registration/profile.html', {'form': form})
I want to make new accouont(object) so, I want to use User.objects.create_user method
#models.py
class Profile(models.Model):
studentNumber = models.CharField(max_length=30, blank=True)
name = models.CharField(max_length=10, blank=True)
major = models.CharField(max_length=20, blank=True)
email = models.CharField(max_length=30, blank=True)
password = models.CharField(max_length=15, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
github = models.CharField(max_length=150, blank=True)
sns = models.CharField(max_length=150, blank=True)
it is my model!
How can I save my model to DB?

Related

How to get username field automatically in Django

I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective.
Here is my Models.py
`class User(AbstractUser):
is_buyer=models.BooleanField(default=False)
is_seller=models.BooleanField(default=False)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
seller = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Order(models.Model):
buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False)
seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500)
amount = models.IntegerField(max_length=50, blank=False)
is_ordered = models.BooleanField(default=False)
order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False)
slug = models.SlugField(null=True)
def __str__(self):
return self.title`
And views.py where I am getting the submissions;
def createOrder(request):
profile = request.user.profile
form = CreateOrderForm()
if request.method == 'POST':
form = CreateOrderForm(request.POST, request.FILES)
if form.is_valid:
order = form.save(commit=False)
order.buyer = profile
order.save()
# form.save()
messages.info(request, 'Order Succesfully Created')
return redirect('create_order')
else:
messages.error(request, 'Order Not Created! Try Again Later')
context = {'form':form}
return render(request, 'users/create_order.html', context)
Any help will he highly appreciated.

Error when trying to save a form in django

I am new to django and I am working on a project whereby users fill a form from frontend and the data is saved to a gig model where the writer extends from a profile foreignkey. The error says
ValueError at /seller_profile/ The Gig could not be created because
the data didn't validate.
Here is the models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
writer = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
image = models.ImageField(null=False, blank=False)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Views.py:
def createGig(request):
gig = request.user.profile
form = CreateGigForm()
if request.method == 'POST':
form = CreateGigForm(request.POST, request.FILES)
if form.is_valid:
gig = form.save(commit=False)
gig.writer = gig
gig.save()
messages.info(request, 'Profile Succesfully Created')
return redirect('create')
else:
messages.error(request, 'Gig Not Created! Try Again Later')
context = {'form':form}
return render(request, 'starter/create_gig.html', context)
And here is a screenshot of the error message: Error message screenshot
I found the solution to this. The problem was with checking if form is valid there was an error with missing brackets. if form.is_valid: should be if form.is_valid:.

Connect the username when sending a report in django

I am beginner to django and I am trying to create a site to send reports after creating a profile, but when I send the report, the username of the author of the report is not saved, Just (None). I searched a lot about it and did not find it
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, verbose_name=("user"), null=True, on_delete=models.CASCADE)
identity_No = models.IntegerField( blank=True, null=True)
mobile_No = models.IntegerField( blank=True, null=True)
city = models.CharField( max_length=15,null=True)
class Meta:
verbose_name =("Profile")
verbose_name_plural =("Profile")
def __str__(self):
return '%s' %(self.user)
class Report(models.Model):
user = models.ForeignKey(User, verbose_name=("user"), on_delete=models.CASCADE)
Report_type =models.CharField( max_length=100, blank=True, null=True)
Region =models.CharField( max_length=30, blank=True, null=True)
city =models.CharField( max_length=30, blank=True, null=True)
sector =models.CharField( max_length=30, blank=True, null=True)
report =models.TextField( max_length=3000, blank=True, null=True)
files =models.FileField( blank=True, null=True)
class Meta:
verbose_name =("Report")
verbose_name_plural =("Report")
def __str__(self):
return '%s' %(self.user)
form.py
Shorten the time, attach only the report
class ReportForm(forms.ModelForm):
class Meta:
model = Report
fields = ['Report_type', 'Region', 'city','sector','report','files' ]
view.py
def report(requst):
if requst.method == 'POST':
report_form = ReportForm(requst.POST)
if report_form.is_valid() :
report_form.save()
return redirect ('accounts:home')
else:
report_form = ReportForm()
return render(requst, 'user/report.html', {
'report_form': report_form,
enter image description here })
You can link the new report wrapped in the ReportForm to the logged in user request.user with:
from django.contrib.auth.decorators import login_required
#login_required
def report(requst):
if requst.method == 'POST':
report_form = ReportForm(requst.POST)
if report_form.is_valid():
report_form.instance.user = request.user
report_form.save()
return redirect ('accounts:home')
else:
report_form = ReportForm()
return render(requst, 'user/report.html', { 'report_form': report_form })
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].

How to implement suitable login form for my registration form and model User?

So, i have such model
class User(models.Model):
CHOICES = (
('1', 'Author'),
('2', 'Customer'),
('3', 'Author and Customer')
)
first_name = models.CharField(max_length=64, blank=False, verbose_name='')
last_name = models.CharField(max_length=64, blank=False, verbose_name='')
patronymic = models.CharField(max_length=64, blank=False, verbose_name='')
age = models.PositiveSmallIntegerField(verbose_name='', blank=False)
email = models.EmailField(unique=True, max_length=128, blank=False, verbose_name='')
password = models.CharField(max_length=32, blank=False, verbose_name='')
role = models.CharField(max_length=32, choices=CHOICES, default='Customer')
about = models.TextField(max_length=512, verbose_name='', blank=True)
and such register form
class RegisterForm(ModelForm):
class Meta:
model = User
fields = "__all__"
it seems like that
and my view for registration form
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponse("Successfull!")
else:
return render(register, 'account/register.html')
else:
form = RegisterForm()
return render(request, 'account/register.html', {'form': form})
but my login view doesn't work(it always gives me invalid data)
What would be the best login view for my forms and models?

Django - Edit access only if logged in user is the user who added the item or if he is a superuser

I am working on a rental website project where users can create a login and add a listing. Now I want the edit access to be given to only the owners of those listing and superuser. I am able to set the edit access either to superuser or to the user, I am trying to figure out how to do both.
models.py
class Listing(models.Model):
category = models.ForeignKey(
'Category', null=True, blank=True, on_delete=models.SET_NULL)
listing_name = models.CharField(max_length=250, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
price = models.CharField(max_length=250, null=True)
short_description = models.CharField(max_length=720)
description = models.TextField()
bedroom = models.CharField(max_length=250, null=True, blank=True,)
bathroom = models.CharField(max_length=250, null=True, blank=True,)
lease = models.CharField(max_length=250, null=True, blank=True)
contact_name = models.CharField(max_length=250, null=True)
email_address = models.CharField(max_length=250, null=True)
contact_number = models.CharField(max_length=12, null=True)
image_url = models.URLField(max_length=1024, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
image_one = models.ImageField(null=True, blank=True)
image_two = models.ImageField(null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.listing_name
views.py
#login_required
def edit_listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
if not request.user.is_superuser or request.user == listing.user:
messages.error(
request, 'Sorry, you dont have the permission to do that.')
return redirect(reverse('home'))
if request.method == 'POST':
if request.user == listing.user:
form = ListingForm(request.POST, request.FILES, instance=listing)
if form.is_valid:
form.instance.user = request.user
form.save()
messages.success(request, 'Successfully updated the listing')
return redirect(reverse('listing_detail', args=[listing.id]))
else:
messages.error(
request, 'Failed to update. Please ensure the form is valid.')
else:
form = ListingForm(instance=listing)
template = 'listings/edit_listing.html'
context = {
'listing': listing,
'form': form,
}
return render(request, template, context)
Particularly this line in the views is what I'm trying to achieve
if not request.user.is_superuser or request.user == listing.user:
messages.error(
request, 'Sorry, you dont have the permission to do that.')
return redirect(reverse('home'))

Categories

Resources