Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add extra context data in LISTVIEW without breaking built-in pagination
Question about pagination issue: Why if I have for example following LISTVIEW: class BoatListView(ListView): model = BoatModel template_name = "boats.html" paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): context = ListView.get_context_data(self, object_list=None, **kwargs) context["boats"] = BoatModel.objects.all() context["images"] = BoatImage.objects.all() return context and I would use “boats” and “images” context in template , for example : {% for boat in boats %} some code here {% endfor %} ... … …. {% bootstrap_pagination page_obj %} paginator will not work at all in this case ( bootstrap one or original Django https://docs.djangoproject.com/en/2.2/topics/pagination/#using-paginator-in-a-view), no difference? But as soon as I change “boats” and “images” to “object_list” - paginator would begin pagination. Whats the problem and how in this case could I add extra context in view if I need to do so within ability to use paiginator indeed? Thank you! -
writing a validator for hashtag fields in model of django
I have a model that has some of fields: class Book(models.Model): title = models.CharField(max_length=160, help_text='H1(SEO)',blank=True) hashtags = models.TextField(blank=True, validators=[validate_hashtags]) the hashtag inputs should be like: #sth #sth #sth in fact I need to have a space after each hashtag except the last one(the last hashtag doesn't need any space after it). here is my validator function using regex def validate_hashtags(value): string1 = value.split() string2 = re.findall("(#\\w+ )", value) if re.match("^#\\w+$", string1[-1]): matching_counter = len(string2) + 1 else: matching_counter = len(string2) if len(string1) != matching_counter: raise ValidationError("please enter # in the correct format") but it doesn't work properly, can anyone help me? -
'WSGIRequest' object has no attribute 'Session' in django
I am trying to scrape a news website using Django and here the logic is the user can scrape only after 24hour time span I was going through a tutorial for this on youtube. where the code worked fine may because of different Django version I am not sure. But when I try to run the code I get error something like this 'WSGIRequest' object has no attribute 'Session' Here this is the code from django.shortcuts import render, redirect # Create your views here. import requests import os import shutil requests.packages.urllib3.disable_warnings() from bs4 import BeautifulSoup from datetime import timedelta, timezone, datetime from .models import Headline, UserProfile def scrape(requests): user_p = UserProfile.objects.filter(user=requests.user).first() if user_p is not None: user_p.last_scrape = datetime.now(timezone.utc) user_p.save() session = requests.Session() session.headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"} url = 'https://www.theonion.com/' content = session.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") posts = soup.find_all('div', {'class': 'curation-module__item'}) #returns list for i in posts: link = i.find_all('a', {'class': 'js_curation-click'})[1] title = i.find_all('a', {'class': 'js_curation-click'})[1].text image_source = i.find('img', {'class':'featured-image' })['data-src'] media_root = '/c/Users/adity/Desktop/django-scrapper/media_root' if not image_source.startswith(("data:image", "javascript")): local_filename = image_source.split('/')[-1].split("?")[0] r = session.get(image_source, stream=True, verify=False) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) current_image_absolute_path = os.path.abspath(local_filename) … -
Querying Django - Return objects where exactly one field is not null
Using Django 1.8 I'm trying to filter a model on whether only exactly one of the chosen fields are populated. If I had a model like this, I would like to be able to filter on it as below. class MyModel(models.Model): field_a = models.IntegerField(null=True) field_b = models.IntegerField(null=True) field_c = models.IntegerField(null=True) field_d = models.IntegerField(null=True) (field_a__is_null=False, field_b__is_null=True, field_c__is_null=True, field_d__is_null=True) OR (field_a__is_null=True, field_b__is_null=False, field_c__is_null=True, field_d__is_null=True) OR (field_a__is_null=True, field_b__is_null=True, field_c__is_null=False, field_d__is_null=True) OR (field_a__is_null=True, field_b__is_null=True, field_c__is_null=True, field_d__is_null=False) So the queryset should return all objects which have only one of the fields in the model populated and the rest of the fields as null. Is there a way to achieve this through Django queries? -
How to insert data into a relational one to one table in django?
I have a UserProfile table which is in relation with the default Django User table. Here's how it looks. class UserProfile(models.Model): user = user.OneToOneField(User, on_delete=models.CASCADE) section = models.CharField(max_length=255, blank=True) year = models.IntegerField(null=True, blank=True) course = models.CharField(max_length=255, blank=True) qrcode = models.CharField(max_length=255, blank=True) present = models.BooleanField(default=False) I am trying to insert the data into the UserProfile table using the Django Shell. from users.models import UserProfile a = UserProfile(qrcode="hello") a.save() This is how I have always known to insert data into tables, it has always worked. BUT when i try to do this in UserProfile model. I get this exception. NOT NULL constraint failed: users_userprofile.user_id. Which in turn is caused by the following exception Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user. I somewhat understand that I somehow need to supply a user instance. But I am clueless as to how. Can someone please help me. -
How to create or update more than one objects of different models from one end point
How to update more than one object of different model types from one end point. I tried it many ways but i still fails.I tried through nested serializer and create method, but it is still not working class Student(models.Model): name = models.CharField(max_length=300) sex = models.CharField(choices=SEX_CHOICES,max_length=255, null=True) Category = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Registration(models.Model): registration_no = models.CharField(max_length=255, unique=True) student = models.OneToOneField(Student, on_delete= models.CASCADE, related_name='registrations') def __str__(self): return self.registration_no class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Registration fields = '__all__' class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' class StudentDataMigrateSerializer(serializers.Serializer): student = StudentSerializer() registation = RegistrationSerializer() -
Why I should check for 'if id is not None' in this code?
I am following a tutorial entitled Raw Delete Class Based View, Raw Update, list and detail Class Based View respectively. I grasp everything save one. in course_list.html I have the following link: <a class="delete-btn" href="{% url 'courses:course-delete' obj.id %}">Delete</a> If user clicks and confirm deletion, it will delete that course from list of courses. The question is why the instructor is checking for if id is not None:? even if he omit that from code, it will still work fine. Moreover, there're zero chances for 'id' to be None, since the user clicks on a form like this below and the link will guide the user to a specific route which finally deletes that specific course. Please help me understand this! This is the code: class CourseDeleteView(View): template_name = "course/course-delete.html" def get_object(self): id = self.kwargs.get('id') obj = None if id is not None: # why would he do that? obj = get_object_or_404(Course, id=id) return obj def get(self, request, id=None, *args, **kwargs): context = {} obj = self.get_object() if obj is not None: # here, why checking obj for not None? context['object'] = obj return render(request, self.template_name, context) def post(self, request, id=None, *args, **kwargs): context = {} obj = self.get_object() if … -
Running django admin command via curl or reqest.post
I have a special django admin action. I would like to start that account from a jenkins job. Something like this was my idea import json import requests item = { "user": "jenkins", "password": "password", "action": "run", "index": 0} resp = requests.post("http://localhost:8000/admin/app/model/", data=json.dumps(item), # serialize the dictionary from above into json headers={ "Content-Type":"application/json", "Accept": "application/json" }) print(resp) 403 is the answer. Is there a way to run django admin command? How can I include a quereyset? Note: manage.py command is not an option -
Adding one to many relationship in Django models
I have two models in my Django-REST application. a ProjectRequest and a ContactRequest I want to make it so, each projectrequest kan has several Contactrequests. class ProjectRequest(models.Model): project_name = models.CharField(max_length=50) company_name = models.CharField(max_length=50) #make array of technologiestechnologies = models.ArrayField(base_field=) (blank=True) project_description = models.CharField(max_length=200) project_type = models.CharField(max_length=30) budget_estimation = models.IntegerField( default=1000, validators=[ MinValueValidator(1800), MaxValueValidator(5000000) ]) #time_estimation = models.DateTimeField(default=None, blank=True, null=True) class ContactRequest(models.Model): topic = models.CharField(max_length=30) description = models.CharField(max_length=200) time = models.CharField(max_length=15) project_request = models.ForeignKey(ProjectRequest, on_delete=models.CASCADE) so far I have established a relationship, with a foreign key, which works fine as of now. However I want to extends the functionality, so, that the ProjectRequest contains a list of all the projectrequest. I have tried with several different fields, without any luck, and the documentation I can only find fields for ManyToMany and OneToOne. How can this be achieved? -
Django: DRY code with property and queryset that have the exact same role?
In my Django code, for OrderedArticle objects I need to compute a hist_price which is the multiplication of 2 fields: hist_unit_price * quantity. The first way I did it was a simple property: class OrderedArticle(Model): @property def hist_price(self): return self.hist_unit_price * self.quantity Then, I realised that when I need to make extensive computing of these prices, I can't use this property for performance reason, and instead I must compute hist_price at a database level. That's why I wrote a custom queryset for this: class OrderOperationQuerySet(Queryset): @staticmethod def _hist_price(orderable_field): # can be an OrderedArticle or another object here return ExpressionWrapper( F(f'{orderable_field}__hist_unit_price') * F(f'{orderable_field}__quantity'), output_field=DecimalField()) Currently, both hist_price property and _hist_price queryset are used in my code. Question This works well, but I'm annoyed to write the same business logic twice. I have a feeling I'm not doing it "the right way" here. I think I should ensure at a code level, that no matter if I use the property or the queryset, it always returns the same result. In this specific case, the business logic is a simple multiplication between two decimals, so it should be OK, but I'll have other cases in my code where it's way more complex. Do … -
how to add special character "#" in django url?
how to add special character "#" in django url? given below is my code: url(r'updateHashTags/(?P[\w-]+)$', views.updateHashTags, name='updateHashTags') -
NOT NULL constraint failed: users_userprofile.user_id
I am trying to insert django form data inside the UserProfile model in my app. I tried using the django shell and views.py but I keep getting this error. Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) section = models.CharField(max_length=255, blank=True) year = models.IntegerField(null=True, blank=True) course = models.CharField(max_length=255, blank=True) qrcode = models.CharField(max_length=255, blank=True) present = models.BooleanField(default=False) def __str__(self): return self.user.username views.py @staticmethod def generate_qr(request): if request.method == "POST": form = MakeAttendance(request.POST) if form.is_valid(): course = form.cleaned_data.get('courses') section = form.cleaned_data.get('section') year = form.cleaned_data.get('year') profile = UserProfile.objects.get_or_create(user=request.user) userobj = UserProfile(qrcode=unique_id) userobj.save().filter(course=course, section=section, year=year) return redirect('/users/dashboard') This question has been answered many times here, but none of the solutions worked for me. I tried Creating a user profile with get_or_create method. I tried deleting my entire database and making migrations again. I manually tried to pass the user ID but nothing. -
url name accessing another view
I have two path in urls.py file. When I hit a url,instead of picking intended url it is picking another one why? Can anyone please help me. This is my urls.py file: from . import views from django.urls import path app_name = 'olx' path('<slug:category_slug>/',views.product_list, name='product_list_by_category'), path('myPost/', views.myPost, name='my_all_post'), In my html file I am using anchor tag like this: <li class="nav-item"> <a class="nav-link" href="{% url "olx:my_all_post" %}">My Post </a> </li> I tried replacing double inverted commas with single inverted commas like this: href="{% url 'olx:my_all_post' %}" but still it is picking another path: <slug:category_slug>/ -
How do i insert data into field of one model, which is OnetoOneField mapped with another model
class defect_details(models.Model): defect_id = models.CharField(primary_key=True,max_length=20) description = models.CharField(max_length=256) class eda_detail(models.Model): eda_defect_id = models.OneToOneField('defects.defect_details',primary_key=True, on_delete=models.PROTECT) analysis_writeup = models.TextField(blank=True, null=True) In my code i am trying to insert into models but getting the error: from defects.models import defect_details from edainfo.models import eda_detail defect_id = "Jira-SMSV-512" description = "Hello There" defect_obj = defect_details(defect_id=defect_id, description=description) defect_obj.save() eda_obj = eda_detail(eda_defect_id=defect_id) eda_obj.save() ERROR: ValueError: Cannot assign "'Jira-SMSV-512'": "eda_detail.eda_defect_id" must be a "defect_details" instance. -
Reason for IntegrityError on Field deletion?
I have a webservice setup with django backend and I am trying to delete entries for my Field objects. Each Field is assigned to a User and there are a number of Assessments done in the Field. The Assessments are linked to the Fields via a foreign key. Upon deletion of the Field object I want to also delete all the Assessments for that Field, but keep the User. I played around with the on_deletion parameter and if I set it to 'CASCADE' the django admin page shows me all the associated Assessment objects if I try to delete the Field object. However I am still getting the following error: IntegrityError at /admin/dfto/field/ update or delete on table "field" violates foreign key constraint "assessment_field_uuid_fkey" on table "assessment" DETAIL: Key (uuid)=(f3a52c10-33be-42f9-995d-482025cea17b) is still referenced from table "assessment". These are my models for Reference: class Assessment(models.Model): uuid = models.TextField(primary_key=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) field_uuid = models.ForeignKey('Field', models.CASCADE, db_column='field_uuid',blank=True, null=True, related_name='assessments') class Meta: db_table = 'assessment' class Field(models.Model): uuid = models.TextField(primary_key=True) name = models.CharField(max_length=50, blank=True, null=True) country = models.CharField(max_length=50, blank=True, null=True) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') crop_uuid = models.ForeignKey(Crop, models.CASCADE, db_column='crop_uuid') class Meta: db_table = 'field' Can someone explain … -
Don't serialize and unserialize (Pickle and Unpickle) the data while reading and writing from redis
I am working in a system in which multiple code bases access the same redis instance, So while reading some data written by some other code base i am getting the following error. Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.5/dist-packages/django_redis/cache.py", line 32, in _decorator return method(self, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django_redis/cache.py", line 81, in get client=client) File "/usr/local/lib/python3.5/dist-packages/django_redis/client/default.py", line 210, in get return self.decode(value) File "/usr/local/lib/python3.5/dist-packages/django_redis/client/default.py", line 318, in decode value = self._serializer.loads(value) File "/usr/local/lib/python3.5/dist-packages/django_redis/serializers/pickle.py", line 35, in loads return pickle.loads(value) _pickle.UnpicklingError: invalid load key, '{'. Can i turn off this pickling and unpickling? -
I need guidance in building a marketplace with django
I am trying to build a marketplace that functions like a combination of ebay,stockX (and maybe also escrow) with Django 2. I have tried searching for tutorials, books and other resources to help me but there are too many to choose from and they are not specifically targeted towards my goal. Does anyone have guidance including steps I should take, online courses, e.t.c. -
css of bootstrap 3 in django not working as expected
I am trying to use tabbable divs in my django app. The toggle seem to work as expected, the content does show when the next tab is clicked. But the CSS doesn't seem to be working. When I click on tab2, the focus still is in tab 1. On tab 2, it only grays out the button and when I click on other parts of the page the gray out disappears and even if tab2 details are shown, the focus is on tab 1. -
How change fields read_only value based on other fields while creating new record?
I'm trying to make some fields in Django admin read_only based on other fields value on creating and before save the record. for example cloths model: and it has Boolean field called is_t_shirt when the user start fill the form when he put this indicator True I want to make other fields such as long_of_leg read only and when that indicator False this field will be editable. All of that before saving and when editing existing or creating new record, may I can called that as real time or run time. many thanks -
how to get current user with Django’s class-based views
NameError: name 'request' is not defined class PostListViewPrv(ListView): queryset = Post.objects.filter(wszyscy=False, pracownik=request.user, published_date__lte=timezone.now()).order_by('-published_date') context_object_name = 'posts' paginate_by = 2 template_name = 'komunikaty/komunikatyPrv.html' variable pracownik should contain the username -
I installed Django on my pc using pip install django
I installed Django in my pc using pip install Django. but after some time I run the app but it is showing Django not install but Django is installed what is the problem ?? also, Django packages not showing or call. -
How to match a model 'A' with an attribute of a model 'B'?
I'm a French student and I'm learning some Django. My project is to create a web site that allows you to manage a sport tournament. Here is my class diagram : http://prntscr.com/nc39r8 I have an attribute "nbMaxTeam" in Tournament table, if this attribute is equal to 4 for example, I want that when I create a 5th team related to a tournament it tells me that is impossible. How do I do that with my models ? class Team(models.Model): name = models.CharField(max_length=16) nbplayers = models.IntegerField() totalpoints = models.IntegerField() position = models.IntegerField(default=0) pool = models.ForeignKey(Pool, default=None, on_delete=models.CASCADE) tournament = models.ForeignKey(Tournament, default=None, on_delete=models.CASCADE) class Tournament(models.Model): name = models.CharField(max_length=32) dateStart = models.DateField(auto_now=False, auto_now_add=False) dateEnd = models.DateField(auto_now=False, auto_now_add=False) nbMaxTeam = models.IntegerField() -
Dhango 1.11 how to filter content of a filter?
Django 1.11 Python 3.6 I have two models, one is using a dropdown filter of the other model list, and it all works: models.py class Office(models.Manager): ...code.... class Customer(models.Manager): ...code.... office = models.ForeignKey(Office, blank=False, null=False) ...code.... admin.py class CustomerAdmin( admin.ModelAdmin): list_ilter = ["office", "<some_other_filter>"] I get a dropdown with the list of offices on my Customer view just like I wanted, everything works. Now for whatever reason I would like to filter the content of the "office" filter on Customer view, e.g. to remove some entries from that dropdown. Overriding get_queryset in class Office does not do it, it only filters the data that gets fed to the view, but not the list of the entries in the filter. Is there clean and easy way to filter a filter in Django 1.11? -
Django Migration Problem with URL Configuration
When we started our Django project we created migrations and migrated, but now, when we want to alter the data model and run makemigrations we get a large error message (see below). After tracing back the message I discovered that when I comment the path('', include('quizarchiv.urls')), lie while running migrations everything is fine. So I guess that I got two questions: Why does this workaround work (at least for creating the migrations)? How do we adjust our project to work with migrations again? This is the part of our models.py (it's rather long): class questioncategory(models.Model): cat_id = models.AutoField(primary_key=True) cat_name = models.CharField(max_length=255, unique=True) class question(models.Model): q_id = models.AutoField(primary_key=True) q_title = models.CharField(max_length=255, unique=True) q_question = models.CharField(max_length=1000) f_kat = models.ForeignKey(questioncategory, on_delete=models.PROTECT) Full error message: COMPUTER:FOLDER USERNAME$ python3 manage.py migrate Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: questioncategory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File … -
How to get model's objects one by one in Django
I need to make a function that will be launched in celery and will take records from the model in turn, check something and write data to another model with onetoone relationship. There are a lot of entries and using model_name.objects.all () is not appropriate (it will take a lot of memory and time) how to do it correctly.