Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display the user ID in a Django table
I am creating a site with a Forum type of format, where users can create Posts-- where they make statements or ask questions, etc. Then under the Posts, other users can create comments to this Post and carry on the discussion, or whatever the case may be. The problem I'm having is when it comes to creating pages that show all the Posts, according to the User that created them. I will show you the code that I have below: the second link with the tags is not linking me to the Posts created by that particular user, but always shows the same content from User #1 (the admin user). Can you tell me what I'm doing wrong that doesn't allow this to work? Thanks. {% for post in posts %} <tr> <td>{{ post.postTitle }}</td> <td>{{ post.postBody }}</td> <td>{{ post.user }}</td> <td><a href="{% url 'single_post' post.id %}" class="btn btn-info">View Post</a></td> <td><a href="{% url 'user_post' user.id %}" class="btn btn-info">User's Posts</a></td> </tr> {% endfor %} Example of Posts page -
Django OAuth Toolkit - Only admin users issue
I'm implementing OAuth in my Django Rest Framework backend with Django OAuth Toolkit so I can grant access (via authorization code) to Google Actions so when my users trigger an action, my backend can search the user resources and send a specific MQTT message. I have already set up the flow correctly, but the problem I'm facing is that when the authentication form is presented by Django OAuth Toolkit, it only allows my admin users to log in. How can I give any user in my DB the possibility to retrieve an access token? -
Easiest way to display Django model data in html
I have data being stored in a Django model, and I want to display that data in my HTML file. What is the easiest way that I could do this? I am familiar with this question, but it does not help me because it is not very detailed and does not have a definite answer. Can someone please help me? My code is down below. Django Model: class userdetails(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML where I want to display data from the model: <div class="box"> <span class="value"> </span> <span class="parameter">Points</span> </div> -
Django User Editing, AbstractUser
We are trying to build endpoints to allow users to edit their own profiles from our front end and we've encountered a problem while trying to edit the "logged in user". This issue happens in django admin as well. For example in django admin: if we have 3 users, (imagine all three are super users/is_staff for now). Logged in user 1, I can edit users 2 and 3, but when I go to edit user 1 (logged in user), the message says it was updated but the database does not change. If I then login as user 2 and update user 1, I can update user 1 but not user 2 as the logged in user. This same behavior happens on our endpoints with request.user. request.user can edit any user except for the logged in user. Background We do use a custom user model: class User(AbstractUser): timezone = models.CharField(max_length=255, blank=True, null=True) is_customer = models.BooleanField(default=False) is_agent = models.BooleanField(default=False) is_carrier = models.BooleanField(default=False) is_shipper = models.BooleanField(default=False) is_tracking = models.BooleanField(default=False) class Meta: db_table = 'auth_user' def __str__(self): return self.first_name It is defined in settings: AUTH_USER_MODEL = 'accounts.User' It's likely that when we added the custom user model we did something wrong as I believe … -
How can I post multiple object with form data via django rest framework
class DeliveryCompany(models.Model): CompanyName = models.CharField("CRegNo", max_length=50, default=None, null=True, blank=True) Address = models.CharField("CName", max_length=100, default=None, null=True, blank=True) CompanyLogo = models.ImageField( default=None, null=True, blank=True) class DeliveryRoute(models.Model): Delivery = models.ForeignKey(DeliveryCompany, on_delete=models.CASCADE, default=None, null=True) RouteFrom = models.CharField("RouteFrom", max_length=100, default=None, null=True, blank=True) RouteTo = models.CharField("RouteTo", max_length=100, default=None, null=True, blank=True) One company delivers multiple routes. How can I post the data via DRF? Kindly help. Note:- There is an ImageField in DeliveryCompany -
"user" is not set when parsing a data-dict to a Django form, but all other fields are
Say I have the following #models.py class MyModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) link = models.URLField(max_length=2048) date_added = models.DateTimeField(default = timezone.now) used = models.BooleanField(default = True) and my form class MyModelForm(forms.ModelForm): class Meta: model = Wishlist exclude = [ "user","date_added" ] If I try to create an instance like (note, I have omitted the if request.method="POST" etc. for clarity) def myView(request): user = request.user instance = MyModel(user=user) data = {"link":link,"date_added":domain,"user":user} form = MyModelForm(data=data) form.save() the link and date_added is written to the database, but the user field is empty. If I set the user to the instance after the form is created like def myView(request): user = request.user instance = MyModel(user=user) data = {"link":link,"date_added":domain} form = MyModelForm(data=data) form.save(commit=False) form.instance.user = user #Setting the user here form.save() It works like a charm. How come, I cannot set the user in the data-dict, and is there a way to do so? -
Incorrect username and password for Custom User model
I have created a custom user model models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Wrong!") if not username: raise ValueError("Wrong!") user = self.model( username =username, email = self.normalize_email(email), ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username = username, email = self.normalize_email(email), password = password ) user.is_superuser = True user.is_admin = True user.is_staff = True print(user, self.normalize_email(email), password) user.save(using = self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=60, verbose_name='email address', unique=True) address = models.CharField(max_length=200, null=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Even did the proper setting in the admin.py files: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account # Register your models here. class AccountAdmin(UserAdmin): list_display = ['username', 'email', 'address'] search_fields = ['username', 'email'] readonly_fields = ['address'] filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) But the admin panel tells me the username … -
How to achieve custom sorting in django?
From the below model I need the last 3 days comment sorted by likes and again the next 3 days comments sorted by likes and again the next three days sorted by likes... goes on for example today is 24th June I need comments from 24,23,22 sorted by number of likes + comments from 21,20,19 sorted by likes+ comments from 18,17,16 sorted by likes so on ........ how to achieve it class Posts(models.Model): comment_text= models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now()) likes = models.IntegerField(default=0) -
Django migration fails with InvalidForeignKey: "unique constraint" error for "django_site"
I've run into a django migration problem. Please help if you have any idea how to get around this! I upgraded Django from 2.2.7 to 3.2. In the new system I continued work, adding a number of new models. I added a new model called "Space" which has a one-to-one relationship with the Django Site model. This all worked on my development machine (PostgreSQL 9.6) and staging machine (PostgreSQL 9.4, although I had to work around a minor incompatibility with Django 3.2). However, on production we have upgraded from an old version of PostgreSQL 9.4, to PostreSQL 12. Now the migration won't run! It gives the following error: Running migrations: Applying appname.0039_auto_20210521_1034...Traceback (most recent call last): File "/data/virtualenvs/appname/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "django_site" This is the part of the migration file 0039_auto_20210521_1034 that must be causing the problem...? migrations.CreateModel( name='Space', fields=[ ('site', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='spaces', serialize=False, to='sites.Site', verbose_name='site')), ('virtual', models.BooleanField(blank=True, default=False)), ], ), The model looks like this: class Space(models.Model): """Space model is OneToOne related to Site model.""" site = models.OneToOneField( Site, on_delete=models.CASCADE, primary_key=True, related_name='space', verbose_name='site') virtual = models.BooleanField(null=False, blank=True, default=False, help_text="The kind of space … -
Load Static doesn't work when I try to implement Bootstrap theme with Django
So I downloaded a bootstrap theme called "modern-business" and I tried to merge it with my django app. This is how it looks: How it looks This is how it should look: How it should look I was able to figure out that my load static isn't working, because I tried to display some pictures on the webpage and I was able to do that when they were in the same folder as index.hmtl file. But they did not work when I put the images in the static file. This is how I am writing it. for the css, images and the js src lines link href="{% static 'css/styles.css' %}" rel="stylesheet" I have included {% load static %} as well My static file is in /mainproject/recordmgmt/static This is my first time trying to merge django and bootstrap and also the first time using django. I think there I am making a mistake with adding the correct path,but I could be wrong. Let me know how to fix this. -
Django exclude query, can i pass multiple parameters?
I have a query and i want to exclude null companies as well as specific user email. Demo.objects.all().exclude(company__isnull=True, email="abc@gmail.com") but seems like above exclude does not work with multiple arguments, my return queryset has email="abc@gmail.com" in it. If i try above query with single arguments, it works. but not working with multiple arguments. Anyone has any idea how to pass multiple arguments in django exclude ? Thanks -
list index out of range in python django
I've creating an application of books recommandation using python in django , so i'm trying to applicate the k means algorithm of machine learning but when i run it i had an IndexError at /log_in/ list index out of range "in the last line of code",here is the code: # Save session as cookie to login the user login(request, user) # get request user reviewed books user_reviews = BxBookRatings.objects.filter(id=request.user.id) user_reviews_books_ids = set(map(lambda x: x.isbn, user_reviews)) #create matrix all_user_names = map(lambda x: x.username, BxUsers.objects.only("username")) all_books_ids = set(map(lambda x: x.books_id, BxBooks.objects.only("books_id"))) num_users = len(list(all_user_names)) ratings_m = dok_matrix((num_users,max(all_books_ids)+1),dtype=np.float32) all_user_names1= list(all_user_names) for i in all_user_names: # each user corresponds to a row, in the order of all_user_names user_reviews = BxUsers.objects.filter(username= all_user_names1[i]) for user_review in user_reviews: ratings_m[i,user_review.books_id] = user_review.book_rating # Perform kmeans clustering # k = int(num_users / 10) + 2 k=4 kmeans = KMeans(n_clusters=k) clustering = kmeans.fit(ratings_m.tocsr()) Cluster.objects.all().delete() new_clusters = {i: Cluster(name=i) for i in range(k) } for cluster in new_clusters.values(): # clusters need to be saved before referring to users cluster.save() for i,cluster_label in enumerate(clustering.labels_): new_clusters[cluster_label].users.add(BxUsers.objects.get(username=all_user_names1[i])) thank you for helping me to solve this problem -
Django template filter extract from list
My view context dictionary produces a list of footage numbers (eg. [1200, 1137, 1428, 5774... ]). I have corresponding tags in my template that pull specific list members... <td> {{ footage | slice:"-1:" }}</td><td> {{ footage | slice:"-2:-1" }}</td><td> {{ footage | slice:"-3:-2" }}</td><td> {{ footage | slice:"-4:-3" }}</td> problem is – when rendered, the html displays the values as a list with a single value – as opposed to a standalone string... how can I extract the values from the brackets (pull them from the lists)? -
django {% url %} template looping
my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] customer_url.py from application_name import views app_name="customer" urlpatterns=[ url(r"^items/",views.items, name='items'), url(r"^checkout/$", views.checkout, name='checkout'), url(r"^make_payment/$", views.make_payment, name='make_payment'), ] staf url would be staff/orders or staff/payments customer urls would be customer/items or customer/checkout etc In my view file I have put every link inside a list which would be iterated inside the template and placed it inside a session This is my view.py staffLink=[ {'linkfield':"customers", 'name':"Customers",'slug':"staff"}, {'linkfield':"orders", 'name':"Orders",'slug':"staff"}, {'linkfield':"payments", 'name':"payments",'slug':"staff"}] links=staffLink request.session['links']= links request.session['sub']= 'staff' context_dict = {'links':links} This is my html template {% for link in request.session.links %} {% if request.session.sub =="staff" %} <a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link"> {% elif request.session.sub =="customer" %} <a href="{% url 'application_name:customer' link.linkfield as the_url %}" class="nav-link"> {% endif %} {% endfor %} Pl This are the following result When I include the if statement i.e. {% if request.session.sub =="staff" %}. The following error is produced django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '=="staff"' from '=="staff"' When I exclude the if statement so making it just <a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link"> I did this for … -
Django Paypal: How To Cancel Subscription From View
I am trying to cancel a subscription from the view but when i view the response all i get is namemessagedebug_iddetailslinks on the page. i used the docs (search for cancel subscription) to send this api call. if i view the source of the response i get TIMESTAMP=2021%2d06%2d23T00%3a45%3a18Z&CORRELATIONID=bce3e4b335473&ACK=Failure&VERSION=86&BUILD=55100925&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Security%20error&L_LONGMESSAGE0=Security%20header%20is%20not%20valid&L_SEVERITYCODE0=Error views.py: def manage_subs(request): header_params = { "Accept": "application/json", "Accept-Language": "en_US", } param = { "grant_type": "client_credentials", } cid = settings.PAYPAL_CLIENT_ID secret = settings.PAYPAL_CLIENT_SECRET token_i = requests.post('https://api-m.sandbox.paypal.com/v1/oauth2/token', auth=(cid, secret), headers=header_params, data=param).json() token = token_i["access_token"] bearer_token = 'Bearer x'.replace('x', token) headers = { 'Content-Type': 'application/json', 'Authorization': bearer_token, } p = { 'reason': "Not satisfied with the service" } url = 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions/*/cancel' # * is replaced with the subscription_id response = requests.post(url, headers=headers, data=p).json() return HttpResponse(response) -
Django models subtraction issue
class Finances(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) student_name = models.CharField(max_length=100, default={Student.student_name}) total_fees = models.IntegerField(default=3500) paid_amount = models.IntegerField(default=0) balance = total_fees - paid_amount balance_fees = models.IntegerField({balance}) I need the balance_fees model to hold the value of a subtraction of total_fees - paid_amount which is held by the balance. I get an error when making migrations 'TypeError: unsupported operand type(s) for -: 'IntegerField' and 'IntegerField' How can I resolve this? -
Displaying Django Models data in html file
I want to display data taken from my Django models in my html file. So in the code bellow instead of a 0 I want the donation model data. Can someone please help? Thank you! Model.py class userdetails(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML: <div class="box"> <span class="value">0</span> <span class="parameter">Donations</span> </div> -
User signup system in Django with custom fields
I am trying to make a user Signup system along with his profile. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=50, unique="True", blank=False) password = models.CharField(max_length=200, blank=False) USERNAME_FIELD = 'username' class Profile(models.Model): user = models.OneToOneField(myCustomeUser, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") my forms.py: class SignUpForm(ModelForm): class Meta: model = Profile fields = '__all__' my views.py: class index(generic.CreateView): form_class = SignUpForm template_name = 'index.html' Now here my problem is, the form gives me an option to choose any user (with dropdown) to create a profile.... but I want to create a user also on that page (not pick an option from dropdown). How can I try for that? -
Missing Python.h file for mod_wsgi
I am following some instruction here to install apache2 and mod_wsgi in order to host Django app. At the step: git clone https://github.com/GrahamDumpleton/mod_wsgi.git ./configure --with-python=/path/to/your/python/exec make The make command gives the following error message: src/server/wsgi_python.h:26:10: fatal error: Python.h: No such file or directory #include <Python.h> What is the this Python.h file and where should I get it from? This thread discusses similar issue of missing Python.h file. I am using Ubuntu and have already installed both : sudo apt-get install python-dev sudo apt-get install python3-dev Reading package lists... Done Building dependency tree Reading state information... Done python3-dev is already the newest version (3.6.7-1~18.04). 0 upgraded, 0 newly installed, 0 to remove and 16 not upgraded. Reading package lists... Done Building dependency tree Reading state information... Done python-dev is already the newest version (2.7.15~rc1-1). 0 upgraded, 0 newly installed, 0 to remove and 16 not upgraded. What is missing still? -
Why will my django website not load correctly with runserver?
Urgent! I am currently working on a django project. One moment my local server, that I ran using "python manage.py runserver", was working fine, I messed around a little with the bootstrap classes, and now, the page is forever loading, nothing is clickable (left-click or right-click), and I can't even open up developer tools. I have tried the following: Restart the server Restart VSCode Try different browser Restart browser Restart computer Clear browser cache (because why not) Tried opening in a private browser (to avoid extensions) Nothing seems to work. I'm not getting any errors in the terminal. What's going on? -
type object 'Profile' has no attribute 'USERNAME_FIELD'
I am building a custom User class in django to use in creating a signup application and I keep on getting the error above every time I try to run the code. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=50, unique="True", blank=False) password = models.CharField(max_length=200, blank=False) USERNAME_FIELD = 'username' def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(myCustomeUser, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") facebook_url = models.CharField(null=True, blank=True, max_length=255) twitter_url = models.CharField(null=True, blank=True, max_length=255) instagram_url = models.CharField(null=True, blank=True, max_length=255) linkdin_url = models.CharField(null=True, blank=True, max_length=255) def __str__(self): return str(self.user) my forms.py: class SignUpForm(UserCreationForm): class Meta: model = Profile fields = '__all__' in views.py: class index(generic.CreateView): form_class = SignUpForm template_name = 'index.html' It says following error after run the code: AttributeError at / type object 'Profile' has no attribute 'USERNAME_FIELD' Kindly suggest how can I fix it? -
Missing Python.h in mod_wsgi to host Django app [duplicate]
I am following some instruction here to install apache2 and mod_wsgi in order to host Django app. At the step: git clone https://github.com/GrahamDumpleton/mod_wsgi.git ./configure --with-python=/path/to/your/python/exec make The make command gives the following error message: src/server/wsgi_python.h:26:10: fatal error: Python.h: No such file or directory #include <Python.h> What is the this Python.h file and where should I get it from? -
Django form not working once I change URL's
Very new to Django, but have followed a tutorial to create a SQLite3 DB which is added to and updated from forms on various html pages. Once I try to change the URL's involved from path('',include('members.urls')), to path('members/',include('members.urls')), issues arise. The submit button for changing the entries for the database keeps POST'ing to "127.0.0.1:8000/update/1" instead of "127.0.0.1:8000/members/update/1" Here is what I think might be relevant code in case someone can help out? Project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('members/',include('members.urls')), path('',include("django.contrib.auth.urls")) ] Members views.py def update(request,id): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] Post.objects.filter(id=id).update(time=time,player1=player1,player2=player2,player3=player3) messages.success(request,'Data has been updated') post=Post.objects.get(id=id) return render(request,'update.html',{'post':post}) Members urls.py urlpatterns = [ path('',views.home,name='home'), path('teetimes/',views.teetimes,name='teetimes'), path('add/',views.add,name='add'), path('update/<int:id>',views.update,name='update') ] Members teetimes.html <h3>All Times</h3> {% for post in posts %} <div> <table class="table table-bordered"> <th><h5>{{post.time}} <br> <a href="/update/{{post.id}}" class="btn-sm btn-success">Update</a></h5></th> <th><h6>{{post.player1}}</h6></th> <th><h6>{{post.player2}}</h6></th> <th><h6>{{post.player3}}</h6></th> </table> </div> {% endfor %} Members update.html % if messages %} {% for msg in messages %} <p class="text-success">{{msg}}</p> {% endfor %} {% endif %} <form method="post" action="/update/{{post.id}}"> {% csrf_token %} <table class="table table-bordered"> <tr> <th>Time</th> <td> <input value="{{post.time}}" type="text" name="time" class="form-control"> </td> </tr> <tr> <th>Player 1</th> <td> <input value="{{post.player1}}" type="text" name="player1" class="form-control"> </td> </tr> <tr> <th>Player 2</th> <td> <input value="{{post.player2}}" type="text" name="player2" class="form-control"> </td> </tr> <tr> … -
How can I filter using uuid of Foreign Key in Django?
I have three tables Token, Auth, UserProfile class Token(models.Model): token = models.CharField(primary_key=True, max_length=255, default=uuid.uuid4().__str__()) auth = models.ForeignKey(Auth, models.DO_NOTHING, blank=True, null=True) class Auth(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) password = models.CharField(max_length=255, blank=True, null=True) user_id = models.CharField(unique=True, max_length=255) role = models.CharField(max_length=255, blank=True, null=True) source = models.CharField(max_length=255, blank=True, null=True) class UserProfile(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) name = models.CharField(max_length=255, blank=True, null=True) phone_number = models.CharField(max_length=255, blank=True, null=True) auth = models.ForeignKey(Auth, models.DO_NOTHING) How can I get UserProfile as I have Token class's object I tried user = UserProfile.objects.get(auth=token.auth) which gives me the error UserProfile matching query does not exist. -
How to use middleware for group route in django like in Laravel?
I am a Laravel developer. I am building web site using Django. I have a problem in development with Django. Route::group(['middleware' => ['checkEAdmin']], function () { Route::post(....); Route::post(....); Route::post(....); Route::post(....); Route::post(....); }); I used middleware for group routes. how can I use middelware in django like this? please help me Thank you.