Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions' did not migrate i'm making crm and i
I'm making this crm and i got this error i will share code with you i'm taking this video and i got this error https://www.youtube.com/watch?v=fOukA4Qh9QA&t=4925s ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. leads.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. leads.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. Setting.py Here's my settings code """ INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' AUTH_USER_MODELS = 'leads.User' models.py Here's my models code from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
create a multidimensional array field in Django model
I get multidimensional arrays must-have array expressions with matching dimensions error from Django when I try to insert data into my model, below is my model and the data format i have effect = ArrayField( ArrayField( models.IntegerField( blank=True, null=True ), null=True, ), null=True, default=list, size=11 ) and this is my data format: "effect": [null,[95],[20],[0],[0],[0],[0],[0],[0],[0],[0]], this is how my data looks and my current model field structure isnt working, i will like a solution to problem please. -
Having issues with Django-Graphene
i built my own content management system here: https://github.com/bastianhilton/Alternate-CMS and I have added graphql support recently with Django-Graphene and updated my models, schema.py. However as I try to run a query, i'm getting the below message. Any direction would be greatly appreciated. { "errors": [ { "message": "relation \"shop_addresscountry\" does not exist\nLINE 1: ... \"shop_addresscountry\".\"is_shipping_country\" FROM \"shop_addr...\n ^\n" } ], "data": { "allAddresscountry": null } } -
Reduce bandwidth loading Django page
Building a Django newsfeed project. The main page of the site is going to be a two timelines adjacent to each other, consisting of a twitter feed and a reddit feed respectively. Utilizing the inspect module in chrome I noticed it was taking upwards of 5.5s to load the page. I have a services script running on page refresh that makes api calls to reddit and twitter, fetches data, then creates a Post object for that particular post/tweet. The post object I modeled in models.py. I then grab all the Post objects and pass them through the view as a context variable. In my template I iterate through the Posts and embed the raw html onto the page. In what way can I change the logic/architecture of my project so the page loads quicker, based on current procedures? Any suggests on how to increase efficiency within the context of my project? Here's my code: services.py import praw import tweepy import requests import webbrowser import pprint import json import os import sys import datetime from .models import Post # twitter sys.path.insert( 0, 'C:\\Users\\Nick\\Desktop\\2021 Python\\NBA_Project\\NBAblog\\news') here = os.path.dirname(os.path.abspath(__file__)) # connect to api def tweet_connect(key, secret, access_key, access_secret): auth = tweepy.OAuthHandler(key, secret) auth.set_access_token(access_key, … -
Modify queryset model fields individually and return queryset without saving the models to db
I want to change a specific model field based on other parameters for each model of the queryset. Afterwards, I would return the queryset with adjusted field values, but without altering the database entries. I'm using django-rest-framework and I currently use bulk_update which sadly updates my db recordings of the models: class CustomModelView(viewsets.ModelViewSet): serializer_class = ModelSerializer def get_queryset(self): long = self.request.query_params.get('long') lat = self.request.query_params.get('lat') point = GEOSGeometry(f'POINT ({long} {lat})', srid=4326) city = City.objects.filter(poly__contains=point) if len(city) == 1: max = CustomModel.objects.aggregate(Max('value')) models= CustomModel.objects.filter(city__in=city) objs = [] for mod in models: mod .attractivness /= max['value__max'] objs.append(mod ) CustomModel.objects.filter(city__in=city).bulk_update(objs, ["value"]) queryset = models return queryset return CustomModel.objects.none() Here I'd want to normalise each "value" field of each model from the query set by the max value of the query set. How can I update the queryset with new field values and alter the database? -
Django Pytest image upload image unit test
I'm using Django 3.2.6, django-pytest, and factory boy to run automated tests. This is the function I use to make a test image: from django.core.files.uploadedfile import SimpleUploadedFile def test_image(name='test.jpg', size=(250,250)): img = Image.new('RGB', size) content = img.tobytes() # return Django file for testing in forms and serializers return SimpleUploadedFile(name, content=content, content_type='image/jpeg') This is the view being tested: class PhotoCreateView(LoginRequiredMixin, CreateView): model = Photo form_class = PhotoForm success_url = '/' template_name = 'photos/create.html' def form_valid(self, form): new_category = form.cleaned_data['new_category'] if new_category: category = Category.objects.create(name=new_category) form.instance.category = category return super().form_valid(form) Here is the test class: class TestPhotoCreateView: url = reverse('photos:create') def test_photo_create_view_authenticated_user_can_access(self, client, user): client.force_login(user) response = client.get(self.url) assert response.status_code == 200 def test_photo_create_view_unauthenticated_user_cannot_access(self, client): response = client.get(self.url) assert response.status_code == 302 def test_photo_create_view_form_valid_existing_category(self, client, user): client.force_login(user) for _ in range(3): CategoryFactory() category = CategoryFactory() image = test_image() form_data = { 'category': category.pk, 'new_category': '', 'description': 'hello world', 'image': image, } response = client.post(self.url, form_data) print(response.content) photo = Photo.objects.get(description=form_data['description']) assert photo.category == form_data['category'] All of the tests pass except for test_photo_create_view_form_valid_existing_category. i ran pytest --capture=tee-sys and this error was in the image field: <p id="error_1_id_image" class="invalid-feedback"><strong>Upload a valid image. The file you uploaded was either not an image or a corrupted image.</strong></p> … -
django not filter by category name
django cannot filter by category name in url The Problem The Problem MyModels Code Views Code HTML Code URL code -
Serialize data to json formate using native serializer Django
I have this dictionary which I need to pass to another view, knowing that possible ways of doing that are either through sessions or cache, now when I am trying to pass to session it is throwing me an error that data is not JSON serializable probably because I have DateTime fields inside this dictionary session_data = serializers.serialize('json',session_data) error on above statement 'str' object has no attribute '_meta' updated date is somewhat in this format {'city_name': 'Srinagar', 'description': 'few clouds', 'temp': 26.74, 'feels_like': 27.07, 'max_temp': 26.74, 'min_temp': 26.74, 'sunrise': datetime.time(6, 11, 10), 'sunset': datetime.time(18, 43, 59)} -
How to send verification email in django
views.py from django.contrib.auth import authenticate, logout as userlogout, login as userlogin def signup(request): if request.method == "POST": username=request.POST['username'] firstname=request.POST['firstname'] lastname=request.POST['lastname'] email=request.POST['email'] password=request.POST['password1'] if User.objects.filter(username=username).exists() : messages.error(request, "Username already exists.") return redirect(request.META['HTTP_REFERER']) elif User.objects.filter(email=email).exists(): messages.error(request,"An account already exists with this email.") return redirect(request.META['HTTP_REFERER']) else: myuser = User.objects.create_user(username, email, password) myuser.first_name= firstname myuser.last_name= lastname myuser.save() messages.success(request, " Your account has been successfully created.") return redirect(request.META['HTTP_REFERER']) I have to send verification email after signup. I have some methods but it didn't work because it works on forms which is created by django but i have own created form in html and get all the data and then saved it with above method. Has someone have any idea how to send verification email. -
Is there a way to create "tag" system in django?
I am trying to create a e-commerce web app that requires tags to find out the categorized items easily and efficiently in django. Until now I have tried using foreign keys but can't find my way out. Any suggestions are welcomed. -
How to find django objects in a manytomany relation (with a throught)?
I need to find services with pricing for each user. I've defined my models: class User(AbstractUser): """Default user model.""" username = None email = models.EmailField(unique=True) proposals = models.ManyToManyField( Service, through=Pricing, blank=True) class Service(models.Model): name = models.CharField(max_length=50) class Pricing(models.Model): user = models.ForeignKey('users.User', on_delete=models.PROTECT) service = models.ForeignKey(Service, on_delete=models.PROTECT) price = models.IntegerField() In my template, I can get my user with associated proposal with this for loop {% for proposal in object.proposals.all %} {{ proposal }} {% endfor %} I do not have prices but only services names. What am i missing ? -
Read after write does not include written data
I have a simple React client and Django server setup for a todo list. On creating a TODO item a POST request is sent with its data, and after the response is received a GET request is sent to retrieve any updates to the list. However the GET will usually not contain the item just written. I can have the written item added to that list from the client side, but I'm wondering if there is a way to configure the server side so that a request will contain updates of requests responded to before it. For reference here is an MVP of the Django side. The client is just using fetch. I've had the same result using Sqlite and Postgres models.py class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True from django.db import models class Todo(BaseModel): name = models.TextField() views.py import json from django.http import JsonResponse from django.views.decorators.http import require_POST, require_GET from django.views.decorators.csrf import csrf_exempt from django.forms.models import model_to_dict from .models import Todo @require_POST @csrf_exempt def todo_add(request): data = json.loads(request.body) name = data.get('name') new_todo = Todo(name=name) new_todo.save() return JsonResponse({'new_todo': model_to_dict(new_todo, fields=['id', 'name']}) @require_GET @csrf_exempt def todo_list(request): results = Todo.objects.all().values('id', 'name') return JsonResponse({'todo_list', list(results)}) -
How to collect all photos from user in 1 pages Using django
i wanna ask.Im making a website using django.but i wanna make all the photo from the user uploaded was show in 1 spesific pages. How i want to link it? -
How to customise update method for ManyToMany fields in Django Rest Framework
I have a few models with ManyToMany relationships between them and I need to override the create and update method to make the POST and PUT request work in DRF. Here's my code so far: class CreateFolderSerializer(serializers.ModelSerializer): class Meta: model = Folder fields = ("id", "title", "description", "users") def create(self, validated_data): users = validated_data.pop( 'users') if 'users' in validated_data else [] folder = Folder.objects.create(**validated_data) folder.users.set(users) return folder This create method works perfectly. I tried re-creating the same logic for the update method, but it doesn't work: class FolderSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Folder fields = '__all__' def update(self, instance, validated_data): users = validated_data.pop('users') if 'users' in validated_data else [] instance.users.set(users) instance.save() return instance When I send a PUT request, the object does not get modified at all, it gets deleted altogether. Any clue? Thanks a lot. -
How to show django logging and error log in Cloud Run's log?
I'm using Django, uwsgi and nginx in Cloud Run. A Cloud Run service can't show django logging and error log. That's why Error Report can't use ,too. Cloud Run log is like this. This is my settings. Django settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'local': { 'format': "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s" }, 'verbose': { 'format': '{message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'local', }, }, 'root': { 'handlers': ['console'], 'level': 'WARNING', }, 'loggers': { 'users': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } } } uwsgi.ini [uwsgi] # this config will be loaded if nothing specific is specified # load base config from below ini = :base # %d is the dir this configuration file is in socket = %dapp.sock master = true processes = 4 [dev] ini = :base # socket (uwsgi) is not the same as http, nor http-socket socket = :8001 [local] ini = :base http = :8000 # set the virtual env … -
django display objects on all url
MyViews: MyHTMLCode: MyUrl: [The Proablem is do not filter by category name][4] -
why django is using email host user as (from email)
The problem is that (from email) is being used as default email host user. So how to solve this problem? Django version 2.2 contact html template views.py for contact settings.py in Django My contact page The email -
“” value has an invalid format. It must be in the format of YYYY MM DD HH:MM
models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class recommend(models.Model): sno = models.AutoField(primary_key=True) comment= models.TextField() user = models.ForeignKey(User,on_delete=models.CASCADE) timestamp= models.DateTimeField(default=now) def __str__(self): return self.recommend[0:20] + "..." + "by" + self.user.username error importing signals Operations to perform: Apply all migrations: admin, apps, auth, blog, contenttypes, home, sessions, verify_email, videos Running migrations: Applying home.0004_alter_contactme_timestamp...Traceback (most recent call last): File "/storage/emulated/0/imaginecode/manage.py", line 22, in <module> main() File "/storage/emulated/0/imaginecode/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 244, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 140, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 608, in alter_field self._alter_field(model, old_field, new_field, old_type, … -
Filter nested serializers in Django Rest Framework
I have several nested serializers for an institution examination module. I began with term -> class -> student ->classes -> subjects -> exam_categories ->exam_subcategories -> marks. I want to filter the marks in the exam_subcategories inorder to be the marks of an indivual student. Currently each student is returning all the marks list. I have been going through several solutions online but it has not provided me with a way of solving it. Here is the sample models and serializers and output. I want to be able to filter the marks_exam_type to return only that student's marks in that term in that subject in that class in that exam subcategory (Only one object in marks_exam_type) The models user are class Classes(models.Model): year = models.ForeignKey(AcademicYear,on_delete=models.CASCADE) current_term = models.ForeignKey(YearTerm,related_name='current_term',on_delete=models.CASCADE,null=True) terms = models.ManyToManyField(YearTerm,related_name="class_terms",through='YearTermClasses') course = models.ForeignKey(Course,on_delete=models.CASCADE) course_year = models.ForeignKey(CourseYear,on_delete=models.CASCADE,null=True) class_name = models.CharField(max_length=255) class_code = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) school = models.ForeignKey(School,on_delete=models.CASCADE) active = models.BooleanField(default=False) def __str__(self): return self.class_name class Meta: ordering = ['-year__start_date'] unique_together=['year','current_term','course','course_year','class_name'] Marks model class Marks(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) subject = models.ForeignKey(CourseSubject,related_name='subject_marks', on_delete=models.CASCADE) term = models.ForeignKey(YearTerm,related_name="terms_marks",on_delete=models.CASCADE) student = models.ForeignKey(Student,related_name='marks',on_delete=models.CASCADE) exam = models.ForeignKey(ExamSubCategory,related_name='marks_exam_type',on_delete=models.CASCADE) exam_category = models.ForeignKey(ExamCategory,on_delete=models.CASCADE,related_name="marks_exam_category",null=True) classes = models.ForeignKey(Classes,on_delete=models.CASCADE) marks = models.IntegerField() created_by = models.ForeignKey(Profile, on_delete=models.CASCADE) created_date = … -
I have problems to displaying a from of type ModelForm in Django
I'm trying a tutorial about Django forms and drop-down lists but I can't manage to show the form, maybe the tutorial is about an old version of Django, but I tried everything, I don't understand what I'm missing. First my Forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() The model: from django.db import models class Country(models.Model): class Meta: db_table = 'countries' name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): class Meta: db_table = 'cities' name = models.CharField(max_length=30) state_id = models.BigIntegerField(null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class Person(models.Model): class Meta: db_table = 'people' name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name The template: {% block content %} <h2>{% trans "Person Form" %}</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save</button> <a href="{% url 'person_changelist' %}">Nevermind</a> </form> {% endblock %} And finally View.py from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.views.generic.edit import FormView from django.urls import reverse_lazy from .models import Person from … -
how to use {% url %} inside a custom filter in django for displaying a hashtag
Hi i want to display a #hashtag with url in django in the post content.for that i created a simple customer filter.but i have a problem for using the "url tag". tag_name.py: @register.filter(name='mention',is_safe=True) @stringfilter def mention(value): res = "" my_list = value.split() for i in my_list: if i[0] == '#': if len(i[1:]) > 1: <!-- my problem is here --> i = f"<a href="{% url 'recommendation_posts' %}?q={i}&submit=Search">i</a>" res = res + i + ' ' return res html: <p> {{ post.content|mention|safe }}</p> by example:when someone write "I like #python" i want to be rendered as "I like #python" my main problem is this {% url %} is not working inside the templatetags.How can i achieve it thanks. -
React Native - Sending token to Django server
So I have this react native code that sends a token in string format, yes I've checked that var token = getCurrentUser() is a string and I've console.log it to ensure it is a JWT token as well. But on the Django side when I check request.headers.get('Authorization', None) it outputs: 'Bearer [object Object]' what's going on? React Native Code const getPosts = () => { var token = getCurrentUser(); const config = { headers: { Authorization: `Bearer ` + token } }; axios .get(`${url}/posts`, config) .then(response => { console.log(response) setData(response.data); }) .catch(error => { console.log(JSON.stringify(error)); }); } -
How to join multiple model with both onetoone and one to many using select_related?
i have few models namely class Alpha(models.Model): name = models.CharField() class XXX(models.Model): owner = models.ForeignKey(Alpha) class YYY(models.Model): name = models.OneToOneField(Alpha) Now while doing select_related like this test = Alpha.objects.filter(id=pk).select_related('XXX') It gives me Invalid field name(s) given in select_related, choices are YYY I understand that YYY is at OneToOne, so its showing up - but is there a way to fetch XXX also ? or should i use "prefetch_related". But i dont wanna use prefetch as its just making slow queries and meanwhile i have 7 models which needs to be select_related :( -
Deploying Django @ Heroku - Windows Libraries
I'm using some python libraries on my Windows localhost (Django) server and I'd like to host my application online. My app is based on reading Excel files and providing this data on the screen. import win32com.client as win32 import pythoncom I suppose this are WindowsOS libraries only and I couldn't deploy @ Heroku, for being a LinuxOS server. Am I correct? If so, are there other good free Windows servers? Thank you! -
Django framework and chatbot development and integration
I have a question related to Python/Django/Chatbot/Web Development. I want to make a website (Django framework) with an integrated chatbot (using Rasa framework probably). Is that a good approach to use the above stacks? Motive : 1) Website is just for chatbot integration, a generic marketing webpage. 2) Chatbot needs to be basic to direct people to the service they need to go to and should be able to provide link for video calls to the concerned department if needed, store data of the customer and answer basic/generic questions. This is my first attempt at working in the web development/chatbot field.