Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
count duplicate words in arrayField of postgres django
In my django's array field Is there any way I can count how many duplicate elements there are in the query_set query? For example, I have tags ["A", "B", "C"] Each object you query in the list will know how many characters it matches Object 1 with tags ["A", "B", "F"] has the same 2 Object 2 with tags ["H", "S", "B"] has the same 1enter image description here -
Setup user role read/edit project by project, Django ORM
I am trying to implement a relationship between three tables; User Project and Permissions I already have a ManyToMany relationship between User and Project class CustomUser(AbstractUser): username = models.CharField(unique=True, max_length=20, null=False, blank=False) // etc... class Project(models.Model): user = models.ManyToManyField(CustomUser, related_name="projects") Now I am trying to add the Permission Table. So that User can take different roles on different project. class Permissions(models.Model): can_read = models.BooleanField(default=True) can_read_and_edit = models.BooleanField(default=False) // etc... What is the best approach on this situation. Should I Add Permission table into manytomany relation as a third table? Or is there a better way to achieve this -
Django recursive relationship in many-to-one and many-to-many
I'm reading Django documentation and currently trying to understand the Django models recursive relationship in many-to-many and many-to-one and I still don't get it. Can anybody help to explain in what situation we need to use recursive relationship? And how will the recursive many-to-one be different from the recursive many-to-many? Will be great if perhaps in an example. Thank you in advance. -
How to use string values of a variable as a django model queries?
I have some Model Fields those are related to User model by many to many relationship class SocialPost(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE, related_name='users_post' ) privacy=models.CharField(max_length=100,blank=True, null= True) post_text=models.TextField(blank=True, null= True) location=models.CharField(max_length=100,blank=True, null= True) feeling_or_activity=models.CharField(max_length=100,blank=True, null= True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(blank=True,null=True) category=models.CharField(max_length=100,blank=True, null= True) tags=models.ManyToManyField(User, related_name='taglist',blank=True) views = models.ManyToManyField(User, related_name='post_views',blank=True) likes = models.ManyToManyField(User,related_name='post_likes',blank=True) love=models.ManyToManyField(User,related_name='post_loves',blank=True) angry=models.ManyToManyField(User,related_name='post_angries',blank=True) haha=models.ManyToManyField(User,related_name='post_hahas',blank=True) sad=models.ManyToManyField(User,related_name='post_sads',blank=True) care=models.ManyToManyField(User,related_name='post_cares',blank=True) senti=models.ManyToManyField(User,related_name='post_senties',blank=True) wow=models.ManyToManyField(User,related_name='post_wows',blank=True) I will get values like reaction='wow' through API call. i want to call like variable=object.reaction.filter() Which will be always call by reaction variables value. as example if reaction='like' it will call variable=object.like.all() and if reaction='sad' it will call variable=object.sad.all() i don't know how can i do this! can anyone help me in this problem? -
Javascript/Jquery: How we can use loading spinner for download some report from our web-page
I'm Just stuck with some problem which is "Generate Report". It actually download the report and it takes time to generate and download the report. So I just want to use loading spinner for that download file. I'm new to understand the concept of Javascript/Jquery. In this logic, I haven't used any ajax request. Also I've 2 files like i.e. .html file and .js, Please suggest me how to solve this logic. I've explored everywhere, couldn't find anything. -
How to automatically set the thread instead of user having to set it in django
I am trying to create a discussion forum website with django. Everything is working, but I want to change one thing and I have no idea how to. In the website users can create threads and posts inside those threads. When a thread is created there is a button in that thread that says add a post in this thread. Then it will take them to a form. Right now, if the form were to work they would have to select from a dropdown menu which thread they wanted to add a post to. I want the thread to be the thread that the button they clicked was inside of. models.py: class Thread(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) description = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('thread-view', kwargs={'pk': self.pk}) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('post-view', kwargs={'pk': self.pk}) views.py: def homeView(request): context = { 'threads': Thread.objects.all().order_by('-created_at'), 'posts': Post.objects.all().order_by('-created_at') } return render(request, 'forum/home.html', context) class ThreadCreateView(CreateView): model = Thread fields = ['title', 'description'] # Right now I also have to add in 'thread' as … -
Reverse for with no arguments not found for URL
I am attempting to create a view that allows users to delete a build log. On the view that shows the delete button with a link to the delete page I am getting the error Reverse for 'build-log-delete' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/build\\-log/(?P<pkz>[0-9]+)/delete$'] If I understand this error correctly its because I am not passing paramaters in the url. <a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a> However I do not understand why I need to pass parameters in the URL as I am not passing any new values into the URL and if so what parameters I would pass. Do I have to re pass the previous two? urls path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete', views.BuildLogDelete, name='build-log-delete') #error views def BuildLogDisplay(request, pk, pkz ): post = BuildLog.objects.filter(post_id=pk) log = BuildLog.objects.get(pk=pkz) context = { 'post':post, 'log':log } return render(request, 'blog/buildlog.html', context) def BuildLogDelete(request): context = { } return render(request, 'blog/BuildLogDelete.html', context) full template <div class="row"> <article class="cars-article"> <div class="flex"> <img class="rounded-circle article-img" src="{{ log.author.profile.image.url }}" /> <div> <a class="article-title">{{ log.title }}</a> </div> </div> <br> <div> {% if log.author == user %} <a class="update-btn" href=""> Update</a> <a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a> {% endif %} </div> <hr class="solid"> <p class="article-content">{{ log.content … -
Formset is not giving me 3 of the form by default and got KeyError when saving
Hi i have the following error while using formset. Exception Type: KeyError Exception Value: 'module' This error happen when i try to press save on the add page. Currently in my webpage, theres only 1 formset. I read online by default its 3 but even after i add extra=3. Its still 1. Can anyone help me? Here are my codes: views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) #di_form= DeviceInterfaceForm(request.POST) di_formset = modelformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), extra = 3) di_form=di_formset(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.DD2DKEY = new_device # If you did not render the hostname for the device detail, set it from the value of new device deviceD.hostname = new_device.hostname deviceD.save() if di_form.is_valid(): deviceI=di_form.save(commit=False) deviceI.I2DKEY=new_device deviceI.save() new_device=Device.objects.all() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) else: device_frm = DeviceForm() dd_form = DeviceDetailForm() di_form = DeviceInterfaceForm() return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) … -
bulk_create always causes primary key error (sql server)
Using Django 3.2.6, DB - SQL Server I'm trying to use bulk_create to create a set of rows in my database. In my view, I create a list of Model objects like this and use bulk_create asset_map_list = [] for row in data_list: asset = Asset(asset_type=AssetType.objects.get(name=asset_type_name), asset_name=row['asset_name'], display_name=row['display_name']) asset_list.append(asset) Asset.objects.bulk_create(asset_list) However it keeps throwing a Primary key error django.db.utils.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK__mm_asset__xxxxxx' My Asset and Asset Type models look like this: class Asset(models.Model): asset_type = models.ForeignKey(AssetType, on_delete=models.CASCADE) asset_name = models.CharField(max_length=80) display_name = models.CharField(max_length=80) class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) description = models.CharField(max_length=80) I tried setting ignore_conflicts=True but SQL Server doesn't support that. I tried doing df.to_sql() but it gets complicated because of the foreign key (as you can see -- the user inputs asset type NAME but in my asset DB I'm storing asset type ID ) Can someone please help me solve this bulk_create issue or point me to a better alternative? Thanks -
How to deal with empty foreign keys in a for loop within django View
I have a model which acts a as schedule where there are multiple FK relationships to the same user table. All of these fields can be blank/null. The issue is, when i do a for loop, i am trying to match the users based on when they appear on a certain shift, then add a +1 to a counter to get the total shifts for that user. The model looks like this: class WeekdayAssignment(models.Model): """Model definition for WeekdayAssignment.""" start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) triage_emea_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_emea_1", blank=True, null=True) triage_nam_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_1", blank=True, null=True) triage_nam_2 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_2", blank=True, null=True) triage_nam_3 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_3", blank=True, null=True) ... As you can see i have 4 triage shifts and the same user can work any of those shifts. I want to do a for loop to count how many times a user is on a shift in any one of those fields. Without getting into all the details of what I am doing, i will keep it simple as the error happens right away. Views.py def someview(request): shift_users = TeamMember.objects.all() weekday_shifts = WeekdayAssignment.objects.all() for t in shift_users: for ws in weekday_shifts: print(ws.triage_nam_3) As long … -
How to submit information using Django?
I have the following form in a modal and I want to save the information in the DB but it does not happen. but if I manage to remove an attribute from the submit button if I save it but the button validations and actions disappear. <button type="submit" class="btn btn-primary" data-kt-account-modal-action="submit"> replacing with this if it works and saves but validations no longer work. <button type="submit" class="btn btn-primary"> -
Django - Populate field based on user selection from dropdown
I want to have the following: User selects a Location ID from a dropdown list and then the next field shows the Location description (name_county_postcode) associated with that ID automatically. I have two models set up: class UkTowns(models.Model): id = models.IntegerField(primary_key=True) locationid = models.CharField(max_length=8, blank=True, null=True) name_county_postcode = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.locationid class Project(models.Model): projectid = models.IntegerField('ProjectID', db_column='ProjectID', primary_key=True) locationid = models.ForeignKey(UkTowns, models.DO_NOTHING, verbose_name="LocationID", db_column='LocationID', max_length=50) project_name = models.CharField('Project Name', db_column='Project_Name', max_length=300) author = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, db_column='Author_id') def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) The following views: class PostCreateView(LoginRequiredMixin, CreateView): model = Project fields = ['projectid','project_name','locationid'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Project fields = ['projectid','project_name','locationid'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): Project = self.get_object() if self.request.user == Project.author: return True return False And the following html page: {% extends "costcapture/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Project</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> {% endblock content %} Currently the form works with the fields from PostCreateView and PostUpdateView (it shows more than what I've included … -
Why is django filling spaces to the max length of the char field?
I have some char fields in django that look like this: attrunit = models.CharField(db_column='AttributeUnit', max_length=64, blank=True, null=True) To my understanding, the blank option allows users to write empty form values, and null means the entry does not need to be populated at all in the database. However, whenever I write to any of my CharFields, django seems to backfill spaces up to the max length of the field. For reference, I routed all of my write-models into a MSSQL server database (not the default SQLLite db that django builds). I'm at a loss as to where these spaces are coming from and I do not want to have to strip the values every time I read them out from the db. -
Django - build HTML table in template using multiple models - one model for columns, one for rows
I'm quite sure this has been answered but I'm not really sure what keywords I need to use to find the answer. I have a simple model that has a foreign key relationship with the built-in User model. There's also a UniqueConstraint to prevent a user from having more than one pick per game. class PickModel(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) game_number = models.IntegerField(blank=False, null=False) class Meta: constraints = [ models.UniqueConstraint(fields=['user','game_number'], name='One user pick per game') ] I need to build an HTML table that summarizes this info. Columns of the table should be users and rows should be the picks. How should I structure the data in my view so that I can loop through it in the template and make sure that a user's pick falls in the correct column? I basically need to be able to loop through both users and picks at the same time. Do I need to do a join on these tables in my view or is there a way to handle this only using template tags/logic? -
Django tests. Equvalent to request.COOKIE
I read a lot on Google and stack, but couldn't find the answer. I got some piece of code in my view: try: cart = json.loads(request.COOKIES['cart'])['products'] except: cart = {} I'm getting data from created cookie (for example name: cart, value: {"products":{"1":{"quantity":1}}}). The problem is: how to test that view by TestCase in Django? For example I tried to use: self.client.cookies["cart"] = {"products":{"1":{"quantity":1}}} But client.cookies is not equal to request.COOKIES. My test everytime fails. Should I put more code? PS. My view works fine, i got problems just with testing. -
How can I spawn a listener from Django?
I want to be able to start a Twitter stream listener upon a request on the django project. For example: user creates a Tracker object (keywords: apple, microsoft). Then calls the /trackers/1/start endpoint and the view starts a thread/coroutine to listen Twitter stream for these keywords. Whenever a tweet appears in the stream, it creates a celery task to save the tweet. Of course, it should be non-blocking. So: should I create new threads per tracker (twitter listener)? should I use async def views? I could create sync or async functions for the tweepy listener/stream. Currently I'm having RuntimeError: You cannot use ATOMIC_REQUESTS with async views. when I do this. By the way, I plan to deploy on Heroku but I can choose VPS if that's not feasible for this problem. -
Assigning Objects to Many-to-many relationships - Django
I have a django project where I have a list with checkboxes, to select and assign students to teachers. I have attached my code below - I am getting no errors, but it doesn't seem to be assigning the student to the "students" many-to-many field in my "teachers" model. I have a GET function that is called earlier to select the teacher, then it is meant to pull that GET record and assign the student to that teacher. Any ideas? Views.py if 'assign_student' in request.POST: form = StudentForm(request.POST) selected = request.GET['select_teacher'] selected_teacher = Teacher.objects.all().filter(pk=selected)[0] if form.is_valid(): student_selected = request.POST('assign_student') student = Student.objects.all().filter(pk=student_selected)[0] selected_teacher.students.add(*student) Template.html <div class="student-list"> {% for instance in all_students %} <div class="input-group" style="border-bottom: 1px solid;"> <div class="item-details"> <div class="form-check"> <form method="POST" class="form-group" name="assign_student"> {% csrf_token %} <input onChange="this.form.submit()" class="form-check-input" type="checkbox" value={{ instance.pk }} id="flexCheckDefault" name="assign_student"> </form> <p> <b>{{ instance.fullname }}</b> <br> {{ instance.homeschool }} - {{ instance.schoolclass }} Class </p> </div> </div> </div> {% endfor %} </div> -
Display and render django admin permissions on a template
I am creating a school management system. I want to display the Django permissions generated on the Django admin page to be rendered and attached (by clickable buttons) to users. I want the administrator to have access to all the CRUD functionality of each model so that he can attach permissions to users on a custom dashboard. I am doing all that so as to prevent the school administrator from using the Django admin panel. Confused as to even where to start -
ValueError: attempted relative import beyond top-level package when trying to import models from another app in django
I have two django applications in my project in my project named electron: the first api and the second elec_meter. The directories are organized as follows: electron / api/ views.py ... elec_meter/ models.py ... In the api / views.py file I want to import elec_meter / models.py.This is how I do it: from ..elec_meter.models import * But I get the following error message: ValueError: attempted relative import beyond top-level package or from electron.elec_meter.models import * In this case I receive this error message: ModuleNotFoundError: No module named 'electron.elec_meter' Here is a picture of my code How can I solve this problem? -
Django Models Select a car model based on Car Make
Somewhat new to Django and I'm trying to create a car listing site. I've already ran into problems with the models. I can't seem figure out how I can create a model where if you select a particular make (e.g. Dodge) then you can select a model related to that make (e.g. Charger, Challenger, Viper etc.) models.py class Make(models.Model): make = models.CharField('Make', max_length=150) class Meta: ordering = ['make'] unique_together = ["make"] verbose_name_plural = "Manufacturers" def __str__(self): return self.make class CarModel(models.Model): year = models.IntegerField(default=datetime.datetime.today().year) make = models.ForeignKey(Make, on_delete=models.CASCADE) model = models.CharField('Model', max_length=150) trim = models.CharField('Trim', max_length=150, help_text='Trim level') class Meta: ordering = ['make', 'model', 'trim', 'year'] unique_together = ("year", "make", "model", "trim") verbose_name_plural = "Models" def __str__(self): return f' {self.year} {self.make} {self.model} {self.trim}' class CarListing(models.Model): content = models.FileField("Media") make = models.ForeignKey(Make, on_delete=models.CASCADE) make_model = models.ForeignKey(CarModel, on_delete=models.CASCADE) class Meta: ordering = ['make_model'] verbose_name_plural = "Car Listings" def __str__(self): return f' {self.make_model.year} {self.make_model.make} {self.make_model.model} {self.make_model.trim} ' -
Endless Databse in Django
I'm building a web app where I can give objects attributes. But I don't want to specify the maximum number of possible attributes. How can I make this database or model.py "endless". -
How shall I "Unsuspend" my suspended Heroku Application?
I got a mail some moments ago saying my deployed Django application has been suspended. I deployed it a few weeks ago and it has been running fine. No reason was given as to the cause of the suspension. And when I try to access the application, all I see is the image below. I'd appreciate any advice on what to do. Thank you. -
Value Error: invalid literal for int() base 10: 'null'
I am working on a e-commerce site with Django. I built a filter tags cart.Py where I compared two variables.one was str and another int. If Int(I'd)==product.id: Return true But the server shows Value Error: invalid literal for int() with base 10 : 'null' Help to figure out please. -
how to append a <hr> to a form element selected in JQuery?
Some introduction: I'm creating a form in Django. In my template I'm trying to select the final element of that form and attach a <hr> html element to help clean up the visual clutter. I've tried selecting the Forms ID and inserting adjacenthtml as well as appending raw html. I have also tried passing raw html into bootstrap in my form but this has also failed to render. tldr; I am trying to append a <hr> element to something I am targeting in Jquery function addHoriztonalRule() { document.getElementById("form").insertAdjacentHTML( "<hr>"); } -
How to server django media files with docker and nginx?
My setup for dockerizing & serving the Django app is a bit different when it comes to Nginx so the solutions I found didn't help. I have dockerized the django app and its working fine except the media files. I am not using nginx inside the container but on the actual server. All the requests even static files are served perfectly except media files. Here is my docker-compose file: version: "3" services: backend: image: gitrepo:latest #image: 731d5d7e9296 ports: - 8400:8000 links: - database command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8000" volumes: - media-cdn-data:/app/media_cdn deploy: restart_policy: condition: on-failure tty: true database: image: "postgres:12" # use latest official postgres version env_file: - database.env # configure postgres volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down volumes: database-data: # named volumes can be managed easier using docker-compose media-cdn-data: This is my nginx file: server { server_name app.platformname.com; location /media/ { proxy_pass http://127.0.0.1:8400/; alias /app/media_cdn/; } location / { proxy_pass http://127.0.0.1:8400/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 3600; proxy_set_header Connection ''; # these two lines here proxy_http_version 1.1; } } Any help is appreciated,I have been …