Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
waypoint infinite scroll loads the next page only once
Html: <div class="loading" style="display: none;"> <div id=circle2></div> <img class=virus id=incircle2 src="{% static 'icons\virus.png' %}" alt="virus"> </div> {% if entries.has_next %} <a class="infinite-more-link" href="?page={{ entries.next_page_number }}"></a> {% endif %} JS: var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); Well I found only one similar question and the recommended solution was to wrap the tag in span as: <span><a href="load-more.php" class="infinite-more-link">More</a></span> But that solution didn't work for me, thank you all for reading. -
TypeError 'builtin_function_or_method' is not iterable during heroku deployment
I'm trying to deploy my first django app to heroku. I have followed all the settings steps in the guide but I run into the following Traceback during deployment: if 'DATABASES' not in config: TypeError: argument of type 'builtin_function_or_method' is not iterable If I disable collectstatic then deployment runs without errors but as soon as I try to migrate my database it raises the same error. Can anyone help please? -
Django Sort By Model Function Not By Model Field
In the CourseForm I would like to sort by the longest total_duration, shortest total_duration, most total_lesson_views and least total_lesson_views. These are all Course parent class functions being done on the Lesson child class inside of the models.py file. Since these are not model fields to sort on, and instead are functions, it makes things a bit more challenging. How would you go about doing this? Courses App Forms.py: class CourseForm(forms.Form): sort = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'sort'}), choices = ([('','- - - - - - - -'), ('name','Ascending'), ('-name','Descending'),('-date','Newest'), ('date','Oldest'), ('-views','Most Popular'), ('views','Least Popular'), ]), required=False) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['sort'].label = "Sort:" Courses App Views.py: class CourseListView(ListView): model = Course template_name = 'courses/course_list.html' sortable_attributes = ['name', 'views', 'date'] def get_queryset(self): qs = super().get_queryset() self.form = form = CourseForm(self.request.GET) if form.is_valid(): sort_query = self.request.GET.get('sort') if sort_query: match_query = sort_query if '-' not in sort_query else sort_query[1:] if match_query in self.sortable_attributes: qs = qs.order_by(sort_query) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form return context Courses App Models.py: class Course(models.Model): slug = models.SlugField() name = models.CharField(max_length=120) date = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) @property def total_duration(self): seconds_dictionary = Lesson.objects.filter(course=self).aggregate(Sum('duration')) sec = seconds_dictionary['duration__sum'].total_seconds() if sec >= 3600: return '%2d:%02d:%02d' % (int((sec/3600)%3600), … -
building a django app using docker: libpython3.8.so.1.0 no such file or directory
I'm trying to build my django app using Docker but I'm getting the following error while executing docker-compose up: /usr/local/bin/python: error while loading shared libraries: libpython3.8.so.1.0: cannot open shared object file: No such file or directory Actually python is not installed at /usr/local/bin Here's my docker-compose.yml file: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: Django/ command: python manage.py runserver volumes: - .:/code ports: - "8000:8000" depends_on: - db and my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip3 install -r requirements.txt COPY . /code/ -
How to update only specific fields in django model?
I want to update only specific fields in my model. This is my models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='teacher/images') phone = models.CharField(max_length=15) address = models.CharField(max_length=25) salary = models.DecimalField(max_digits=20, decimal_places=2) joindate = models.DateField(auto_now_add=True) status = models.BooleanField(default=True) And this is my forms.py class TeacherForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] class TeacherExtraForm(forms.ModelForm): class Meta: model = models.Teacher fields = ['phone', 'address', 'salary', 'status', 'image'] And this is my views.py def update_teacher(request, pk): teacher = models.Teacher.objects.get(id=pk) user = models.User.objects.get(id=teacher.user_id) form1 = forms.TeacherForm(instance=user) form2 = forms.TeacherExtraForm(instance=teacher) context = { 'teacher': teacher, 'user': user, 'form1': form1, 'form2': form2 } if request.method == 'POST': form1 = forms.TeacherForm(request.POST, instance=user) form2 = forms.TeacherExtraForm(request.POST, instance=teacher) if form1.is_valid() and form2.is_valid(): user = form1.save() # user.set_password(user.password) user.save(update_fields=['first_name', 'last_name', 'email', 'username']) f2 = form2.save(commit=False) f2.status = True f2.save(update_fields=['phone', 'address', 'salary', 'status']) return redirect('Teacher:teacher_index') return render(request, 'Teacher/update_teacher.html', context) Here I only want to update the first_name, last_name, email, username, phone, address, salary and status without affecting the password and image field. When I add the password and image field also, it works but I do not want to update password and image here. -
django csrf verification failed in android webview
I design a Django web app and then I create an android webview.in android webview, all functions work properly.in the Django web app, I use a payment gateway. payment gateway working in all browsers but it's not working in the android web view.android webview its return a forbidden(403) CSRF verification failed error. -
How to store images based on a particular user in django?
I have a multi-user platform built using Django, Each user should have their own image gallery, which should be hidden to other users. How exactly can I design such a network using Django? -
How to acces user detail in template in django
I want check whether logged in user is doctor or patient i tried the following method to check that thing,but did not succeed can any one help me. model.py forms.py index.html output or what does this error means Could not parse the remainder: '=='Doctor'' from 'user.user_type=='Doctor'' -
Aggregate number of likes for each day within period
I am building a REST Api on Django RF which represents a very basic social network. I have a model Post that has a value Likes which is related to a User by many to many through a Like model. My models: class Post(models.Model): content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='posts') likes = models.ManyToManyField(CustomUser, related_name='likes', through='Like') class Like(models.Model): author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) liked_on = models.DateTimeField(auto_now_add=True) I need to aggregate a likes statistics for each day within a given period. For example, a request looks like this analytics/?date_from=2020-05-15&date_to=2020-05-17 And I need give something like this: [{ 'date': 2020-05-15, 'likes': 5, }, { 'date': 2020-05-16, 'likes': 7, }, { 'date': 2020-05-17, 'likes': 10, }] How can I do that in Django? Should I query a Post model that has likes as just a list? Or Likes model? And what query should be? -
How to filter by known parameters in Django?
I have several parameters with values that you can select for filtering. The fact is that the admin can add other parameters and their values should also go to the get request and be processed on the server. It looks something like this: Country -checkbox- USA -checkbox- Germany Resolution -checkbox- 1920x1080 -checkbox- 5120x ... Other options .... That is, I have several filters there and it will look something like this: products = Product.objects.filter(Q(country=request.GET.get('country') || Q(resolution=request.GET.get('resolution')) But how to make the parameters by which dynamic become dynamic? -
Django 404 page not recognized
I've placed a 404.html page in my root templates directory, but whenever an invalid URL is requested, the default error text is given. Strangely in production, "Internal Server Error" is displayed, while "Not Found. The requested resource was not found on this server." is displayed on localhost. Debug is set to false in both cases. app/templates/app/404.html: {% extends "app/base.html" %} {% block page_header %} <h1>404</h1> <h2>The page you requested is not available.</h2> <i class="far fa-meh"></i> {% endblock page_header %} -
Error in shell django core.exceptions.ImproperlyConfigured:
The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. this kind of error is coming out while using class based view in urls.py file in blog apps from django.urls import path from .views import ( ArticleListView, ArticleDetailView, ) app_name = 'articles' url_patterns = [ path('', ArticleListView.as_view(),name='article-list'), ] views.py from django.shortcuts import render from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, DeleteView ) from .models import Article # Create your views here. class ArticleListView(ListView): template_name ='articles/article_list.html' queryset = Article.objects.all() #<blog>/<modelname>_list.html models.py from django.db import models from django.urls import reverse # Create your models here. class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField(blank=True,null=True) active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("articles:article-list", kwargs={"id": self.id}) -
Not able to create a SignUp page using Django
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model. views.py def SignUpView(request): if request.method == 'POST': user_form = SignUpForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): new_user = user_form.save(commit=False) new_profile = profile_form.save(commit=False) new_profile.user = new_user userName = new_user.username password = new_profile.password1 new_user.save(commit=True) new_profile.save(commit=True) user = authenticate(username = userName, password = password) login(request, user) return redirect('blog-home') else: user_form = SignUpForm() profile_form = ProfileForm() context = { 'user_form': user_form, 'profile_form': profile_form, } return render(request, 'user/signup.html', context=context) forms.py: class SignUpForm(UserCreationForm): class meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class meta: model = Profile fields = ['user', 'email'] models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # img = date_of_birth = models.DateField(blank=True, null=True) bio = models.CharField(blank=True, max_length=500) location = models.CharField(blank=True, max_length=50) email = models.EmailField(unique=True, max_length=200) def __str__(self): return f'Profile for {self.user.username}' It is displaying an error message on the signup page as : ValueError at /signup/ ModelForm has no model class specified. -
User exists but not able to authenticate using simpleJWT and Django Admin
When trying to authenticate a user created through a view in DRF Browsable API, I get No active account found with the given credentials The view: class MyUserCreate(APIView): def post(self, request, format='json'): serializer = MyUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The serializer: class MyUserSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=MyUser.objects.all())], min_length=5, max_length=20 ), password = serializers.CharField( required=True, max_length=256 ) class Meta: model = MyUser fields = ('username', 'password') def create(self, validated_data): password = make_password(validated_data['password']) user = MyUser.objects.create_user(validated_data['username'], password) return user The password is being hashed. At this stage, went on to the admin page and tested to login there too with the created account and got Made sure the custom user model had is_active, is_superuser and is_staff and checked if that would fix the issue but it didn't. class MyUserManager(BaseUserManager): def create_user(self, username, password, **extra_fields): user = self.model( username=username ) user.is_staff=True user.is_active=True user.is_superuser=True user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(username, password, **extra_fields) class MyUser(AbstractBaseUser): objects = MyUserManager() class Meta: # managed = False db_table = 'user_entity' user_id = models.AutoField(primary_key=True, … -
the reason why i get in Django, an empty query-set
def Cart(request): if request.user.is_authenticated: customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=True) items=order.orderitem_set.all() print(items) else: items=[] context={"items":items} return render(request,'store/Cart.html',context) i'm trying to show some orderitems in the Cart template but nothing appears so i tried to print the items and i get a an despite in the admin pannel i assisgned in an order some orderitems -
Obtain a specific data from my model - Django
I'm trying to understand how to obtain some data from my models. I have a model like this, class Device(models.Model): dev_id= models.CharField(max_length=16, primary_key=True, unique=True) dev_name = models.CharField(max_length=20, unique=True) fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE) def __str__(self): return self.dev_eui If for example one of my devices has the dev_id like "lop7576", I want to obtain two data, its dev_name and its fleet_id. If I do the following I obtain all the info from this device, jq1 = Device.objects.filter(dev_id="lop7576") But how can I obtain only this two values in string/int format directly? Thank you very much. -
How to decide what to return in def __str__(self) function in Django?
While creating model for Webpage in models.py class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name Here we returned self.name. Why not self.url. Are these attributes that are returned some sort of primary keys? -
Create a schedule in Django
I’m working on Django project “management system for clinic” and I have no idea how to create a schedule for doctors. For example administrator makes an appointment for patient. I want him to see a schedule of doctor and which time is placed or free. As I understand I should create model “Time” and connect it with a doctor, but I don’t really know what should I do after this. Thanks for your help! -
How can i make div contents responsive?
I'm developing an app with a ready html template, but i have a problem in how the homepage is displayed on mobile. I'm a very beginner in html and css so i need a little help. I think the problem is the "sub_content" so i tried changing its width but that didn't work. Thanks in advance Page displayed on my laptop Page displayed on mobile HTML code CSS code -
How to submit form using REST API for Django backend with CSRF enabled?
I'm trying to submit form to Django Web app using Java Rest Client. It doesn't work at all, I have no idea why. I was able to login using my client. I took csrftoken and sessionid cookies from login response I do submit form and provide csrfmiddlewaretoken=cookies.csrftoken.value I send csrftoken and sessionid cookies along with request. DJango backed doesn't recognise me and redirects to login. Why? I managed to figure out that for GET requests I need to send only sessionid cookie. DJango redirects to login if Cookie 'csrftoken' is sent along with GET request. What do I do wrong? It should be so trivial... -
Which ORM syntax to join three tables in Django?
I have the following three Models (tables) in my Django project: class Tool(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.CharField(db_column='Name', unique=True, max_length=50) class Flow(models.Model): id = models.AutoField(db_column='Id', primary_key=True) Toolid = models.ForeignKey(Tool, models.DO_NOTHING, db_column='ToolId') name = models.CharField(db_column='Name', unique=True, max_length=50) class Task(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.CharField(db_column='Name', max_length=50) FlowId = models.ForeignKey('Flow', models.DO_NOTHING, db_column='FlowId') I want to make ORM query that returns all info of Technology, Flow, and Task together that are related to each other (i.e. JOIN method in SQL queries). For example, I want to get something like this: [ { Tool name: ... Flow name: ... Task name: ... } { Tool name: ... Flow name: ... Task name: ... } ... ... ] Do you know what ORM sentence should I write to get that output? I really want to get the result from all of the three tables (not only from two of them)! It would be really appreciated if you provide me with the syntax related to my tables I provided above. Thanks a lot! -
how to display the dynamic data in html page
how to send data to club.html dynamically changing with user. how to achieve this. I stuck here. I don't know where is the mistake please help me. club.html <div class='container'> <p class="newlycreated">Prisimax Welcomes you {{user.username}} <img src={{user.userprofile.userphoto.url}} id="ownimg"></p> <br> <p style="margin-left: 100px;">Your LEVEL: {{Clubmember.level}} </p> <p style="margin-left: 100px;">Your cash <i class="fas fa-wallet"></i> : {{Clubmember.usermoney}}</p> </div> views.py class club(View): template_name = "club.html" def get(self,*args,**kwargs): if self.request.user.userprofile.Isclubmem: club_member = Clubmember.objects.filter(user=self.request.user.userprofile) context = { 'club_member': club_member } return render(self.request,'club.html',context=context) return render(self.request,'club.html') def post(self, *args ,**kwargs): if self.request.user.userprofile.Isclubmem: if self.request.method == 'POST': self.request.user.userprofile.userphoto = self.request.FILES.get('image') self.request.user.userprofile.phone_number = self.request.POST.get('userphonenumber') self.request.user.userprofile.Isclubmem = True club_member = Clubmember.objects.create( user = self.request.user.userprofile, refer = refgen(), ) club_member.save() self.request.user.userprofile.save() return redirect('core:home') else: return redirect('/paytmpay') -
How do I create links in Django such that other users can't access them?
I'm pretty confused about how do I prevent users' from accessing the data of other users. The case at hand : I'm creating a Notes + To-Do app in which a user logs in, creates their notes and tasks. But I'm not sure how to create links to those notes such that they aren't accessible by other users. In the To-Do app, how do I keep the tasks of one user unique to them? Similarly for the note app, how do I achieve that? -
How to add a string to my blog post path instead of integer with get_absolute_url in django?
I'm working on a simple blog project and have been following Corey Schafer on YouTube. In the tutorials, he creates new blog posts with integers (e.g. /blog/1, /blog/2, and so on), but I would like to create my post path with strings (like blog/my-blog-post, /blog/new-blog-post). I'm pretty new to python and django and I've tried some things with little luck. Any tips on how to do this? Models: class BloggPost(models.Model): tittel = models.CharField(max_length=100) innhold = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='blogg_foto') def __str__(self): return self.tittel def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Urls: from django.urls import path from .views import BloggPostListViewHome, BloggPostListView, BloggPostDetailView from . import views path('blogg/<int:pk>/', BloggPostDetailView.as_view(), name='bloggpost-detail'),