Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't set multiple forign keys in one table in django models
Actually my code is like, Models.py class Employee(models.Model): employee_code = models.IntegerField(unique=True,primary_key=True) employee_name = models.CharField(max_length=50,unique=True) class LeaveRequest(models.Model): emp_name = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='empl_name') emp_code = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='emp_code',default='') leave_type = models.CharField(choices=( ('CL', 'Casual leave'), ('SL', 'Sick leave'), ('ML', 'Medical leave'), ('Comp off', 'Compensation') ),default='',max_length=20) serializers.py class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class LeaverequestSerializer(serializers.ModelSerializer): class Meta: model = LeaveRequest fields = '__all__' Views.py class Empcreate(CreateAPIView): # permission_classes = [IsAuthenticated] serializer_class = EmployeeSerializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": serializer.data, "message": "User Created Successfully..!", }) class Leaverequest(CreateAPIView): serializer_class = LeaverequestSerializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": serializer.data, "message": "Request Created Successfully..!", }) Actually since i mapped two foreign keys from same table(emp_name and code),there is the problem arriving. whenever i create request in leave request module, emp_name also showing emp_code as shown in the image below. But i want to display the name, can anyone suggest resolution for this, also how can i set different conditions for different leave types, where to create the conditions ? serializers or views? is for loop good option for creating different conditions of leave types? -
html h1 tag no show type
after click no.1 and blank to than page it no show h1 tag enter image description here inspect here enter image description here code html here {% extends "main.html" %} {% block content %} <h1>{{room.name}}</h1> {% endblock content %} code python here i don't know this have problem or not from django.shortcuts import render rooms = [ {'id': 1, 'name': 'Lets learn python!'}, {'id': 2, 'name': 'Design with me!'}, {'id': 3, 'name': 'Fronted develpoers!'}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def room(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'romm': room} return render(request, 'base/room.html', context) -
Django - Contain both register & login views on the same page
I am creating a simple application in Django, where my users can register and login to their accounts. I have both a signup and a login form on my home page, but it doesn't work for logging in or registering: the form won't let the user's create an account or sign into their already existing account. My Register Form: <form action = "" method = "POST"> {% csrf_token %} <input type="email" placeholder="Email" name = "email" /> <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "register">Register</button> </form> My login form: <form action = "" method = "POST"> {% csrf_token %} <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "login">Log In</button> </form> And finally, my view (I based it off [this](How can i Register and Login In The Same Page in Django? solution but it doesn't work): def home(request): if "register" in request.method == "POST": if request.method == "POST": email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') newuser = User.objects.create_user(username = username, email = email, password = password, ) newuser.save() user = authenticate(request, username=username, password=password) if "login" … -
How to show a detail view Serialize in a Django Project
In my Django Project I have Category and a SubCategory. Under each Category there are several SubCategory items. I want to show all the SubCategory items under the Category. I was able to show all the Category items under the same user, but not sure how to filter the SubCategory items that is related to same Category. Here are the models.py class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class SubCategory(models.Model): category= models.ForeignKey(Category, on_delete=models.CASCADE, related_name='SubCategory') Here are the serializers.py class Categoryerializer(serializers.ModelSerializer): user = serializers.CharField(source="user.username", read_only=True) class Meta: model= Category fields = '__all__' class SubCategorySerializer(serializers.ModelSerializer): class Meta: model= SubCategory fields = '__all__' Here is the views: @api_view(['GET']) @permission_classes([AllowAny]) def getCategory(request, **kwargs): user = get_object_or_404(User, username=request.user) category =Category.objects.filter(user=user) serializer = categoryserializer(category, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([AllowAny]) def getSubCategory(request, id,**kwargs): user = get_object_or_404(User, username=request.user) category =Category.objects.filter(user=user, id=id) subcategory =SubCategory.objects.filter(category_id=id) serializer = SubCategorySerializer(subcategory, many=True) return Response(serializer.data) Here are the urls: urlpatterns = [ path('<str:username>/category/', views.getCategory, name='api_category'), path('<str:username>/category_details/<int:id>', views.getSubCategory, name='api_subcategory'), My question how can I show the items of each SubCategory which is related to a specific Category -
Is there an up to date Django geolocation module that can give me countries using IP?
Is there something as simple as plug in the code and go for geolocation? I only want countries so that my website can switch to the appropriate language. It seems that the ones I found are either deprecated, have less than 10 users, are paid/trial versions. -
InvalidAlgorithmError in Django REST framework simplest
Does anybody how to solve this issue? from .backends import TokenBackend File "....../envs/jwt/lib/python3.9/site-packages/rest_framework_simplejwt/backends.py", line 7, in <module> from jwt import InvalidAlgorithmError, InvalidTokenError, algorithms ImportError: cannot import name 'InvalidAlgorithmError' from 'jwt' (...../drf-courses/jwt/jwt/__init__.py) -
Django vs Vue.js/Angular/React/Svelte [closed]
Which one should I use it with Django between Vue.js/Angular/React/Svelte ? Moreover I want to use in future Flutter for mobile app development -
How to show ForeignKey attributes in Django Admin
I am trying to show details of the foreign key in my Django admin. In my case I have a class Category with user in it and a class SubCategory with foreign key with the class Category. In my admin I want to show the user of each class SubCategory Here is the example: class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class SubCategory(models.Model): category= models.ForeignKey(Category, on_delete=models.CASCADE, related_name='SubCategory') Here is the admin: class CategoryAdmin(admin.ModelAdmin): list_display = ['user'] list_filter = ['user'] class SubCategoryAdmin(admin.ModelAdmin): list_display = ['id','category'] My question How can I filter the SubCategory by the user which is an attribute of the foreign key? -
How to check whether it is dns issue, browser issue or server setting issue?
I have deployed www.stochie.com successfully point is now I want to create a subdomain for 'idx.stochie.com' and point it to a new server with IP address 54.179.144.127. I check the DNS already link 'idx.stochie.com' to IP address 54.179.144.127. (https://dnschecker.org/#A/idx.stochie.com) It is ok if I try to go to 54.179.144.127 via my browser but when I tried to go to the address, I get "Hmmm… can't reach this page idx.stochie.com took too long to respond" I am using nginx and here is the config: server { server_name idx.stochie.com '' 54.179.144.127; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/stochie/; listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot if ($host = 'stochie.com') { return 301 https://www.stochie.com$request_uri; } ssl_certificate /etc/letsencrypt/live/idx.stochie.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/idx.stochie.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = idx.stochie.com) { return 301 https://$host$request_uri; } # managed by Certbotlisten 80; server_name idx.stochie.com '' 54.179.144.127; return 404; # managed by Certbot } for the webserver, I am using Django and I have add "idx.stochie.com" to the ALLOWED_HOSTS in settings.py For the starter I … -
Django how to dynamically change select field via Date selected
I'm trying to develop an appointment based app. I want that on my form when I pick a Date it will instantly shows me which hours can I book. Like if im in the form and I want to book for tomorrow but won't see an hour that's good for me then I choose another Date and it will show me the hours of the new date then, without posting the form. models.py: ``` def business_hours(): hours_choices = [] hours = range(8, 20) for hour in hours: if hour < 10: hour = f'0{str(hour)}' for ten_min in range(6): if ten_min * 10 == 0: ten_min = f'{str(ten_min)}0' else: ten_min = str(ten_min * 10) result = str(hour) + f':{ten_min}' hours_choices.append(f'{result}') hours_choices = list(enumerate(hours_choices)) return hours_choices def available_hours(query_set): hours_shown = business_hours() for appointment in query_set: hours_shown.pop(appointment.hour_slot) return hours_shown # Create your models here. class Appointment(models.Model): hours_of_the_day = business_hours() pet = models.ForeignKey(Pet, on_delete=models.CASCADE, related_name="appointments") description = models.TextField(max_length=500, null=True, blank=True) appointment_date = models.DateField() hour_slot = models.IntegerField(choices=hours_of_the_day, null=True) completed = models.BooleanField(default=False) results = models.TextField(max_length=500, null=True, blank=True) created_by = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) creation_date = models.DateTimeField(default=datetime.datetime.now()) def __str__(self): return f"Appointment for - {self.pet.name} ({self.pet.owner}), on " \ f"{self.appointment_date.__format__('%d/%m/%Y')} at " \ f"{self.hours_of_the_day[self.hour_slot][1]}" ``` ``` views.py: ``` ``` … -
Django static root files
Hello i am currently working on a Django project where iam using CKEditor. Its working but if iam trying to customize CKEditor through STATIC ROOT where are all file for them is located, Django not reloading these files. I can even delete whole folder and CKEditor will still work, even i i tryed to delete browser caches atd.. settings.py STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
Why do I need to run the second loop to get the sigle value in django?
The project was to create a filter page where users can filter the model data based on their chosen criteria. The whole thing is working but a specific part is not clear and not making sense. Here is my model- class Author(models.Model): name=models.CharField(max_length=30) def __str__(self): return self.name class Kategory(models.Model): name=models.CharField(max_length=20) def __str__(self): return self.name class Data(models.Model): title=models.CharField(max_length=120) author=models.ForeignKey(Author, on_delete=models.CASCADE) categories=models.ManyToManyField(Kategory) publish_date=models.DateTimeField() views=models.IntegerField(default=0) reviewed=models.BooleanField(default=False) def __str__(self): return self.title Data is the main model while Author was added as ForeignKey and Kategory as many to many fields. My main issue is around this categories field in Data model which has many to many relationship with Kategory model. Here is my views.py file- # This view is for the filter page def is_valid_queryparam(param): return param !='' and param is not None def filter(request): qs=Data.objects.all() kategory=Kategory.objects.all() title_contains_query=request.GET.get('title_contains') id_exact_query=request.GET.get('id_exact') title_or_author_query=request.GET.get('title_or_author') view_count_min=request.GET.get('view_count_min') view_count_max=request.GET.get('view_count_max') date_min=request.GET.get('date_min') date_max=request.GET.get('date_max') category=request.GET.get('category') if is_valid_queryparam(title_contains_query): qs=qs.filter(title__icontains=title_contains_query) if is_valid_queryparam(id_exact_query): qs=qs.filter(id=id_exact_query) if is_valid_queryparam(title_or_author_query): qs=qs.filter(Q(title__icontains=title_or_author_query) | Q(author__name__icontains=title_or_author_query)) if is_valid_queryparam(view_count_min): qs=qs.filter(views__gte=view_count_min) if is_valid_queryparam(view_count_max): qs=qs.filter(views__lte=view_count_max) if is_valid_queryparam(date_min): qs=qs.filter(publish_date__gte=date_min) if is_valid_queryparam(date_max): qs=qs.filter(publish_date__lte=date_max) if is_valid_queryparam(category): qs=qs.filter(categories=category) test=Data.objects.only('author') context={'queryset':qs, 'kategory':kategory, 'test':test} return render(request, 'myapp/filter.html', context) As you can see in the views.py that I have 2 variables holding all of Data and Kategory model data. I have worked with this type … -
How to autoincrement values checkbox with jinja2 (Django) with reset
I need to autoincrement value in my checkbox and reset value when I generated new massive of checkbox forloop.count dont reset {% for ans in Answ %} {% if ans.question_id_id == Questions.id %} <input type="hidden" value="{{ Questions.id }}" name="id"> <div class="form-check" ><label><input type="checkbox" value="{{ ans.id }}" name="answer"> {{ ans.answer }} </label></div> {% endif %} {% endfor %} -
Run and follow remote Python script execution from Django website
I am running a Django website where user can perform some light calculation. This website is hosted in a Docker container on one of our server. I would like now to add the ability for the users to run some more complicated simulations from the same website. These simulations will have to run on a dedicated calculation machine (they will run in parallel for a several hours/days) under Ubuntu server in the same network. What will be the best way to achieve this? Send the calculation to the calculation serverand send them back automatically to Django? How can I follow the status of the calculation (waiting, calculating, finished) from the Django instance? Should I use a job scheduler on the calculation server? This is close to this question that was asked in 2014, so there might be more actual solutions. -
Django form is never valid and hence doesnt save to database
I am creating a registration model which has date,time(charfield with choices),customer and restaurant .I need some help on why my instance is not saved even when I fill out my model form models.py class reservation(models.Model): TIMESLOTS = [ ('11:00-1:00', '11:00-1:00'), ('01:00-3:00', '01:00-03:00'), ('03:00-05:00', '03:00-05:00'), ('05:00-07:00', '05:00-07:00'), ('07:00-09:00', '07:00-09:00') ] date=models.DateField(null=True) time=models.CharField(null=True,max_length=200,choices=TIMESLOTS) customer=models.OneToOneField(User,null=True,on_delete=models.CASCADE) restaurant=models.OneToOneField(Restaurantdetails,on_delete=models.CASCADE,null=True) def __str__(self): return self.restaurant.name forms.py class Reservationform(ModelForm): class Meta: model=reservation fields=['date','time','restaurant'] views.py def reservationcreator(request): form=Reservationform() if form.is_valid(): form = Reservationform(request.POST) res=form.save() res.customer=request.user res.save() messages.success(request, 'reservation created') return redirect('menu') else: print('BS') context = {'form': form} return render(request,'userrestaurant/reservation.html',context) -
Find all objects of a certain class who do not have any active links with other objects
I have a class A which is used as a Foreign Key in many other classes. class A(): pass class B(): a: A = ForeignKey(A) class C(): other_name: A = ForeignKey(A) Now I have a database with a huge table of A objects and many classes like B and C who reference A (say potentially dozens). In this table, there are many objects (100k+) and I want to clean up all objects that are not actively referenced by other objects with a Foreign Key. For example, object 1 of class A is not referenced by class B and C. How would I do this? I already came up with the following code: a_list: list = list() classes: list[tuple] = [(B, "a"), (C, "other_name")] for cl, field in classes: field_object: Field = cl._meta.get_field(field) for obj in cl.objects.all(): a: A = field_object.value_from_object(obj) a_list.append(a) to_remove: list[A] = [a for a in A.objects.all() if a not in a_list] for a in to_remove(): a.remove() This leaves me with a few questions: What if I don't know the full list of classes and fields (the case since it is a large group)? Is this the most efficient way to do this for a large table with … -
Edit form AuthAll Django
I'm new using Django and i'm using AuthAll to login/logout, the problem comes when i try to edit the template of the original form. I've created a the templates but i want to change the form with the inputs, originally there are no inputs just "{{form}}" line 38 . Is there a way to access to that inputs and change the style? Thanks!! I actually dont want to create views, i really want to use AuthAll and just change the style of the 2 inputs. I tried searching where its created the form but i think its automatic. -
How to get papypal client side info to django?
I am using PayPal standard IPN payment solution in client side in my Django web app. <body> <!-- Set up a container element for the button --> <div id="paypal-button-container"></div> <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '88.44' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { // Successful capture! For demo purposes: console.log('Capture result', orderData, JSON.stringify(orderData, null, 2)); }); } }).render('#paypal-button-container'); </script> </body> everything works fine and I can access all the data through the details variable in the js code. Now, i need to insert the details into django db, how can it be done? No api, simple model. Tried many things, none worked. Thanks for the help! -
Best place to start to develop a website for someone who knows python
The small healthcare company I work for is looking to update the website that other employees enter data into that then gets sent to our database. The current website was coded by someone that isn't there anymore and no one really knows how to maintain it efficiently. Even though I am a data analyst my team has been tasked with this to do. Since I use python every day I was wondering if there was a good way to make all of this relying on python for most of it, or where would you guys point someone like me to start learning this? Thank you! I have heard of flask and Django but just wanted to see what people's opinions are for doing this kind of project. The website really just needs some basic interactivity like going to different pages and entering stuff into a field (and restricting what they can't enter) that then gets sent to a database. -
Mark specific Django migrations as fake migrations during test DB setup
I have some database migrations, some are structural migrations some are data migrations eg. 0001_initial.py 0002_move_data.py 0003_add_field.py 0004_move_more_data.py I would like to skip those data migrations (0002 and 0004) as I don't want to spend the effort to fake the source for those data migrations but still run 0001 and 0003 when running python manage.py test Is it possible? -
How to get foreign key attribute (or many to many attribute) of a model instance in Django in asynchronous queries?
In asynchronous queries, I want to get foreign key and many to many attributes of a model instance. In my case, I want to get university and courses of the model Student. models.py: from django.db import models class University(models.Model): name = models.CharField(max_length=64) class Course(models.Model): name = models.CharField(max_length=64) class Student(models.Model): name = models.CharField(max_length=64) university = models.ForeignKey(to=University, on_delete=models.CASCADE) courses = models.ManyToManyField(to=Course) when I use this code (in django 4.1): async for student in Student.objects.all(): print(student.university) print(student.courses) I get the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How can I fix this error? -
Will Django model instance always be populated when calling save()?
I have a model where I am overriding the save() function to add SearchVector's. I need to preprocess one of the instance's fields so I am overriding the save function: class Student(models.Model): first_name = models.CharField(max_length=255, default="") last_name = models.CharField(max_length=255, default="") search_vector = SearchVectorField(null=True) def save(self, *args, **kwargs): sv = SearchVector(Value(self.first_name)) + SearchVector(Value(self.last_name)) if len(self.last_name) > 3: sv += SearchVector(Value(self.last_name[0:3])) self.search_vector = sv super().save(*args, **kwargs) Can I expect that all fields (first_name & last_name) of the instance are always populated inside the save() function? I noticed that the instance loading function from_db seems to suggest that model instances can be created with a partial set of fields. Does this mean that first_name could be None on the save() call? -
How to make an ajax function to execute only in in a certain case?
I have an ajax function that updates every second some value on page, I want to update it only when the script is working, because to not request a value that is the same. The script is updating this value, and ajax is refreshing it on website, but when script is not working, my ajax is requesting the value. How to make it work only when the script is working? var interval = 1000; function update() { $.ajax({ type: 'GET', url: 'http://localhost:8000/api/updating', headers : {'Authorization': "Token "+ token,}, data: $(this).serialize(), dataType: 'json', success: function (data) { $('#points_a').html(data)// first set the value }, complete: function (data) { // Schedule the next setTimeout(update, interval); } }); } setTimeout(update, interval); This is script in python view, Django: def task(userid, seconds_for_thirtydays=0): if(seconds_for_thirtydays < 2592000): p_a = Wallet.objects.filter(name__id=userid).values("points").first()['points'] add = p_a + 1 result = Wallet.objects.filter(name__id=userid).update(points=add) seconds_for_thirtydays = seconds_for_thirtydays + 1 time.sleep(1) task(userid) else: return The thing that I want to make is: When the value is not changing(the script is not working), then this ajax won't work and won't make requests, is it possible? -
Django/Wagtail Media Files not showing up in the admin portal on a fresh install
I am working on a site in dev that contains a media folder. When I do a fresh setup of the site (empty db) and do all the migrations and steps to get the site up and running I noticed in the admin portal none of the images and assets in the media folder dont show up even though they exist. I have to re-import an image and then it shows up in the admin portal as expected. I have looked all over and cannot find an answer. To put it simply why isnt the admin portal importing existing files in the media folder on a fresh setup? django==3.2 wagtail==3.0 base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' urls.py from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from wagtail.contrib.sitemaps.views import sitemap from search import views as search_views urlpatterns = [ ... ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If anyone has any idea? -
JS static files not working for Django Project
I am following this online countdown-tutorial https://www.youtube.com/watch?v=ZpujnQqcvAA to implement into my website. I feel I am missing something simple. base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- favicon --> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- custom js--> {% block scripts %} {% endblock scripts %} <title>countdown to events</title> </head> <body> <div class="container mt-3"> {% block content %} {% endblock content %} </div> </body> </html> main.html {% extends 'base.html' %} {% block content %} {% for obj in object_list %} <div> <a href={{obj.get_absolute_url}}>{{obj.name}}</a> </div> {% endfor %} {% endblock %} countdown.html {% extends 'base.html' %} {% load static %} {% block scripts %} <script scr={% static 'main.js' %} defer></script> {% endblock scripts %} {% block content %} <div class ="row"> <div class = "col-5"> <div>{{object.names}} will take place:</div> </div> <div class = "col-7"> <div id="event-box">{{object.when|date:"M d, Y H:m:s"}}</div> </div> </div> <div>Time left:</div> <div id ="count-down-box" class="text-center mt-3 h1"> <div class ="spinner-border" role = "status"></div> </div> {% endblock content %} main.js console.log('hello world') const eventBox = document.getElementById('event-box') const countdownBox = …