Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PYTZ dataobject is not being handled ok by the pendulum library
I have a 2 datetimes from "America/Santiago" timezone: 2022-09-04 00:00:00 2022-09-04 01:00:00 In "America/Santiago" they usually change the hour on the 4th Sept. This is at 2022-09-04 00h they say it is 2022-09-04 01:00:00. But this year because of elections the change of hour was delayed one week. So there is no change of time on the 4th. I need to convert the chilean time to UTC. Therefore: By using an updated version of pytz library, i succeed to convert this to a datetime object in "UTC": 2022-09-04 00:00:00-04:00 2022-09-04 01:00:00-04:00 The old version i was using did not had this into count because did not know about it. The problem is that i want to generate too and end time so the script i am reviewing from my department is using the following pendulum library: def my_next_hour(datetime_obj): //datetime_obj=2022-09-04 00:00:00-04:00 new_dt = pendulum.instance(datetime_obj).add(hours=1) return new_dt The output i get is: 2022-09-04T02:00:00-03:00 2022-09-04T02:00:00-03:00 As it can be seen, on the first record i do not know why it changes the -4 to -3. Anyway at the end it does the job. But as a consequence in the second record i do not get the plus hour. So i am asking to … -
I can't get the user to create session in Django
I'm doing a custom Login, using an AuthenticationForm, and I redefine the dispatch function to Authenticate it, so far so good, the problem is to create the session, I'm redefining the "form_valid" function, including the login function but I can't pass the "user" " to have django create the user's session. I try to get it from the "form" but I get this error. 'WSGIRequest' object has no attribute 'form' I have tried changing the methods def form_valid(self, form): login(self.request.POST.Pform.get_user()) return super().form_valid(form) -
Returning a list from a Django table query
Could someone help me with the last step of a query in a Django view please. I have two tables. class Item(models.Model): class Meta: verbose_name_plural = 'Items' name = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Select(models.Model): item = models.ForeignKey('Item', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name Basically, Item is a category. Entries in the Select table reference Item as a category, Item can be either 'metrics', 'consumption' or 'demographics'. I want to retrieve all of the entries from the table Select which are in the 'demographics' category. I have the following code: list-to-pass = Select.objects.filter(item__name='demographics').values() This returns the following: <QuerySet [{'id': 1, 'item_id': 3, 'name': 'Age Breakdown'}, {'id': 2, 'item_id': 3, 'name': 'Work Status'}, {'id': 3, 'item_id': 3, 'name': 'Occupation'}, {'id': 4, 'item_id': 3, 'name': 'Industry'}, {'id': 5, 'item_id': 3, 'name': 'Nationality'}, {'id': 6, 'item_id': 3, 'name': 'Education'}, {'id': 7, 'item_id': 3, 'name': 'Commuting'}, {'id': 8, 'item_id': 3, 'name': 'Leave Home'}, {'id': 9, 'item_id': 3, 'name': 'Travel Time'}, {'id': 10, 'item_id': 3, 'name': 'Car Ownership'}, {'id': 11, 'item_id': 3, 'name': 'Internet'}, {'id': 12, 'item_id': 3, 'name': 'Affluence'}]> but what I would like is something like: ['Age Breakdown','Work Status','Occupation','Industry','Nationality','Education','Communting', 'Leave Home','Travel Time', 'Car Ownership','Internet', … -
'error : can only concatenate str/tuple(not "tuple/str) to str/tuple' error in adding fields to UserCreationForm
i tried to add new fields to UserCreationForm with using CustomUserCreationForm but i get this error TypeError:can only concatenate str(not"tuple") to str and when i change the field to str i got the other one, here is my code: forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationform(UserCreationForm): #new UsercreationForm class Meta(UserCreationForm): #new meta for UserCreationForm model = CustomUser fields = UserCreationForm.Meta.fields + ('age',) class CustomUserChangeForm(UserChangeForm): #new UserChangeForm model = CustomUser fields = UserChangeForm.Meta.fields +('age',) admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): #new UserAdmin to change defualt model add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email','username','age','is_staff',] admin.site.register(CustomUser,CustomUserAdmin) models.py: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True,blank=True) idk whats wrong with code can u help pls? -
Exception Value: Field 'id' expected a number but got 'create-room'
I am stuck with this error and cant' seem to figure out the solution. I was following a YouTube course on channel called "Traversy Media" and it's title is "Python Django 7 hour course" and this part is around 01:39 min into the video "CRUD" section. this is the home.html file {% extends 'main.html'%} {% block content %} <h1>Home PAGE</h1> <div> <a href="{% url 'create-room' %}">Create room </a> <div> {% for room in rooms %} <div> <span>@{{room.host.username}}</span> <h4> {{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a> </h4> <small>{{room.topic.name}}</small> <hr /> </div> {% endfor %} </div> </div> {% endblock content %} There is a 'create room' link in the home page and this link redirects to a room-form.html file below which is a template for creating and updating a room. {% extends 'main.html' %} {% block content %} <div> <form method="post" action=""> {% csrf_token %} <input type="submit" value="Submit" /> </form> </div> {% endblock content %} here is the urls.py file from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('room/<str:pk>/', views.room, name='room'), path('create-room/', views.createRoom, name='create-room'), ] here is the views.py file from django.shortcuts import render from .models import Room # Create your views here.= def home(request): … -
Post called in another HTML w django
So I have a form in a Home1.html, this form has submit that creates a file and lets you download it. But now, and this is the part I'm unsure of, I have created another button next to the "Download" that's called "list" this guides you to a Home2.html, this HTML has a grid (made w bootstrap) with the parameters that were filled before. I want every user that has pressed the submit button on this "Home1.html",I want the data they have submitted (I thought using my existing post method) to fill the missing blocks on the grid. for example if someone input their name Dylan in the previous form, on Home2.html I want the grid missing spaces to fill w this data name: user input (think of an excel sheet, name in A1,A2 the input) -
load template tags from module that is not a django app
wondering if there's a way to load template tags from a module that is not a django app. Templates are on s3 and our custom loader reads templates just fine from s3, but the {% load my_template_file %} call of the template cannot find the tag library (it's not registered, because django doesn't know where to find it). Of course, the solution would be to convert the module to a django app, and add that app to INSTALLED_APPS and to the loaders path, but I'm hoping for something that would allow an arbitrary folder from a module to be the lookup path for tags? -
Can I use mysql connector used in python , in django to connect to MySQL database
I am currently connecting django with MySQL using mysqlclient module,can I use mysql connector which is used in python to connect with MySQL database, here in django to enter deal with MySQL database I didn't actually tried it.did anyone have tried it -
Django derive model field based on other field value
I have a CustomUser model class Account(AbstractBaseUser): email = models.EmailField(verbose_name = "email", max_length = 60, unique = True) username = models.CharField(max_length = 30, unique = True) I am using a User creation form to register new users as follows, class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length = 60, help_text = "This will be your login.") class Meta: model = Account fields = ("email", "username", "password1", "password2") What I want to do is remove the "username" from the form fields, so fields = ("email", "password1", "password2") And then when the user submits the form, I wish to insert a value into the username field based on the email provided by the user, for e.g. email = abc@xyz.com, then username = abc. How do I do this? -
Django site on aws nginix server with supervisor and gunicorn [closed]
Hello everybody I have a issue. I deploy site on aws it is working properly. Than i host godaddy domain so i added that domain name in Allowed Hosts. www.mysite.com and mysite.com. when i go to the site with mysite.com it is working , but if i add www.mysite.com it is not working some times writes that it is now allowed host and sometimes not responding. have anyone idea ? I try restart reboot and everything like that. In /etc/ngninx/site-availabe/default file also written this domain names, if it sense, but cant repair it . -
Django does not create superuser using Custom User Model
I am creating a Django application and I am implementing a Custom User Model for authentication. I cannot create a superuser. I get an error saying RecursionError: maximum recursion depth exceeded while calling a Python object. I am using Django version 4.1.2. Here is my User Model class CustomAccountManager(BaseUserManager): def create_superuser(self, user_name, email, first_name, last_name, phone, 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_superuser(email=email, user_name=user_name, first_name=first_name, last_name=last_name, phone=phone, password=password, **other_fields) def create_user(self, user_name, email, first_name, last_name, phone, password, **other_fields): if not email: return TypeError(_('Please provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, first_name=first_name, last_name=last_name, phone=phone, **other_fields) user.set_password(password) user.save() return user class Users(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) user_name = models.CharField(max_length=100, unique=True) email = models.EmailField(_('email address'), max_length=50, unique=True) phone = models.CharField(_('phone number'), max_length=50, unique=True) status = models.CharField(max_length=50) role_id = models.ForeignKey("Roles", on_delete=models.CASCADE, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name', 'last_name', 'phone'] class Meta: ordering = ['id'] def __str__(self): return self.user_name … -
Get unique elements in an array and add the value if same element is found - django
<QuerySet [{'product': 6, 'quantity': 1}, {'product': 6, 'quantity': 10}, {'product': 7, 'quantity': 2}, {'product': 9, 'quantity': 3}] > how to get unique elements only in the array and add the quantity if same product is found. In the above eg: there are two "product: 6", so the new QuerySet should be <QuerySet [{'product': 6, 'quantity': 11}, {'product': 7, 'quantity': 2}, {'product': 9, 'quantity': 3}] > -
Filter QuerySet from a given list of indexs
I have a list of index i want to extract from another queryset. >>> allLocation = loc.objects.all() >>> allLocation <QuerySet [<loc: loc object (1)>, <loc: loc object (2)>, <loc: loc object (3)>, <loc: loc object (4)>, <loc: loc object (5)>]> >>> UserIndex = [0,3,4] >>> >>> allLocation[UserIndex[1]] <loc: loc object (4)> >>> filteredUser = ? I can query a single item but I want to filter all the index item from my allLocation given the index number in a list ( UserIndex ) and store it in filteredUser -
I am trying to show some extra data in my DRF via serializer
So I have created a shopping cart table with quantity, user, and product. I want to show all the detail of the product in the response. This is my models file for the shopping cart This is my serializer file this serializer shows all the detail of the user but the product id is showing twice if remove 'product' from the serializer then while I do the POST request it says that the NOT NULL constraint is violated And this is my response here I don't want to show 'product' and don't want any problem in POST request too if it's possible -
Deploying django using Apache and mod_wsgi problem
Was able to create a working Django application and works fine in development (runserver). However, I'm currently stuck with my production build using Apache as the web server. Hope someone can help. Have added the following lines in my httpd.conf file: # ServerName localhost:80 # use this if you're running this on a VirtualBox VM or PC ServerName localhost:8000 # Django Project LoadFile "C:/Users/Anton/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/Anton/Documents/Dad/PythonVirtual/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/Anton/Documents/Dad/PythonVirtual" WSGIPythonPath "C:/Users/Anton/Documents/Dad/Complere" WSGIScriptAlias / "C:/Users/Anton/Documents/Dad/Complere/Complere/wsgi.py" <Directory "C:/Users/Anton/Documents/Dad/Complere/Complere/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ "C:/Users/Anton/Documents/Dad/Complere/static/" <Directory "C:/Users/Anton/Documents/Dad/Complere/static/"> Require all granted ` Without the additional lines mentioned above, I can see the apache service running in background. However, once above lines have been added, the apache server is in stopped status. Below is the log file content. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 8692:tid 408] AH00455: Apache/2.4.54 (Win64) mod_wsgi/4.9.4 Python/3.10 configured -- resuming normal operations [Mon Nov 07 22:01:09.941909 2022] [mpm_winnt:notice] [pid 8692:tid 408] AH00456: Apache Lounge VS16 Server built: Jun 22 2022 09:58:15 [Mon Nov 07 22:01:09.941909 2022] [core:notice] [pid 8692:tid 408] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Mon Nov 07 22:01:09.945903 2022] [mpm_winnt:notice] [pid 8692:tid 408] AH00418: Parent: Created child process 6552 Python … -
How to remove from QuerySet by some condition
I have a queryset, and lets say its described like this (in JSON) { [ { "name": "Alex", "01_correct_answers": 1, "02_correct_answers": 3, }, { "name": "John", "01_correct_answers": null, "02_correct_answers": null, }, { "name": "James", "01_correct_answers": null, "02_correct_answers": 3, }, ] } Here 01 and 02 are subject IDs. And I have a list of these IDs, now how can I loop through this list of IDs and check the queryset if the correct_answers of the student for these subjects are not null, if they are null (all subjects), just remove them from the queryset. And finally I would like to have a filtered queryset like below: { [ { "name": "Alex", "01_correct_answers": 1, "02_correct_answers": 3, }, { "name": "James", "01_correct_answers": null, "02_correct_answers": 3, }, ] } How can I achieve this in Django? -
AttributeError: module 'dotenv' has no attribute 'dotenv_values'
I am installed django-environ and try to get my values from .env. I haven't problems when I run server in local, but when i run my app with docker-compose up --build I have error: Traceback (most recent call last): File "/usr/bin/docker-compose", line 33, in <module> sys.exit(load_entry_point('docker-compose==1.29.2', 'console_scripts', 'docker-compose')()) File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 81, in main command_func() File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 200, in perform_command project = project_from_options('.', options) File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 60, in project_from_options return get_project( File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 148, in get_project config_data = config.load(config_details, interpolate) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 442, in load service_dicts = load_services(config_details, main_file, interpolate=interpolate) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 558, in load_services return build_services(service_config) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 537, in build_services return sort_service_dicts([ File "/usr/lib/python3/dist-packages/compose/config/config.py", line 538, in <listcomp> build_service(name, service_dict, service_names) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 526, in build_service service_dict = finalize_service( File "/usr/lib/python3/dist-packages/compose/config/config.py", line 947, in finalize_service service_dict['environment'] = resolve_environment(service_dict, environment, interpolate) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 732, in resolve_environment env.update(env_vars_from_file(env_file, interpolate)) File "/usr/lib/python3/dist-packages/compose/config/environment.py", line 38, in env_vars_from_file env = dotenv.dotenv_values(dotenv_path=filename, encoding='utf-8-sig', interpolate=interpolate) AttributeError: module 'dotenv' has no attribute 'dotenv_values' I have my .env file: SECRET_KEY="django-insecure-t+)^5*1syzvs=p%tiy324)zxz26$ra!+__8)y8=!hnyjn_cg3m" My docker-compose: version: "3.10" services: postgres: image: postgres:13.3 env_file: - ./support/.env volumes: - .:/docker-entrypoint-initdb.d ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U alexey_razmanov -d support_app_db"] interval: 10s timeout: 5s … -
django eccomerce prodcut name not showing in file
i am creating a new django eccomorce website now in product detail page here is my code the problem is i cant see product name correct in html page problem with first() when i use first then only product name showing but all products have same name i have 8 producs in my page eight product name same to first just like overwriting also i cant use for loop with first() i will add some pics urls.py path('collection/<str:cate_slug>/<str:prod_slug>',views.product_view,name="productview"), views.py def product_view(request,cate_slug,prod_slug): if (Category.objects.filter(slug=cate_slug, status=0)): if (Products.objects.filter(slug=prod_slug, status=0)): products = Products.objects.filter(slug=prod_slug, status=0).first() context = {'products':products} else: messages.error(request,"no such product found") return redirect("collection") else: messages.error(request,"no such category found") return redirect("collection") return render(request,"product_view.html",context) models.py class Products(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) slug = models.CharField(max_length=150, null=False, blank=False) product_name = models.CharField(max_length=150, null=False, blank=False) product_image = models.ImageField( upload_to=get_image,null=True,blank=True) description = models.TextField(max_length=500,null=False,blank=False) original_price = models.IntegerField(null=False,blank=False) selling_price = models.IntegerField(null=False,blank=False) status = models.BooleanField(default=False,help_text="0=default , 1=Hidden") trending = models.BooleanField(default=False,help_text="0=default , 1=Trending") meta_title = models.CharField(max_length=150,null=False,blank=False) meta_keyword = models.CharField(max_length=150,null=False,blank=False) meta_description = models.CharField(max_length=400,null=False,blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product_name productview.html {% block content %} <h1>{{ products.product_name }} </h1> {% endblock %} i just want correct product name for every category i stucked here in morning helping are appreciated thank you all for helping till … -
Django admin keeps the users data when removed from the like-list
I created a like button with django which saves the information of the users who clicked the button. When the same user click the button again and 'unlike' it, the counter beside the button goes back to the number before the user clicked and the user is supposed to be removed from save-list. However, the data set in the admin keeps the user listed as one of whom clicked the button once after they clicked it. The code shows no error and I have no idea where to modify to remove the users who 'unlike'd from the data set because the code post_obj.liked.remove(user) seems running properly. My models.py is: class Post(models.Model): posts = models.CharField(max_length=420, unique=True) slug = models.SlugField(max_length=42) date_created = models.DateTimeField(auto_now_add=True) liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') def __str__(self): return str(self.posts) LIKE_CHOICES = ( ('like', 'like'), ('unlike', 'unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='like', max_length=10) My views.py is: def likes(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if request.user.is_authenticated: if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == … -
Django Channels. How to avoid exception RuntimeError: Task got Future attached to a different loop?
I use `Django Channels` with `channel_layers` (`RedisChannelLayer`). Using Channels I only need to get live messages from signals when post_save event happens. I try to send a message from the `signals.py` module. The fact that the message is sending properly, I got it successfully in the console, but then **disconnection** from the socket happens **with an Exception**: `RuntimeError: Task got Future attached to a different loop.` It refers to *`...redis/asyncio/connection.py:831`* All my settings were done properly in accordance with the documentation. My project also uses `DRF`, `Celery`(on Redis), `Redis` itself, `Daphne` server. I only try to implement it with Debug=True mode, let alone production. I have no idea what happens and how to solve it. Here are snippets from my code: consumers.py class LikeConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = "likes" await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'type': 'chat', 'message': message })) signals.py channel_layer = get_channel_layer() @receiver(post_save, sender=Like) def new_like(sender, instance, **kwargs): async_to_sync(channel_layer.group_send)( 'likes', { "type": "chat_message", "message": "1212341324, 213413252345" } ) script.js const likeSocket = new WebSocket(url); likeSocket.onmessage = function(e) { let data = JSON.parse(e.data); console.log(data); }; -
django eccomerce website problem with first() function
when i use first() it repeting first name to all products also when i use first() for loop is not working i just want to display correct name for products i really stucked here helping are appreciated thank you -
Import "django.urls" could not be resolved from source
I am expecting the solve please help me I m new at that. I tried searching but I could not find anything. -
Could not parse the remainder: ':' from '1:'
TemplateSyntaxError at /challeges/1 Could not parse the remainder: ':' from '1:' This is my challege.html {% if month == 1: %} <h1>This is {{ text }}</h1> {% else: %} <p>This is {{ text }}</p> {% endif %} This is my views.py def monthly_challege(request, month): return render(request, "challeges/challege.html", { "text": "Your Url Is Empty", month: month }) This is my urls.py urlpatterns = [ path("<month>", views.monthly_challege), ] -
How to stop DRF's ModelSerializer to use model field's default value?
I'm stucked with this strange bug(?) with BooleanField. While partial_update, serializer is always set all boolean values to false, if it is not set in request. My models.py class User(AbstractUser): agree_email = BooleanField(blank=True) agree_sms = BooleanField(blank=True) serializers.py class UserChangeSerializer(serializers.ModelSerializer): class Meta: model = AZUser fields = "first_name", "agree_email", "agree_sms" When i trying to set agree_email to True - it's validating as {'agree_email': True, 'agree_sms': False}, and if i try to set agree_sms to true - it'll validate it as {'agree_email': False, 'agree_sms': True} and update User object respectively. How to prevent such behavior of DRF? -
Table without primary key and two FKs - Django
I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have a single table (foos_bars) with 2 FKs only. bar_id (FK) | foo_id (FK) 1 |1 2 |2 When I use the endpoint, I get: django.db.utils.OperationalError: (1054, "Unknown column 'foos_bars.id' in 'field list'") There is a way to work with?