Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why am I not able to filter events by month in django?
I have below django views to filter events based on month class FilterByMonthView(ListView): model = Event template_name = 'your_template.html' context_object_name = 'filtered_data' def get_queryset(self): month = self.kwargs.get('month') month = str(month).zfill(2) # Construct a date range for the specified month start_date = datetime.strptime(f'2023-{month}-01 00:00:00', '%Y-%m-%d %H:%M:%S') end_date = datetime.strptime(f'2023-{month}-01 23:59:59', '%Y-%m-%d %H:%M:%S') # Assuming end of the month # Filter the data based on the date range queryset = Event.objects.filter( event_date__range=(start_date, end_date) ) return queryset Below is my models.py class Event(models.Model): emp_id = models.IntegerField(max_length=50) event_type = models.CharField(max_length=50) event_date = models.DateTimeField() email = models.EmailField() def __str__(self): return f"{self.event_type} {self.event_date} {self.email}" In the django admin page when I am creating an event, I see below output ID Emp id Event type Event date Email 6 67565 Birthday Nov. 15,2010,6 a.m. jhad@jhsd.com Below is the urls.py for project level and app level respectively urlpatterns = [ path('admin/', admin.site.urls), path('emp/', include('EVENTS.urls')), ] from django.urls import path from .views import FilterByMonthView urlpatterns = [ path('filter/<int:month>/', FilterByMonthView.as_view(), name='filter-by-month'), ] HTML looks as below <!DOCTYPE html> <html> <head> <title>Filtered Events</title> </head> <body> <h1>Events for the Selected Month</h1> <ul> {% for event in filtered_data %} <li>{{ event.event_date }} - {{ event.event_name }}</li> <!-- Display other event attributes as needed … -
How do I make the openai api message output in real time?
I'm trying to make a chatbot website. I want the ai's response to be sent chunk by chunk as soon as the chunk is processed, but the output message is being sent all at once on my website. In the terminal, I made it so that the response gets outputted as soon as each chunk is processed, and it worked for the terminal using this code: print(chunk_message['content'], end='', flush=True) But I can't figure out how to make it send as soon as each chunk was processed in my website. I made the browser console print out the times when the chunks were sent to it and they all were apparently sent at the same time. I know that is the problem but I can't figure out how to solve it. Here is my github link for the full code: https://github.com/Breath3Manually/chat-bot.git the important files are the consumers.py file and the chat_view.html file any help will be appreciated, I've spent 2 days trying to fix this <3 I want the ai's response to be sent chunk by chunk as soon as the chunk is processed, but the message is being sent only after all of the chunks have finished processing. -
NGINX UWSGI Permission Denied
Using: Ubuntu 20.04 Python 3.8.10 not using virtualenv. Everything is installed globally. I am trying to deploy a Django website on my VPS using uwsgi and nginx but I keep getting 502 error code. In nginx error.log file I have the following exception: *543 connect() to unix:/root/uwsgi/testproject.sock failed (13: Permission denied) while connecting to upstream The project structure is as follows: wsgi file: root/html/testproject/testproject/wsgi.py uwsgi ini: root/uwsgi/sites/testproject.ini socket: root/uwsgi/testproject.sock Note: I have used the root user during the whole setup. testproject.ini [uwsgi] chdir=/root/html/testproject wsgi-file=/root/html/testproject/testproject/wsgi.py socket=/root/uwsgi/testproject.sock chmod-socket=666 uid=www-data gid=www-data master=True pidfile=/tmp/project-master.pid vaccum=True max-requests=5000 daemonize=/tmp/uwsgi.logs /etc/nginx/sites-available/testproject server{ listen 80; server_name 85.31.237.228; location / { include uwsgi_params; uwsgi_pass unix:/root/uwsgi/testproject.sock; } } Can someone please help me figure out what I'm doing wrong? I have switched between 666 and 644 for chmod param but nothing worked. -
Python:Selenium finding element by XPATH by Django If statement class
I am trying to test a simple notification page in Django using Selenium to test whether notifications are marked as read. To do this, I have a notifications model which includes a boolean field, defaults to False if the notification hasn't been read. I want to be able to show that some are read, and some aren't by using css. I have the following html which works exactly as I want it to when running runserver; however, I can't get it to pass the tests. {% for notification in notifications %} <div class="notification-card {% if notification.read == False %} unread {% else %} read {% endif %}"> <h3>Badge Awarded</h3> {% endfor %} Then in my Selenium test file, I have the following line. If I hardcode the class in the html file, this test passes, but if I try to add Django for the class selector, the test fails. unread_notifications = self.browser.find_element(By.XPATH, '//div[@class="notification-card unread"]/h3') self.assertEqual(unread_notifications.text, 'Badge Awarded') How do I find the desired element? I have already tried using '//div[contains(@class="unread")]/h3' to no avail. I don't want to hardcode the html because the next test is to find the read notifications. -
Django: ClearableFileInput does not support uploading multiple files -- error?
I am trying to add an option to add multiple files at once in a form, and I found the solution with using ClearableFileInput: class Image(models.Model): id = models.AutoField(primary_key=True) post = models.ForeignKey(BlogEntry, on_delete=models.CASCADE) photo = models.ImageField(null=True, blank=True, upload_to='media/') photo_objects = models.Manager() class ImageForm(forms.ModelForm): class Meta: model = Image fields = ['photo', ] widgets = { 'photo': forms.ClearableFileInput(attrs={'multiple': True}) } However, when I tried to run it using runserver, it gave me an error. Can somebody help me with fixing it? Is there another straightforward option to add multiple files? I tried to search difference solutions on the internet but some of them did not work while others looked too complicated for my current level. I also see this option to upload multiple files in the official documentation (https://docs.djangoproject.com/en/dev/topics/http/file-uploads/) but I wonder if there is a simpler version in which I would not need to create MultipleFileInput and MultipleFileField by myself. Is there something in Django to enable multiple file upload? -
Trying to migrate from Vue-cli to Vite and Components are not Rendering
I have this django and vue 2 application that is currently using vue-cli and webpack loader but I'm trying to migrate the application to vite. I've gone through what I thought would be all the steps. But when I build and run the dev server and have it communicate with the backend, loading it at localhost:8000, although I see all the vue, js, sass, scss components in the networks tab in dev tools returning 200s I don't see anything show up on the page. Anyone ever face this issue before and know what the issue might be? I've followed all the steps from here and was expecting my components to at least render even if there were some errors that I could worry about troubleshooting after, but instead I see 200s for all my components in the network tab but a blank page. My django endpoints are also not showing up in the terminal or network tab. -
Django-Project folder not found inside a script
I'm having a problem including the settings.py file inside a script. My django project uses a script that fills my database with models. To do this, I use following code: # some imports import <project_name>.settings as app_settings from <app_name>.models import ( .... different models) settings.configure( INSTALLED_APPS=app_settings.INSTALLED_APPS, DATABASES=app_setttings.DATABASES ) django.setup() # read file external file and insert data (model) into the db.sqlite3 database The problem is that the module <project_name> can not be found. The above script is in the project directory. The error is thrown in line import <project_name>.settings as app_settings. : ModuleNotFoundError: No module named '<project_name>' Why can't the script include the project folder? -
Paypal Webhook get Email from request data
I am building an endpoint that receives the webbhooks from paypal. At the event PAYMENT.SALE.COMPLETED a mail should be sent. Of course the email has to be filtered from the request data. However, neither in the request.META nor in the eventbody such information can be found. The situation is different for the BILLING.SUBSCRIPTION.ACTIVATED. There you can find the email in the eventbody. But since this is a completely different event and not an indicator for a successful payment, I cannot use this. Does anyone have experience with this, how to use the email forPAYMENT.SALE.COMPLETED to get the email of the Paypal user account? -
How is the value of page column under wagtailcore_page table is populated. How is it decided which page will have what value?
I need to insert bulk pages in wagtail database and I need to find out how is the value of path column under wagtailcore_page table is decided? I tried looking into the database but couldn't map the value of this path column to the path of the page. -
Django - Image not supporting while DEBUG = False
In my Django project some of dynamic image files is not served when I change the DEBUG mode into False, other static files are working properly the issue that I faced only in the case of some images. For example if I have 20 products contain 20 images maybe 5 or 6 will not show rest of them have issues. How can I solve the issue in a production time I can't make DEBUG in True mode, for static serving I have used WhiteNoise module. -
How to display the errors of the "Django authentication system" in a template?
I use Django authentication system for my project. According to the structure of the template, I have to use the form fields individually. This is signup template: <section class="form-container___auth"> <div class="form-container"> <img src="{% static './images/white-logo-all.png'%}" /> <p class="title">ثبت نام دانش آموز</p> <form class="form" method="post" action=""> {% csrf_token %} <div class="input-group"> <label for="email">ایمیل</label> <input type="email" name="{{ form.email.name }}" id="{{ form.email.id_for_label }}" placeholder="" value="{{ form.email.key }}"> </div> <div class="input-group"> <label for="email">نام کاربری</label> <input type="text" name="{{ form.username.name }}" id="{{ form.username.id_for_label }}" placeholder="" value="{{ form.username.key }}"> </div> <div class="input-group"> <label for="password">رمز عبور</label> <input type="password" name="{{ form.password1.name }}" id="{{ form.password1.id_for_label }}" placeholder="" value="{{ form.password1.key}}"> </div> <div class="input-group"> <label for="password">تکرار رمز عبور</label> <input type="password" name="{{ form.password2.name }}" id="{{ form.password2.id_for_label }}" placeholder="" value="{{ form.password2.key}}"> </div> <button type="submit" class="sign">ثبت نام</button> </form> <div class="social-message"> <div class="line"></div> <p class="message">ورود</p> <div class="line"></div> </div> <p class="signup">.اگر حساب کاربری دارید ، وارد سایت شوید <a rel="noopener noreferrer" href="{% url 'login' %}" class="">ورود</a> </p> </div> </section> Django authentication system detects the errors and provides them to you, but I don't know how to display the errors of each field in my template. Now how can display the errors? -
Django cannot run because GDAL is loading wrong libtiff version
I am unable to run Django on my MacOS Ventura. Looking at the error, I think GDAL is unable to load libtiff library. I did some investigation, I do have libtiff installed. % otool -L /opt/homebrew/lib/libgdal.dylib | grep libtiff /opt/homebrew/opt/libtiff/lib/libtiff.6.dylib (compatibility version 7.0.0, current version 7.1.0) If looking at the error, I think its trying to load libtiff.5.dylib, but I have libtiff.6.dylib. How can I get GDAL to load the installed libtiff ? % python manage.py runserver Watching for file changes with StatReloader 2023-10-01 17:14:00,801 INFO Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
yfinance python package size is too big
I am trying to host a Django Application with yfinance as one of the package using pythonanywhere.com which gives 500 MB free space.There are only three packages Django, plotly and yfinance but the size of built is crossing more than 500mb. I noticed that there are many packages installed simultaneously when yfinance is installed. Are they all necessary or is there any way to avoid them. -
How To booking time (start pm) and (end am)
I am creating a site for booking stadiums by the hour, so the user books the stadium for a period of time, for example: John books Stadium X from 9 pm to 11 pm.... No other user can book the same stadium on the same day and at the same time The code in front of you is working very, very correctly But only one problem happens when the booking starts in the evening and ends in the morning It's when the user, for example: John, books the stadium from 11 pm to 2 am If someone else booked the same stadium on the same day, an example of: Lion makes a reservation for the same stadium from 12 AM to 1 am the system accepts this reservation and does not prevent it (Considering it's considered the same period for user John ) This is not true because there will be more than one user who has booked the same period I don't know the solution my models : class OpeningHours(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) pitche = models.ForeignKey(Pitche,on_delete=models.DO_NOTHING) made_on = models.DateField() from_hour = models.TimeField() to_hour = models.TimeField() timing = models.CharField(max_length=50,choices=timing) def __str__(self): return f"{self.pitche}-{self.from_hour} to {self.to_hour}" class Meta : ordering =['-made_on'] … -
Run celery app in django docker container
I have a Django project which uses docker and docker-compose, and I want to use Celery within the Django project. I have followed Celery docs to create an app, a task and connect it with RabbitMQ broker. This is my celery.py file, in the same dir as the settings.py file: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") backtest_app = Celery("backtest_app") # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. backtest_app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django apps. backtest_app.autodiscover_tasks() Also I have set the Celery app config in the settings.py file: # CELERY config CELERY_BROKER_URL = "amqp://rabbitmq:5672" CELERY_BROKER_USER = "user" CELERY_BROKER_PASSWORD = "pass" CELERY_BACKEND = "rpc://" CELERY_BROKER_POOL_LIMIT = 100 CELERY_TASK_DEFAULT_QUEUE = "backtest_queue" CELERY_TASK_DEFAULT_EXCHANGE = "backtest_exchange" CELERY_TASK_DEFAULT_ROUTING_KEY = "backtest_queue" CELERY_ENABLE_UTC = True CELERY_TIMEZONE = "UTC" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_RESULT_BACKEND = "django-db" CELERY_CACHE_BACKEND = "django-cache" Now, I have this code in the Dockerfile of the backend: FROM python:3.10.8-alpine # Prevents Python from writing pyc files to disc: ENV PYTHONDONTWRITEBYTECODE … -
Docker Containers are not able to communicate
here is my docker-compose file : version: '1' services: frontend: image: 'ccm-frontend' build: context: ./client dockerfile: Dockerfile.Dev ports: - 3000:3000 networks: - codecommunitymusic-network environment: NODE_OPTIONS: --max-old-space-size=4096 NEXTAUTH_URL: http://frontend:3000 __NEXT_PRIVATE_PREBUNDLED_REACT : next APP_URL: http://frontend:3000 NEXT_PUBLIC_BACKEND_URL: http://backend:8000 BACKEND_URL: http://backend:8000 depends_on: - backend backend: image: 'ccm-backend' build: context: ./server dockerfile: Dockerfile.dev ports: - 8000:8000 networks: - codecommunitymusic-network depends_on: - database environment: - DJANGO_SUPERUSER_USERNAME=admin - DJANGO_SUPERUSER_EMAIL=admin@example.com - DJANGO_SUPERUSER_PASSWORD=password - SECRET_KEY= - DATABASE_NAME=postgres - DATABASE_USER=postgres - DATABASE_PASS=password - DATABASE_HOST=database - EMAIL_HOST_USER=hello@gmail.com - EMAIL_HOST_PASSWORD=demo_password volumes: - ./server:/app command: > sh -c " python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" database: image: postgres:16-alpine environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: password networks: - codecommunitymusic-network ports: - 5432:5432 networks: codecommunitymusic-network: driver: bridge Frontend is unable to make api calls to backend I tried localhost and also tried service name but requests are getting failed Error its gives me : xhr.js:251 GET http://backend:8000/users/abhishek net::ERR_NAME_NOT_RESOLVED I tried including them in same network also restarted the instance. I went into frontend and curl to backend and its works but from the browser its not working. -
How do I keep all query parameters intact when changing page in django?
I have this issue with pagination: <a href="{{ request.get_full_path }}{% if request.GET %}&{% else %}?{% endif %}page={{ page_obj.previous_page_number }}">previous</a> It works fine, but every time I click on it it adds one more ?page=1 at the end of URL, so url looks like this after few clicks: example/something?query_params=5&page=1&page=1&page=1&page=1 I know why that happens, it's because I hardcoded it into url, but I have to use get_full_path because I need other query parameters together with page. So basically I want all those query params but WITHOUT page=something being added each time I change page. I need only one page query parameter. -
Django nested serializer instance update issue
I am building a django backend rest API and I have an issue which I can't overcome. So I have two models. #1 Company Model: class Company(models.Model): companyID = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) email = models.CharField(max_length=50) description = models.CharField(max_length=500,blank=True, null=True) #2 Employee Model: class Employee(models.Model): JOB_CHOICES = [ ('software engineer', 'Software Engineer'), ('data scientist', 'Data Scientist'), ('product manager', 'Product Manager'), ('data analyst', 'Data Analyst'), ('software developer', 'Software Developer'), ('ui/ux designer', 'Ui/UX Designer'), ('manager', 'Manager'), ('software tester', 'Software Tester'), ('accountant', 'Accountant') ] employeeID = models.BigAutoField(primary_key=True) companyID = models.ForeignKey(Company, db_column="companyID", related_name='employees', on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.CharField(max_length=50) age = models.IntegerField(default=18, validators=[MinValueValidator(18), MaxValueValidator(100)]) job = models.CharField(max_length=50, choices=JOB_CHOICES, default='software engineer') cv = models.CharField(max_length=500, null=True, blank=True) I would like to create a serializer which is get one object like this (from PUT request): { "companyID": 3, "name": "New Name", "email": "test@gmail.com", "description": "test", "employees": [ { "employeeID": 31, "name": "Test USER", "email": "goreca7783@fulwark.com", "age": 18, "job": "data analyst" } ] } and it should update all of the values in the database. Here's my serializer this is how I tried to solve this problem which is almost works. class CompanyEmployeeSerializer(serializers.ModelSerializer): # Serialize the employees of a company employees = EmployeeCompanySerializer(many=True) class Meta: model = … -
Passing parameters to a database backend in Django
I have created a Django backend to manage databases. I need to be able to pass values to it based on the user. I have created this Middleware for that purpose, and it behaves correctly in the development environment, PyCharm. The question is, will it work correctly in production if it's running with multiple threads since I'm using Gunicorn? My code, I use the session variable SESSION_B2J for this, and from the backend, I call get_session_b2j to retrieve values: import threading def get_session_b2j(): thread_local = B2jBakendMiddleware.thread_local if hasattr(thread_local, 'session_b2j'): return thread_local.session_b2j def set_session_b2j(session_b2j): thread_local = B2jBakendMiddleware.thread_local thread_local.session_b2j = session_b2j class B2jBakendMiddleware(object): thread_local = threading.local() def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.thread_local.session_b2j = request.session.get('SESSION_B2J') response = self.get_response(request) return response -
I need to show funds according to the category selected in point 1
django application, I need to take categories from the database (step 1) and based on them (step 3) show the funds that belong to these categories, how can this be done in js? Thank you models.py TYPE = ( (1, 'fundacja'), (2, 'organizacja pozarządowa'), (3, 'zbiórka lokalna'), ) class Category(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class Institution(models.Model): name = models.CharField(max_length=64) description = models.TextField() type = models.IntegerField(choices=TYPE, default=1) category = models.ManyToManyField(Category) def __str__(self): return self.name @property def type_name(self): return TYPE[self.type - 1][1] class Donation(models.Model): quantity = models.IntegerField() categories = models.ManyToManyField(Category) institution = models.ForeignKey(Institution, on_delete=models.CASCADE) address = models.CharField(max_length=64) phone_number = models.IntegerField() city = models.CharField(max_length=64) zip_code = models.CharField(max_length=10) pick_up_date = models.DateField() pick_up_time = models.TimeField() pick_up_comment = models.TextField() user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) is_taken = models.BooleanField(default=False) taken_timestamp = models.DateTimeField(auto_now=True) views.py class DonationView(LoginRequiredMixin, View): def get(self, request): all_category = Category.objects.all() all_institution = Institution.objects.all() context = { 'all_category': all_category, 'all_institution': all_institution, } return render(request, 'form.html', context) def post(self, request): try: institution_name = request.POST.get('organization') institution = Institution.objects.get(name=institution_name) categories_names = request.POST.getlist('categories') categories_ids = [] for category_name in categories_names: category = Category.objects.get(name=category_name) categories_ids.append(category.id) quantity = request.POST.get('bags') address = request.POST.get('address') phone_number = request.POST.get('phone') city = request.POST.get('city') zip_code = request.POST.get('postcode') pick_up_date_str = request.POST.get('data') pick_up_date = datetime.strptime(pick_up_date_str, '%Y-%m-%d').date() pick_up_time … -
error as Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'
` from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): profile_picture = models.ImageField(upload_to='profile_pics/', blank=True, null=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=255, blank=True) date_of_birth = models.DateField(null=True, blank=True) interests = models.CharField(max_length=255, blank=True) twitter_profile = models.URLField(blank=True) instagram_profile = models.URLField(blank=True) linkedin_profile = models.URLField(blank=True) class Meta: db_table = 'tbl_profile' def __str__(self): return self.username class UserRelationship(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='following') followed_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='followers') class Meta: db_table = 'tbl_followers' def __str__(self): return f"{self.user.username} follows {self.followed_user.username}" ` error: HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'. accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'accounts.CustomUser.user_permissions'. basically i want create user profile by inherit abstractuser class in django models.py for my social chat app, but i m not able to migrate this models with above error. -
I am working with django and i got some errors .why BaseAuthentication from restframework showing me errors what is the reasons
Showing this after running server .What is the reason ? This is the code i wrote. I think i wrote the code correctly i asked the G.P.T it saying that you need to create custom authentications. can anyone explain what is the reason behind it? -
Sending email through Django, incorrect page rendered
Basically I am trying to send email to users when they click the activation link sent to their email when registered. The below code works fine and user does get the email however after email.sent() its goes to activation_invalid.html instead of activation_success.html def account_activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) current_site = get_current_site(request) subject = 'Activation Successful!' message = render_to_string('app/auth/email/account_activation_success_email.html', { 'user': user, 'domain': current_site.domain, }) to_email = user.email email = EmailMessage(subject, message, to=[to_email]) email.send() return render(request, 'app/auth/activation_success.html') else: return render(request, 'app/auth/activation_invalid.html') When I remove email.send(), activation_success.html is rendered like it should in the first place. -
How to redirect user to welcome page by authenticating its enterd details in login form with db in django
I have created a model for signup form and allowed user to enter its data ,which is further stored in DB , then I have created a login form which take the detail of user like email and password and then verifies it in db and allows user to redirect to welcome page I am attaching my code details INDEX.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>What do u want/?</h1> <button class="submit"><a href="{% url 'login' %}">login</a></button> <button class="submit"><a href="{% url 'signup' %}">signup</a></button> </body> </html> LOGIN.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST"> {% csrf_token %} <input type="email" id="email" name="email"><br> <input type="password" id="password" name="password" value="password"> <button class="submit">submit</button> </form> </body> </html> SIGNUP.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" > {% csrf_token %} <input type="text" id="name" name="name" value="name"><br> <input type="email" id="email" name="email" value="email"><br> <input type="password" id="password" name="password" value="password"> <button class="submit"><a href="{% url 'welcome' %}">submit</a></button> </form> </body> </html> WELCOME.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome {{name}}</h1> </body> </html> VIEWS.PY from django.shortcuts import render,redirect from .forms import Detailsform from … -
How can i get variable by call model and don't create new variable
I created a Mutation for my django project . At first i create an input class for get variable and now i want to send them without input class and make a new way like serializer in REST This is my Schema import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = '__all__' class DataInput(graphene.InputObjectType): name = graphene.String() class CategoryCreate(graphene.Mutation): class Arguments: input = DataInput(required=True) category = graphene.Field(CategoryType) @staticmethod def mutate(parent, info, input=None): category_instance = Category.objects.create(name=input.name) return CategoryCreate(category=category_instance) class Mutation(graphene.ObjectType): create_category = CategoryCreate.Field() Schema = graphene.Schema(query=GameQuery, mutation=Mutation)