Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Download documents in docx and csv format
I make a website on Django I have a code with filling out documents in docx and csv format CSV: FILENAME = "static.csv" with open(FILENAME, "w", newline="") as file: columns = ["Date","Price"] writer = csv.DictWriter(file, fieldnames=columns) writer.writeheader() i = 0 a = 0 while i<len(date): while a < len(price): users = [ {"Date": date[i],"Price": price[a]}, ] writer.writerows(users) i+=1 a+=1 docx: doc = DocxTemplate('template.docx') dates = date prices = price tbl_contents = [{'expirationdate': expirationdate, 'price': price} for expirationdate, price in zip(dates, prices)] context = { 'tbl_contents': tbl_contents, 'finalprice': sum(prices) } doc.render(context) doc.save("Static.docx") I need to download these documents. How can this be done? -
Custom Serializers - serializers that do not map directly onto a model
My questions are with regards to Django Rest Framework, and specifically, Custom Serializers - serializers that do not map directly onto a model. I have really done my best to summarize. Assume we have two tables, User Table and User Information table linked by a one-to-one relationship (user being a field in User Information). I created a custom Serializer which combines all fields of both tables and when save() is called, creates a record in both User Table and User Information Table. Observations In the view, serializer.data will be empty. Probably because the serializer does not commit to the db (given that the serializer does not map to one specific model) and therefore serializer.data is not populated. Is this possibly the (most) correct implementation? I cannot get it to work for both read and write (see code below). It seems to work for reading or writing but not both. If the serializer is not mapped to a model, can it read and write or just write? Maybe my Serializer is poorly done? SERIALIZER first_name = serializers.CharField( write_only=True, required=True ) last_name = serializers.CharField( write_only=True, required=True ) phone_number = serializers.CharField( write_only=True, required=True ) email = serializers.CharField( write_only=True, required=True ) national_id = serializers.CharField( … -
Query degenerates into a PK scan when order by is added
I have a query that results in a couple of rows and executes in microseconds, but turns into a primary key scan once an order by is added. explain select * from mcqueen_base_video as v1 left join mcqueen_base_visit as v2 on v1.visit_id = v2.id where v2.protocol_id = 191 and v1.is_valid = TRUE order by v1.id limit 10; QUERY PLAN ----------------------------------------------------------------------------------------------- Limit (cost=0.99..284.38 rows=1 width=543) -> Nested Loop (cost=0.99..23421737.58 rows=82648 width=543) -> Index Scan using mcqueen_base_video_pkey on mcqueen_base_video v1 (cost=0.56..3191817.90 rows=44436676 width=470) Filter: is_valid -> Index Scan using mcqueen_base_visit_pkey on mcqueen_base_visit v2 (cost=0.42..0.45 rows=1 width=69) Index Cond: (id = v1.visit_id) Filter: (protocol_id = 191) (7 rows) This query is generated by Django's ORM and the reason for the order by v1.id limit 10 is the way that django does pagination. I know that order by/limit is a terrible way to paginate large datasets, but even though the table is large, the filters usually result in small result sets. The problem is that the query planner decides to do an index scan and filter on is_valid before determining the join results. I've already tried adding an index on visit_id,is_valid but that did not alter the query plan. If I manually resolve the … -
Slow Django many to many query
I have 9 Million records. It will be 200M soon. It can take 15min + to fetch this: class Follower(): hashtags = models.ManyToManyField( "instagram_data.Hashtag", verbose_name=_("hashtags_name")) class Hashtag(models.Model): name = models.CharField(_("HashtagName"), max_length=150, null=True, blank=True, unique=True) def __str__(self): return self.name Ubunto htop: I think it reverse lookup for all values. I think it will have maybe 2000 records found. What am I doing wrong ? -
Send tasks to two separate workers in celery
I have two tasks in celery and would like to send them to different workers to complete but I am not sure how to do this. I have looked at the task_routes section of the celery documentation and have tried a few things from stackoverflow but no luck. tasks.py @app.task def task1(): does something @app.task def task2(): does something else I have two celery workers and I would like them to focus on one task each so worker1 on task1 and worker2 on task2 celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.conf.timezone = 'Europe/London' app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL=str(os.getenv('REDIS_URL')), CELERY_RESULT_BACKEND=str(os.getenv('REDIS_URL')), broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }, redis_backend_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) app.autodiscover_tasks() Then procfile - web: gunicorn project.wsgi --log-file - worker1: celery -A project worker -l INFO --concurrency=1 -Ofair -n worker1.%h worker2: celery -A project worker -l INFO --concurrency=1 -Ofair -n worker2.%h How do I set the queues up so that worker1 = task1 and worker2 = task2? -
How to get all remaining data after returning data using offset and limit in django
I responded the data result, using offset and limit. After that, what should I do in django when a request to reponse all other than the response data comes in? first_response = Foo.objects.all()[:10] after_response = Foo.objects.all()[10:] ??? -
How does one display a list in Django + JavaScript element by element?
To start, the version of my problem I'm presenting here is simplified to make my question clearer. Let's say I want to make a Django web app, which takes some data from user, runs some Python logic and returns a list of objects. An object has 2 values, I want to display the values of each list member one by one, moving on to the next object after X seconds or after the user presses the button. I understand that I'll probably have to get JavaScript involved...I'm really a newbie to JS and I was wondering whether you faced a similar issue and have some useful links or advice. Thanks in advance :) -
Django Heroku: Adding secret key to heroku does not work
I'm trying to add my SECRET_KEY environment variable to heroku using the command: heroku config:set SECRET_KEY='mysecretkey' The command won't even be executed because it says to a part of my secret key "cannot be processed syntactically at this point" (it may be a bit different in english, my command line runs in german. That's just my translation). -
NameError: name '_' is not defined in django
class Food(models.Model): File "D:\Django\restaurant\foods\models.py", line 7, in Food description = models.CharField(("توضیحات"), max_length=50) NameError: name '' is not defined -
Static file (images & CSS for admin) is not loading
On my Django website When I am making DEBUG = True Images are not loading. Please find my Dir structure and code. Settings.py STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/admin/' STATICFILES_DIRS=[ STATIC_DIR, ] MEDIA_URL = "/abcd/" MEDIA_ROOT = BASE_DIR INSTALLED_APPS = [ ------ 'django.contrib.staticfiles', -- - - - - - ] Models.py class Product(models.Model): " " " - -- - - -- - - image = models.ImageField(upload_to='upload/products/', default='',null=True, blank=True) """"""""" class PostImage(models.Model): post = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='upload/products/') urls.py from django.conf.urls.static import static urlpatterns = [ """"""", ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML file: {% if product.image %} <img class="rounded-circle" src="{{product.image.url}}" alt=".." height="45px" width="45px"> {% endif %} here If I am changing Debug=False It is working as expected but when it is True images are not loading and I admin page CSS is not working. Can anyone help me with steps on how to resolve this problem? -
Have each user have a model attached to them, and that model has a many to one relationship with items
I am trying to create a Django application where each User has one model attached to them ( a list of Plants ) and that model is composed of individual plants. I already know I can have the plants connected to the plant list through a many-to-one relationship using foreign key as shown down below: class PlantList(models.Model): plant_list_id = models.AutoField(primary_key=True) class Plant(models.Model): plantlist = models.ForeignKey(PlantList, on_delete = models.CASCADE) name = models.CharField(max_length = 20) wateringInterval = models.PositiveSmallIntegerField() However, I want each user to have a plant list attached to them that can be displayed uniquely for each user, according to the plants that they add to their list. How would I make it so that each user has a plant list? I was trying to have it inside the register form but couldn't figure out how to do it and I wanted each plantlist to have a unique ID so that I can add plants to it easier. -
Django Rest Access Model Values in Another Model
I am new on Django and I have some issues about Rest API. I want to access User Model Values from Project Model. I have User JSON like this: [ { "id": 15, "first_name": "Ebrar", "last_name": "Bilgili", "university": "Bahçeşehir University", "faculty": "Software Engineering", "user": 17 }, ] And also I have Project JSON like this: { "id": 4, "title": "teammate", "city": "istanbul", "user": 17, "user_profile": 15 } But I want to access User First name, Last name, University and Faculty values in Project JSON like this: { "id": 4, "title": "teammate", "city": "istanbul", "user": 17, "user_profile": { "first_name": "Ebrar", "last_name": "Bilgili", "university": "Bahçeşehir University", "faculty": "Software Engineering", } } I have many researched but I could not find any solution. I searched all the methods that came to my mind.. I hope you help me. Thanks. -
Django admin served with gunicorn displays without styling at all
I have a Django application served with Unicorn, and I can reach the application through the IP, but Django Admin (and all other django views) looses all the styling: I followed this tutorial to make the deployment, and this is my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_DIR = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = '/vol/web/media' LOCALE = "es_MX" I can't find what I can be doing wrong. -
URL tracking with the presence of GET parameters
I send a request to the site with GET parameters response = requests.get(f'http://localhost/botcontact&phonenumber={phonenumber}&user_id={user_id}') Tracking in urls.py path('botcontact/', views.botcontact) I get the error Not Found: / botcontact&phonenumber=+79162321578&user_id=228695396 How to make GET parameters not taken into account in urls.py and it could be tracked via path ('botcontact/', views.botcontact)? In this case, GET parameters must be obtained in the function -
Django create ContentType in only one database
I am having a Django project with two apps. One is a custom Auth1 app and other is the main app. I have two databases, one for each app with respective routers but I am not able to migrate. The below error occurs: (venv) D:\Languages\Python\DMS\void>manage.py migrate --database=Auth1 Operations to perform: Apply all migrations: admin, auth, contenttypes, cred, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "D:\Languages\Python\DMS\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: django_content_type The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Languages\Python\DMS\void\manage.py", line 22, in <module> main() File "D:\Languages\Python\DMS\void\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_l ine utility.execute() File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\commands\migrate.py", line 268, in handle emit_post_migrate_signal( File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "D:\Languages\Python\DMS\venv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "D:\Languages\Python\DMS\venv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\contrib\auth\management\__init__.py", … -
Django Get Returns More then one value
hello im new to django i am making a blog site i am getting an error when i try to acces my blog my code: views.py: from django.http import request from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Item, Blog # Create your views here. class BlogView(ListView): model = Blog template_name = "main/blog.html" context_object_name = "blog" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) search_input = self.request.GET.get('search') or '' if search_input: context['blog'] = context['blog'].filter(title__icontains=search_input) return context class Detail(DetailView): model = Item template_name = "main/item.html" context_object_name = "items" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = Item.objects.get() context['items'] = Item.objects.filter(blog_id=obj.blog_id) return context models.py: from django.db import models # Create your models here. class Blog(models.Model): title = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True) created = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.title class Meta: ordering = ['created'] @property def imageURL(self): try: url = self.image.url except: url = "" return url class Item(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=1000) image = models.ImageField(null=True, blank=True) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) def __str__(self): return self.title @property def imageURL(self): try: url = self.image.url except: url = "" return url any help would be appreciated on this error:MultipleObjectsReturned at /detail/2/ get() returned more than one Item … -
CreateView TestCase doesn't create an object
I have a simple CreateView for Hub objects, allowing users to create hubs. It works perfectly on local server but the TestCase fails. class HubTestCase(TestCase): def setUp(self): User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') def test_create_hub(self): u = User.objects.get(username='john') self.client.force_login(u) response = self.client.post('/hub/create-hub/', {'mydata': 'somedata'}) self.assertEqual(Hub.objects.count(), 1) self.assertEqual(Hub.objects.count(), 1) AssertionError: 0 != 1 class CreateHubView(LoginRequiredMixin, CreateView): model = Hub form_class = HubModelForm template_name = 'hub/hub_form.html' success_url = '/' /hub/create-hub/ is the correct url. -
Django - how to copy one, specific model instance between two databases
I have an application that has a model called CalculationResults. I also have two databases with the same scheme - let's call them "source" and "target". On source database, I have a specific instance of CalculationResults that I want to migrate to "target" database - preferably, I also want to change the field "owner" of this instance in the process. What is the easiest way to achieve this goal? The data I'm talking about is not huge, so it's rather a question of manpower vs computational power. -
Use builtin-lookups in subclasses of a Django builtin-field in Python
While subclassing Django's IntegerField class I stumbled across the fact that the builtin lookups, like eq, gt, le, are not available for my subclassed field. from django.db.models import IntegerField class FooField(IntegerField): pass a = IntegerField() b = FooField() Do I need to register the lookups from the Django sources manually or is there a workaround to have the parent's field lookups in the derived class as well? -
Handling multiple Foreign keys from mutiple models in django
I have my parishioner model like below (Only pasting relevant CODE) class Parishioner(models.Model): family = models.ForeignKey(Family, null=True, on_delete=models.PROTECT, related_name='members') role = models.ForeignKey(FamilyRole, null=True, blank=True, on_delete=models.PROTECT, related_name='role') Parishioner can have one Family and One role in that family So I'm trying to achieve this in my Family Serializer. class FamilySerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField( many=True, queryset=Parishioner.objects.all(), allow_null=True, required=False ) role = serializers.PrimaryKeyRelatedField( many=True, queryset=FamilyRole.objects.all(), allow_null=True, required=False ) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'role', 'enabled') read_only_fields = ('id',) depth = 1 Basically What I'm trying to do is When I add family I can add members(Parishioners) to that family and assign a role each member. What am I doing wrong here ? because when I load my api/family/ I'm getting below error 'Family' object has no attribute 'role' But you can clearly see I added related_name='role' in my Parishioner model. So how can I achieve what I want ? I want to add members(Parishioners) to Family and asssign Role to each member in that Family. Examples for FamilyRole: Father, Mother, son, daughter -
Django 3 test to catch ValidationError is not recognising the raised error
I'm struggling to get my Django test to succeed. The test file is as follows, I've kept it as simple as I can: from django.test import TestCase from django.core.exceptions import ValidationError from .models import Reporter class NewReporterTests(TestCase): def test_reporter_name_should_not_be_empty(self): """ Checking new reporter name cannot be empty and raises validation error correctly """ blank_reporter = Reporter(full_name="") self.assertRaises(ValidationError, blank_reporter.save()) The code which is firing the exception is in the data model as follows: class Reporter(models.Model): uuid = models.UUIDField(default = uuid.uuid4, editable = False, unique=True) full_name = models.CharField(max_length=70) def save(self, *args, **kwargs): if self.full_name == '': raise ValidationError('full_name is empty and is not allowed to be') super(Reporter, self).save(*args, **kwargs) def __str__(self): return self.full_name The output from python manage.py test is: ====================================================================== ERROR: test_reporter_name_should_not_be_empty (gallery.tests.NewReporterTests) Checking new reporter name cannot be empty and raises validation error correctly ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/james/repos/django_play/gallery/tests.py", line 14, in test_reporter_name_should_not_be_empty self.assertRaises(ValidationError, blank_reporter.save()) File "/home/james/repos/django_play/gallery/models.py", line 17, in save raise ValidationError('full_name is empty and is not allowed to be') django.core.exceptions.ValidationError: ['full_name is empty and is not allowed to be'] ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) Destroying test database for alias 'default'... So the test is creating a new reporter with a blank user … -
Use value from one form as value for another form in redirected template (Django)
I have two models def CarModel(models.Model): type = models.CharField() price = models.FloatField() img = models.URLfield() def WrongCar(models.Model): wrong_type = models.CharField() correct_type = models.CharField() price = models.FloatField() I have a product-list of, say, cars using the CarModel but if a car is classified wrong, the user should be able to correct it by filling out the fields in WrongCar by clicking on a button called "correct type", then the user is redirected to the wrong_car-template where the fields from WrongCar are such they can be filled out. When that happens, wrong_type should then automatically be filled out with the value type from the CarModel such that the user only should fill in correct_type and price. I think I can extract it from the request object, but I really dont have any idea of how to do so. -
Django migrations on gitlab CI/CD creates the same 0001_initial.py every time
I've configured GitLab CI/CD for my project. Suppose that I have a model named News and I want to add a new field named 'yyy' to it: class News(models.Model): title = models.CharField(max_length=200, verbose_name="News Title") description = models.TextField(verbose_name="Description") yyy = models.CharField(max_length=10, blank=True, null=True) # New field And my .gitlab-ci.yml file is like this: stages: - build build: stage: build script: - source /path-to-my-project/venv/bin/activate - cd /path-to-my-project/ - python3 manage.py makemigrations news - python3 manage.py migrate news Every time I add a new field to any table and push the changes, gitlab-ci creates the same 0001_initial.py file and I see this message on GitLab CI/CD console: This causes some inconsistent errors ( for example when I want to add a foreign-key field to the model ). A change that I did on GitLab CI configuration was that I changed Git strategy on the General pipelines section from git fetch to git clone and set the Git shallow clone to 0. Settings -> CI/CD -> General pipelines How can I fix this? Thank you -
Django how to restrict staff-user to edit or delete others staff-user post
Right now my all django staff-user can edit or delete others staff-user post. I want they only can able to be edit or delete their own post. How to restrict them to edit or delete others people post? here is my code: views.py: class BlogPublishView(PermissionRequiredMixin,CreateView): raise_exception = True permission_required = "blog.add_post" model = Post form_class = BlogPost template_name = "blog_post.html" #fields = ['title','author','body'] class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost class BlogDeleteView(PermissionRequiredMixin,DeleteView): raise_exception = True permission_required = "blog.delete_post" model = Post template_name = "delete_blog_post.html" success_url = reverse_lazy('blog') urls.py path('blog-post', BlogPublishView.as_view(), name='blog-post'), path('blog-update/<slug:slug>', BlogUpdateView.as_view(), name='blog-update'), path('blog-delete/<slug:slug>', BlogDeleteView.as_view(), name='blog-delete'), html {% if user.is_authenticated %}{% if user.id == post.author.id %} <a href="{% url 'blog-update' post.slug %}"><b>(Edit Blog)</b></a>&nbsp;<a href="{% url 'blog-delete' post.slug %}"><b>(Delete Blog)</b> </a>{% endif %}{% endif %} Let you explain little bit more if you still now don't understand my problem. Assume I have three user in my djano admin panel "A", "B" and "C". user "A" is Admin and user "B" and "C" is staff-user. User "B" and "C" have permission only edit, delete and publish post from admin panel. The problem is user "A" can edit and delete user "B" … -
Django QuerySet filter on inverse relationship
Really struggling with this one and could appreciate some help. I have the following model... class Booking(models.Model): property = models.ForeignKey(Property, related_name='booking', on_delete=models.SET_NULL, null=True) check_in_date = models.DateField() check_out_date = models.DateField() def __str__(self): return f"{self.property}" class Property(models.Model): name = models.CharField(max_length=100, blank = False) def __str__(self): return f"{self.name}" But when I run the following (below) to retrieve property bookings with a date equal to 2021-05-14, instead of just the bookings with a check_in_date of 2021-05-14 being returned, all the bookings for each property are returned even if they don't have a check_in_date of 2021-05-14 Property.objects.filter(booking__check_in_date='2021-05-14') Probably something really simple, but I'm new to Django have been stuck on this all morning and could appreciate some help. Thanks