django user queries to get data from database - python

I have models.py like this
class Faculty(TimeStampedModel):
_registry = []
faculty_code = models.CharField(max_length=30, unique=True)
name = models.CharField(max_length=255)
date_of_birth = models.DateField(default=datetime.date.today)
age = models.IntegerField()
current_subjects = models.CharField(max_length=255)
research_interest = models.CharField(max_length=255, blank=True)
joining_year = models.CharField(
max_length=5, )
projects = models.CharField(max_length=255, blank=True)
now the user can't add Faculty but can view those created from the admin. In order to do so the user must enter the faculty_code in a form after which I have to get the other fields and show it to the user.
I don't how to implement this. I mean anytime we create a django-form and use POST method it creates a new object I don't want that. User should send a 'GET' request to fetch data of other fields of the class.

I don't think a form is necessary for this, use a DetailView.
url
urlpatterns = patterns('',
url(r'^faculty/(?P<slug>\w+)/$', FacultyDetail.as_view()),
)
view
from django.views.generic.detail import DetailView
class FacultyDetail(DetailView):
model = Faculty
slug_field = 'faculty_code'
More info:
docs
ccbv

Related

'project.Account' has no ForeignKey to 'project.Object': How to link an account model to the objects of a project?

I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address...
So I modified admin.py:
from django.contrib import admin
from .models import Todo, Account
from django.contrib.auth.models import User
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class TodoAdmin(admin.ModelAdmin):
readonly_fields = ('created',)
inlines = (AccountInline, )
admin.site.unregister(User)
admin.site.register(Todo, TodoAdmin)
But got back:
<class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'.
So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE):
from django.db import models
from django.contrib.auth.models import User
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.CharField(max_length=100)
firstname = models.CharField(max_length=30)
lastname = models.CharField(max_length=50)
company = models.CharField(max_length=5)
def __str__(self):
return self.user.username
class Todo(models.Model):
title = models.CharField(max_length=100)
datetime = models.DateTimeField()
memo = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
datecompleted = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
def __str__(self):
return self.title
But I still have the error, and I don't have any Users in the admin panel anymore
You accidentally wrote unregister for Users in your admin.py file. It should be admin.site.register(User)
You misinterpretted the error: the error states that you don't have a foreign key in your Account model to Todo.
This means your inline admin code isn't correct as it's expecting the other way around.

django assign User to a model

I want to assign a User to a Model in django, I created a custom User model and sign-up/sign-in Forms but now I want to Assign a User model to another model named Customer whenever a new user is Created Here he the Customer model
class Customer(models.Model):
id = models.AutoField(primary_key=True)
User = models.OneToOneField(
Account, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, default='0', null=True, blank=True)
address = models.CharField(
max_length=200, default=' ', null=True, blank=True)
city = models.CharField(max_length=200, default=' ', null=True, blank=True)
def __str__(self):
if self.name == None:
return "ERROR-CUSTOMER NAME IS NULL"
return self.name
Note: I can assign the User manually in the Database and It lists All the Users but I want it to do it itself when a new user is created
I think it would be better to extend the User model, and add more fields rather than creating a new model (which has a User onetoonefiled in it).
Something like this:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
This is the kind of approach I use in my projects.
Here you have the default User model fields:
User model default fields
You don't need to add these in your Profile class.
I based this on this article: How to extend User Django Model
don't forget to add to the admin.py:
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
to see the Profiles in the admin page
Got it fixed by setting the user in the Customer model when a user is created
Customer.objects.create(user=request.user, name=username, email=email, phone=phone)

Django admin page not showing user models

My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users.
I have made custom models as shown below.
Database is MySQL.
models.py
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_restaurant = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
food_pref = models.CharField(max_length=10, default='veg')
class Restaurant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
restaurant_name = models.CharField(max_length=100, blank=False)
Regisrar your models inadmin.py file.
from . models import Model_Name
Then you can register your models in two ways:
I) admin.site.register(Model_Name)
II)
#admin.register(Model_Name)
Class Xyz(admin.ModelAdmin):
pass
Second method gives you more flexibility like list_display, list_filter, date_hierarchy, etc. for customising your Admin section/site.
You can look more about customising admin site at https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#module-django.contrib.admin
Have You registered them in admin.py?
from .models import ModelName
admin.site.register(ModelName)

How to save forms field in django

i have some fields in my django models.
class Product(models.Model):
user=models.ForeignKey(User)
product_name = models.CharField(max_length=50)
product_cost = models.IntegerField(default=0,null=True, blank=True)
product_description = models.TextField(null=True, blank=True)
quantity = models.IntegerField(default=0,null=True, blank=True)
product_image = models.FileField(upload_to='images/',blank=True,null=True,)
coupon_code = models.CharField(max_length=50)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.product_name or u''
when i use form to save all the data from front end in my database i can do this.
class DocumentForm(forms.ModelForm):
class Meta:
model = Product
fields = ('user','product_name','product_image','product_cost','product_description','product_description','coupon_code')
Problem is this i don't want to allow user to fill user data from front-end.when user save data it save request.user to user.
I am new to work with forms so facing some issues.
Please help me how can i do this.
Thanks in advance.
In fields you have to remove user:
so it will look like this:
class DocumentForm(forms.ModelForm):
class Meta:
model = Product
fields = ('product_name','product_image','product_cost','product_description','product_description','coupon_code')
and in your views.py when you save the data from the form you have write something like this:
user = request.user
in this case user will be saved if he is authenticated.
If you want that not authenticated user could fill the form too, you have to change in your model.py Product class from:
user=models.ForeignKey(User)
to:
user=models.ForeignKey(User, null=True)
then not authenticated user will be NULL.

How to allow only one User to see "UpdateView"?

I have a Users and Jobs. If some User creates a Job, then and only then he/she can edit some information of this Job.
So he visits the url .../job/update/<id>. If the Job is created by him (the User is a ForeignKey in Job, then he can modify data. Otherwise he gets 404 error.
In view function, I would probably get current Users id and compare this id to Jobs ForeignKey.
But there are many patterns and shortcuts in class views so I'm curious how to do that this way.
class EditOrderView(UpdateView):
model = Job
fields = ['language_from','language_to','level','short_description','notes',
'text_to_translate','file']
template_name = 'auth/jobs/update-order.html'
class Job(models.Model):
customer = models.ForeignKey(User, related_name='orders', help_text=u"Zákazník")
translator = models.ForeignKey(User, related_name='jobs', null=True, blank=True, help_text=u"Prekladateľ")
price = models.FloatField(null=True, blank=True, help_text=u"Cena")
language_from = models.ForeignKey(Language, related_name='jobs_from', null=True)
language_to = models.ForeignKey(Language, related_name='jobs_to', null=True)
...
It looks like you can override .get_object() method and include your own logic:
from django.shortcuts import get_object_or_404
class EditOrderView(UpdateView):
model = Job
...
def get_object(self, queryset=None):
return get_object_or_404(self.model, pk=self.kwargs["pk"], customer=self.request.user)

Categories