Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django: "Post.author" must be a "User" instance error
I am trying to assign username to author field in Post model , Django spews out the following error: "Post.author" must be a "User" instance. model: class Post(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='',null=True,blank=True) image_url = models.CharField(max_length=200,default=None,null=True,blank=True) date = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, null=False, blank=False,on_delete=models.CASCADE) categories = models.ManyToManyField(Category) published = models.BooleanField() def __str__(self): return self.title view: @login_required def new_post(request): # Add a new post if request.method != 'POST': # No data submitted, create a blank form form = PostForm() else: # Post data submitted, process data form = PostForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user.username new_post.save() return redirect('elogs:posts') #Display a blank or invalid form context = {'form':form} return render(request,'elogs/new_post.html',context) form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','content','image','image_url','published'] widgets = { 'title': forms.Textarea(attrs={'placeholder': 'Title..'}), 'content': forms.Textarea(attrs={'placeholder': 'What is on your mind?'}), 'categories': forms.TextInput() }enter code here -
FieldError at /answer/ Cannot resolve keyword 'i' into field. Choices are: add_time, answer, detail, id,
believe it or not I've been here for 4 hours trying to get this to work, so yes, I've been trying to make a question and answer site, currently trying to make an answer form so I can send in answers to the question that I am currently viewing, trying to get the id of the question so I can attach the answer into that, but I'm getting this error, I'm sure I wrote 'id' but it thinks I wrote 'i'... What? Anyway here is the traceback, please tell me what I am doing wrong, thanks. Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/answer/ Django Version: 4.0.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.humanize', 'forum', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'crispy_forms', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'vote'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) File "/home/titsnium/Documents/eduzec/forum/views.py", line 78, in … -
do we need a package like spatie for Permissions and Roles with Django
i am new with Django, and I have been using Spatie with Laravel for a long time, my question is does I need to use something like it with Django? or even do I need to do anything about multi roles and permission with Django since the admin panel looks perfect and completed already..... Thanks -
Why does order_by in Django is ignoring spaces while sorting with name alphabetically?
Image of the issue Suppliers.objects.all().order_by('name') -
Django Paginate_by not displaying proper pagination
Hello i have a page using paginate_by 10, and instead i'm getting only 9 elements per page, even tho in the element inspector i see 10 grid spaces my for cicle is just being able to fill 9 out of 10 then it goes into the next page. Views.py class VideoListView(generic.ListView): model = Video template_name = 'index.html' context_object_name = 'video_list' paginate_by = 10 def get_queryset(self): return Video.objects.order_by('-date') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category_list'] = Category.objects.all() return context -
In Django how to delete, retrieve, and update a table when calling an external API
I was wondering what the correct way is to delete one table in the database and update it with new information from an external API every time that is called. Basically, whenever the API would be called, the information saved in the table should be substituted by new one. my views.py from rest_framework import generics from .serializers import TickerSerializer from ticker.models import Ticker import requests import logging logger = logging.getLogger(__name__) class TickerList(generics.ListAPIView): serializer_class = TickerSerializer queryset = Ticker.objects.all() class TickerRetrieve(generics.RetrieveUpdateDestroyAPIView): serializer_class = TickerSerializer queryset = Ticker.objects.all() lookup_field = 'id' def get_object(request): url = 'https://api.kraken.com/0/public/Ticker?pair=1INCHEUR,1INCHUSD' response = requests.get(url) data = response.json() for key in data['result']: if isinstance(data['result'][key], int): continue crypto_data =data['result'][key] ticker_data = Ticker(crypto = (key), crypto = (key), a_0 = (crypto_data.get('a')[0]), ) ticker_data.save() my models.py from django.db import models class Ticker(models.Model): id = models.AutoField(primary_key=True) # auto increment field crypto = models.CharField(blank=True, null=True, max_length=25) a_0 = models.FloatField(null=True, blank=True, default=None) my serializers.py from rest_framework import serializers from ticker.models import Ticker class TickerSerializer(serializers.ModelSerializer): class Meta: model = Ticker fields = ( 'id', 'crypto', 'a_0', ) my urls.py from .views import TickerList, TickerRetrieve from django.urls import path app_name = 'ticker' urlpatterns = [ path('', TickerList().as_view(), name='ticker'), path('tickerretrieve/', TickerRetrieve().as_view(), name='tickerretrieve'), ] Every time that i … -
Django IntegrityError (1048, "Column 'newuser_id' cannot be null")
I'm new to Django. Basically, I'm trying to create a password confirmation field, but when I try to submit the form I get this error: (1048, "Column 'newuser_id' cannot be null") models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from datetime import datetime from django.core.validators import MinLengthValidator from .CHOICES import * from django.utils.translation import gettext_lazy as _ from django.db import models # Create your models here. country_choice = COUNTRY_CHOICE class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, first_name, password, **other_fields) def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=50, validators=[MinLengthValidator(8)], unique=True) first_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False) # day = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(31)], blank=False) # month = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(12)], blank=False) # year = models.IntegerField(validators=[MinValueValidator(1942), MaxValueValidator(2017)], blank=False) # gender model GENDER_CHOICES = ( ('M', 'Male'), … -
How to update password of Auth user in django rest framework
I'm new to django rest framework. I'm implementing a simple login, signup and forgot password functionality using reactJs and django. All the functionalities are working fine but the problem I'm facing is that, on signup, the passwords in the database encrypted and then saved in the database but on updating password, the new password saved exactly same as user typed it. I want it also be encrypted in the database just like it encrypted in signup. My serializer.py file from dataclasses import fields from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields='__all__' # fields = ('username','first_name', 'last_name', 'email') class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token','first_name', 'last_name','email', 'username', 'password') My views.py file from asyncio.windows_events import NULL from django.http import Http404, HttpResponseRedirect from django.contrib.auth.models import User from rest_framework import viewsets, permissions, status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from .serializers … -
Django - template doesnt render HTML, only see source code
I try to go with https://www.youtube.com/watch?v=PtQiiknWUcI&t=3500s however I have stucked after 56:30 minutes step, when I have created new home.html template file. I have copied and pasted old home.html code into new one however after server refresh I can see only source code. Can you please advice?Thanks -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I do not understand
from django.db import models # Create your models here. class Topic(models.Model): text = models.CharField(max_length=200) data_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text ` I do not understand, what is mean django.core.exceptions.AppRegistryNotReady? ` -
how do I get the value or pk of a model in django?
hey I'm a beginner in django and trying to make a question and answer project using class based views, im trying to make an answer form to write an answer for the question, the posting and all is already good. but I don't know how to make it so that it posts the answer object to the correct question object in class based views, how do I do this? Please explain in a very simple way for a beginner, thank you! -
Mocking django recaptchafield
When testing a view, how do I bypass the recaptcha field inside my user create form? This test fails after adding the captcha field from django-recaptcha, with the validation error "Error verifying reCAPTCHA, please try again." This (incorrect) approach tells me "app.views" is not a package, but I can do "from app.views import *" without error @mock.patch("vividqr.myapp.views.CustomUserCreationForm.fields.ReCaptchaField.validate") def test_outside_signup_ok(self): client = Client(HTTP_HOST='vividqr.local') client.post(reverse('myapp:outside'), data={'action': 'signup', 'signup_form-first_name': 'FirstName', 'signup_form-last_name': 'LastName', 'signup_form-captcha': 'dummystring', 'signup_form-email': 'test24@example.com', 'signup_form-password1': 'DifferentPassword420', 'signup_form-password2': 'DifferentPassword420'}, follow=True) self.assertEqual(User.objects.filter(email='test24@example.com').count(), 1) -
Django DatField returns null value every time I register information
I have a model that registers a project information which have start date and end date but when I submit those information, the value of start date and end date is null their value never saved to the database. Here is my model.py class Project(models.Model): project_name = models.CharField(max_length=255, blank=False) created_by = models.ForeignKey( Employee, related_name='employee', on_delete=models.CASCADE) status = models.CharField( max_length=50, choices=PROJECT_STATUS_CHOICES, default=COMING_STATUS, null=True, blank=True ) start_date = models.DateField( null=False) end_date = models.DateField( null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.project_name Here is the list of project data { "id": 1, "created_by": "Teshome", "project_name": "Teshome", "status": "Coming", "start_date": null, "end_date": null, "created_at": "2022-04-15T12:16:31.045887Z", "updated_at": "2022-04-15T12:16:31.045887Z" }, { "id": 2, "created_by": "Teshome", "project_name": "Babi", "status": "Ended", "start_date": null, "end_date": null, "created_at": "2022-04-15T12:30:03.332208Z", "updated_at": "2022-04-15T12:30:03.332208Z" }, I did not use any frontend framework to register project information I just did it from Django Admin. How can I solve this Isuue? Thanks -
How to get value of defaultdic in JS (Django framework)?
I want to use chartjs to display a chart on the page (Django framework). views.py chart_data = defaultdict(<class 'int'>, {'3': 2, '2': 2, '8': 2, '5': 2, '7': 1}) context["chart_data"] = chart_data home.html <script type="text/javascript"> var my_chart = "{{ chart_data }}"; </script> my_chart.js const data = { labels: labels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: Object.values(my_chart), }] }; But it didn't work. When I used console.log(Object.values(my_chart)) to check, I found that what Object.values(my_chart) returns was ['d', 'e', 'f', 'a', 'u', 'l', 't', 'd', 'i', 'c', 't', '(', '&', 'l', 't', ';', 'c', 'l', 'a', 's', 's', ' ', '&', '#', 'x', '2', '7', ';', 'i', 'n', 't', '&', '#', 'x', '2', '7', ';', '&', 'g', 't', ';', ',', ' ', '{', '&', '#', 'x', '2', '7', ';', '3', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', 'x', '2', '7', ';', '2', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', 'x', '2', '7', ';', '8', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', …], it just disassembled each letter and symbol … -
How to sort a list(queryset) containing a manytomany field
Python: 3.9.10 Django: 4.0.3 I am using Django Paginator. To sort the data on each page, and only the data on that page, I am converting my queryset to a list and then sorting the list by its key using attrgetter(). My model contains two ManyToManyFields and so I cannot sort it using the standard sorted() method as I receive the error message: TypeError: '<' not supported between instances of 'ManyRelatedManager' and 'ManyRelatedManager' I think I understand why this is happening - sorted() cannot compare two lists (manytomanyfields) against each other and determine which is greater than or less than - so therefore the list(queryset) cannot be sorted in this way. I imagine I probably have to iterate through the list(queryset), get the first value of the manytomanyfield and then somehow sort everything by that. I am not what the best way is to go about doing this. models.py class DataExchange(models.Model): name = models.CharField(unique=True, max_length=15, null=True) def __str__(self): return self.name class DataSource(models.Model): name = models.CharField(unique=True, max_length=10, null=True) def __str__(self): return self.name class Provider(models.Model): name = models.CharField(unique=True, max_length=15, null=True) exchange = models.ManyToManyField(DataExchange, related_name="providers_exchange") source = models.ManyToManyField(DataSource, related_name='providers_source') score = models.IntegerField(null=True) def __str__(self): return self.name Paginator helper function: def paginator_helper(request, paginator): page … -
How to turn a LightGBM model into a web-app?
everyone, I'm new to Machine learning. Recently, I've built a LightGBM model with 30 features. The model works great. Then, my boss wants me to build a web app for this model which allows the user to input the data and return the prediction to the users. He wants a web app like this project: http://wwwnew2.hklii.hk/predictor. I don't know where to start. In my understanding, I might need an input form then pass the values to the model and then return the prediction to the front-end. However, I totally had no idea how to get started. Here are my questions: How can I pass the value to the trained model and return the result? Should I build the front-end with Django? Is there any python library that allows me to build such a web app easily? Should I host the web app on a VM? Thank you very much. -
Filtering user post and shared post on his account wall
How best can i filter a user's post and shared post on user's account wall! with what i have done, when i visit let say my account wall i don't see my shared post but but rather when i visit the account of the original post that was shared i see that my shared post on his account with the original post and my shared post with is name! why am i getting this effect as i want to be able to have all the shared post on my wall and not the other way round? def account_view(request,*args, **kwargs): context = {} user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) try: post_list = Post.objects.filter(username=account) except Post.DoesNotExist: post_list = Post.object.prefetch_related('postimage_set').order_by("date_posted") posts = post_list.all() try: friend_list = FriendList.objects.get(user=account) except FriendList.DoesNotExist: friend_list = FriendList(user=account) friend_list.save() friends = friend_list.friends.all() -
Filtering in my project not working (django restframework)
I'm building APIs with django and I have been trying to implement filtering into the system but the filter option just brings back all the list. Below is my codes view.py from unicodedata import name from django.shortcuts import render, get_object_or_404 from rest_framework import generics, status from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from .serializers import DailySalesSerializer, DailySalesCreateSerializer from .models import DailySales # Create your views here. class DailySalesListView(generics.GenericAPIView): serializer_class = DailySalesSerializer queryset = DailySales.objects.all() name = 'Daily Sales List' filter_backends = (DjangoFilterBackend,) filterset_fields = ('id', 'customername','havepaid', 'datesold', 'itemsold') def get(self, request): sales = DailySales.objects.all() serializer = self.serializer_class(instance=sales, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) I have also added django_filters to my settings.py -
Django Template Variable not found
I'm pretty new to Django and I'm really struggling with this issue. So if anyone can help I would be very grateful :). Basically everytime I access the path to reach one specific profile, the variable {{profile.user.username|default="Not found"}} does not get recognised and the default value is the output. When I access another path like profile_list, the right output comes up from the same variable. Both html pages(profile.html and profile_list.html) inherit from base.html. Any idea where the issue might be or where I should be looking into? -
How to preserve values from multiple select objects on one form using Django HTMX
Picture a todo list with multiple columns that include Priority, Status, AssignedTo, Due Date. Now I have a form below this list that has a ChoiceBox (and in one case ModelChoiceBox) for each of these conditions. So set Priority to 2, and the list refreshes to just 2's. Now select Status = 3 for example, and the two filters should be combined. In my View however, they are not. The value of the most recent Select comes over, but he previous value is reset to None. Here is a slimmed down example with just 2 Selects. class FilterForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.attrs = {"novalidate": '', } priority = forms.ChoiceField( choices=PRIORITY_CHOICES, widget=forms.Select(attrs={ 'hx-get': reverse_lazy('change-priority'), 'hx-target': '#tasklist', 'hx-trigger': 'change' }) ) status = forms.ModelChoiceField(queryset=TaskStatus.objects.all(), widget=forms.Select(attrs={ 'hx-get': reverse_lazy('change-priority'), 'hx-target': '#tasklist', 'hx-trigger': 'change' }) ) Here is a scaled down View: def change_priority(request): filtform = FilterForm(request.POST) form = NotePadForm(request.GET) fpriority = form["priority"].value() fstatus = form["status"].value() tasklist = get_object_or_404(TaskList, owner=request.user) if tasklist: tasks = Task.objects.filter(priority=fpriority, status=fstatus) filtform = FilterForm() context = { "tasks": tasks, "filtform": filtform, "form": form } return render(request, "planner/partials/tasklist.html", context) return HttpResponse("Error - No Valid Task List") So changing Priority sends the correct Selected value to … -
Django Project on Port 80 while running on localhost?
I want to run a local django project on port 80 instead of default 8000 while running the project on localhost. -
How to add the name of an uploaded file to a model in django
I am learning django. I am stuck with this problem. I have created a form in which a user uploads a text file and selects a gender. The user is also supposed to write the name of the text file in the text box. sample output In the backend I want to save the name of the text file along with the gender in a model. The purpose of doing this is because when multiple users will use the application, I should know which user selected what gender so that I can produce the desired output. As I have already mentioned the user needs to type the name of the file, I was thinking is it possible to get the name of the file from the uploaded file and then save it to the model so the user need not type the name of the file and hence no text box. Here is the link to my git repository - https://github.com/AnshulGupta22/auto_generation.git Can someone please tell me how to do it? As I already said I am new to django and some help will be appreciated. -
Erreur: HTTPConnectionPool(host='dnode2', port=9864): Max retries exceeded with url: /webhdfs
I'm trying to read a file on my hdfs server in my python app deployed with docker, during dev, I don't have any problem, but in prod there are this error : Erreur: HTTPConnectionPool(host='dnode2', port=9864): Max retries exceeded with url: /webhdfs/v1/?op=OPEN&namenoderpcaddress=namenode:9000&offset=0 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1af13d45d0>: Failed to establish a new connection: [Errno -2] Name or service not known')) Note that I use an address IP not that "dnode2" name and neither use that port!! please any body can help -
Integrity Error - Foreign Key constraint failed when uploading image to data bank Django Imagefield
This is part of my class in models.py class Account(AbstractBaseUser): email=models.EmailField(verbose_name="Email", max_length=60, unique=True) nick_name=models.CharField(verbose_name="Nickname", max_length=20) null=True, profile_img=models.ImageField(upload_to=upload_location,null=True, blank=True, default=None) #necessary date_joined=models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login=models.DateTimeField(verbose_name="last login", auto_now_add=True) is_admin=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) is_superviser=models.BooleanField(default=False) this is my receiver in models.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def post_save_compress_img(sender, instance, *args, **kwargs): if instance.profile_img: picture=Image.open(instance.profile_img.path) picture.save(instance.profile_img.path, optimize=True, quality=30) settings.py: AUTH_USER_MODEL = 'account.Account' whats wrong in here that I run into an integrity error? -
i get this error OperationalError at /admin/accounts/student/
hey guys i work withe django framework i had the error OperationalError i have to class with same fields class Student(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) First_Name = models.CharField('First Name', max_length=30, null=True, blank=True) Last_Name = models.CharField('Last Name', max_length=30, null=True, blank=True) ID_Number = models.CharField('Id Number', max_length=30, null=True, blank=True) Phone = PhoneNumberField('Phone',null=True) class Meta: verbose_name_plural = "Students" def __str__(self): return str(self.user) class Lecturer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) First_Name = models.CharField('First Name', max_length=30, null=True, blank=True) Last_Name = models.CharField('Last Name', max_length=30, null=True, blank=True) ID_Number = models.CharField('Id Number', max_length=30, null=True, blank=True) Phone = PhoneNumberField('Phone',null=True) class Meta: verbose_name_plural = "Lecturers" def __str__(self): return str(self.user) and i add new field to my Student and also to Lecturer classes the field is Phone = PhoneNumberField('Phone',null=True) and yes i did the commands: python manage.py makemigrations python manage.py migrate after that i get prove that every thing is update: Operations to perform: Apply all migrations: HomePage, accounts, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. but when i run the runserver and after the i go to the url http://localhost:8000/admin add i go the Lecturers data every things work great i have new field Phone but when i try …