Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django many to one operatoins
I have two tables in my model as shown below: class grade(models.Model): # Class of student grade = models.CharField(max_length=255, null=True, unique = True) class student(models.Model): name = models.CharField(max_length=255) grade = models.CharField(max_length=255) rollno = models.BigIntegerField() As it can be seen the grade is common in both the tables. I can access these two tables separately using the urls '/grade' for first table and '/name' for second. What I am looking for is a new table which takes both the tables and give something like below (with an example): enter image description here And I want to this so that I can perform the following functions: post,delete /grade/{grade_value}/name/{name_value} Also, get /grade/{grade_value} so that I can get the information about all the students of that grad value. I know I am required to use many to one, but not sure how. Thanks in advance. -
Why Django does not load static file if DEBUG = True?
I mean this is dumb, I wasted couple of hours just to figure whats wrong, the css was not loading, and then I changed DEBUG = False, it worked. My question is if I have an actual server and have DEBUG =True, the css wont load, this is ridiculous. -
fill roaster data in sql database on the basis of month
i want to create a roaster database in which i will fill the employee shifts in advance. so how i can design a database? can you provide the queries i am confusing in can i create a 31 columns for each employee or 31 rows in each employee still i am confuse code in not created how i can create -
how to use ifchanged and rowspan nested regroup in Django template table
my source code: https://gist.github.com/happychallenge/8c5e994f9e4d5c39fa51f5fe3266c32d In nested regroup in table, ifchanged is not working properly. I want to categorize the business cost with cost_type and currency. If I categorize on cost_type, it works correctly. But I categorize the business cost with cost_type and currency, the table is mess. How to modify below code. list incorrect models.py class Service(models.Model): REWORK = '재작업' CUSTOMER = '고객요청' MAINTENANCE = '하자보완' ADDITIONAL = '추가작업' ASTYPE = ( (MAINTENANCE, '하자보완'), (REWORK, '재작업'), (CUSTOMER, '고객요청'), (ADDITIONAL, '추가작업'), ) ACCEPT = 'AS 접수' TEAMASSIGNED = '팀 할당' SITE_COMPLETE = '현장 완료' REPORT = '출장 보고서 작성' COMPLETE = 'AS 처리 완료' STYPE = ( (ACCEPT, 'AS 접수'), (TEAMASSIGNED, '팀 할당'), (SITE_COMPLETE, '현장 완료'), (REPORT, '출장 보고서 작성'), (COMPLETE, 'AS 처리 완료'), ) ascode = models.CharField("AS 코드", max_length=10, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,null=True) customer = models.ForeignKey(CustCompany, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='고객사 명') project_name = models.CharField("Project 명", max_length=100, default='') representative = models.ForeignKey(Representative, on_delete=models.CASCADE, blank=True, null=True, verbose_name='고객 담당자') asmans = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='asmans') created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_at',) def __str__(self): return self.ascode def get_absolute_url(self): return reverse('fta:service_detail', args=[self.id]) def get_cost_count(self): return self.costs.count() def get_costs(self): return self.costs.all().order_by('ctype', 'currency') class Cost(models.Model): TRAFFIC = 'TRANSPORTATION' FOOD = 'FOOD' HOTEL = 'HOTEL' BUSINESS = 'TRIP' … -
Customize form validation error display in Django
When I use form.is_valid() Django automatically outputs the validation error message shown in the link below (circled in red). But what if I want to customize that message with custom logic but display it in the same way. How do I do that? The page linked below allows you to register a phone number to a database. I want to add an unsubscribe page where the database is queried and if the phone number exists then delete the number. But if it doesn't exist in database, I want to display the message "Phone number is not currently registered." https://imgur.com/SxqIt1N (sorry for external link, can't embed images yet) models.py class PhoneNumber(models.Model): country = models.CharField(max_length = 1) area = models.CharField(max_length = 3) phone_number = models.CharField(max_length = 7) reg_date = models.DateTimeField(default=timezone.now) class Meta: unique_together = ('country', 'area', 'phone_number') def add_to_database(self): self.save() def __str__(self): return str(self.country) + str(self.area) + str(self.phone_number) -
Django Cannot find cursor object in connection object
I am developing a web application using django. I am new Django. I have call a stored procedure from my application. I gone through the django documentation and i found out that using cursor object i can call the procedure. But i cannot find the cursor object in connection object. This is how my code looks like : from django.db import connection cursor = connection.cursor() But i cannot find cursor object itself in the connection. Please help me out where i am going wrong. -
Bootstrap 4 navbar active class not working [duplicate]
This question already has an answer here: How to change active class while click to another link in bootstrap use jquery? 8 answers In a website, I am trying to get this specific navbar active class to work. When I click on the current page, I would like the link to turn blue. Since I am a beginner, any help would be really appreciated. Thanks in advance. Here is the navbar : <div class="nav-scroller py-1 mb-2"> <nav class="nav d-flex justify-content-between"> <a class="active p-2 text-muted" href="#"><b> Business</b> </a> <a class="p-2 text-muted" href="#"><b> Design </b></a> <a class="p-2 text-muted" href="#"><b>Travel </b></a> <a class="p-2 text-muted" href="#"><b> Opinion </b></a> </nav> </div> Here is the javascript code: $('.nav .p-2 .text-muted').click(function(){ $('.nav .p-2 .text-muted').removeClass('active'); $(this).addClass('active'); }) I also used CSS to turn the current navbar page link to blue: .nav > .p-2.activate { color:blue; } -
Django: IntegrityError duplicate key value violates unique constraint "ride_ownerrequest_driver_id_key" DETAIL: Key (driver_id)=(2) already exists
Here I have three models: OwnerRequest: class OwnerRequest(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner_owner_request_set') driver = models.OneToOneField(User, on_delete=models.CASCADE, related_name='driver_owner_request_set', blank=True, null=True) and Vehicle class Vehicle(models.Model): plate_number = models.CharField(max_length=10, primary_key=True, blank=False, null=False) driver = models.OneToOneField(User, on_delete=models.CASCADE, blank=False, null=False) and User class User(AbstractUser): ROLE = Choices('owner', 'driver', 'sharer') catalog = models.CharField(max_length=6, choices=ROLE, blank=True, null=True) plate_number = models.CharField(max_length=10, blank=True, null=True) and my problem happens at: def driver_confirm_request(request, pk): to_confirm = get_object_or_404(OwnerRequest, pk=pk) driver = get_object_or_404(User, pk=request.user.id) if to_confirm.status == 'confirmed': messages.info(request, "You are slow!") return redirect('ride:home') if driver != request.user: return redirect('ride:home') to_confirm.driver = driver to_confirm.status = 'confirmed' to_confirm.save() # HAPPENS HERE messages.info(request, "Ride Confirmed!") return redirect('ride:home') Could anyone give some hint? Thanks! -
Showing hyperlinks to external websites in Django (with Sites Framework). Sites Model is putting a text prefix
I am running into some problem with Django hyperlinks on a template page due to usage of Sites framework. Tried many options but they are not working. models.py class User(AbstractUser): first_name = models.CharField(verbose_name="Name", max_length=30) last_name = models.CharField(verbose_name="Surname", max_length=60) facebook = models.URLField(max_length=400, blank=True, default='https://www.fb.com') class SiteAdmin(admin.ModelAdmin): fields = ('id', 'name', 'domain') In the database name=n/a, domain = booksite for the site model In the template, called the link using absolutize module (https://pypi.org/project/django-absoluteuri/) as below <div class='icon social fb' ><a class=' fa fa-facebook' title="click to view facebook profile" style="color:white;" href="{{ object.facebook|absolutize }}" ></a></div> however, the hyperlink is rendering as n/ahttps://www.fb.com. The n/a is being picked up from the sites model. May be this is a very simplle thing but am not able to figure out. Can someone please point out, how to get rid of the n/a prefix in the hyperlink? I tried deleting the row in the sites model but the app is not working without at-least one data point in the sites model. Greatly appreciate any help from the community. -
How to retrieve selected data from Django Choice Field?
I want to retrieve the question_description answer_descritption and question_image answer_image if found in the database according to topic and question type using two ChoiceField for both: Topic and Question Type. However, I don't know how to do that. I have seen some tutorials and gotten glimpses of what I have to do, but I am not sure how to preform the same techniques on my case because online there are not that many ChoiceField examples, except that there are general examples on how to use forms and extract data from the database. This is the models.py from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __str__(self): return '%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __str__(self): return '%s' % self.image_file class Question(models.Model): question_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.question_type class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) answer_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) def … -
How to generate a pdf report with django
I need to generate a pdf report from a django view, ir must contain múltiple fields from the témplate that the user must fill. Please i Will thanks any help -
How to incorporate Reportlab with Django Class Based View?
I am trying to convert my HTML to a PDF. I watched this tutorial, https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ and I was able to successfully get the tutorial to work with hardcoded values. The problem is...I can't figure out how to dynamically incorporate my model and it's attributes into this example. Here are the steps I followed... First I installed reportlab into my environment with the following version... pip install --pre xhtml2pdf This worked... Then I added a utils.py file to my project as instructed. Then I copied this code into my utils.py file... from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Then I created an HTML file like the one below: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> <style type="text/css"> body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: 22px; font-weight: 100; /* text-align: right;*/ padding: 10px 20px 0px 20px; } .title span { color: #007cae; } .details { padding: 10px 20px 0px 20px; text-align: … -
How to specify a log handler class with a required argument using dictConfig syntax?
I Would like to use the Notifiers logging handler in Django. I have my loggers specifed using dictConfig syntax. Here is an example from Notifer's own docs: >>> import logging >>> from notifiers.logging import NotificationHandler >>> log = logging.getLogger(__name__) >>> defaults = { ... 'token': 'foo, ... 'user': 'bar ... } >>> hdlr = NotificationHandler('pushover', defaults=defaults) >>> hdlr.setLevel(logging.ERROR) >>> log.addHandler(hdlr) >>> log.error('And just like that, you get notified about all your errors!') The dictConfig syntax is like this: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/path/to/django/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } How do I add the Notifier handler using the latter syntax? I can't find a way to set the first, required argument to NotificationHandler. -
How to ensure tests.py test is hitting correct endpoint
My unit test in Django is failing because it is returning a 404. I know my self.client.get(... is probably going to the wrong base directory but not sure how to fix. from django.test import TestCase, Client import random class TestViews(TestCase): def test_valid_results(self): client = Client() data = { 'device_uuid': '00000000-0000-0000-0000-000000000000', 'end_time': '1524835983', 'window_time': str(random.randint(1, 3600)), 'num_windows': str(random.randint(1, 10)) } response = self.client.get('api/device_uuid/' + data['device_uuid'] + '/end_time/' + data['end_time'] + '/window_time/' + data['window_time'] + '/num_windows/' + data['num_windows'], content_type="application/json") assert 200 == response.status_code This test is located in the tests.py file in my api directory of my Django App. I specify the endpoint (starting with /device_uuid...) in the urls.py in this same directory (api). My main urls.py is in my bandwidth_base directory and includes path('api/', include('api.urls')) If any further info is help please let me know. -
How to iterate child data in nested for loop in relation to parent data for loop
I have a for loop with a nested for loop. The parent for loop displays all the ingredients for the meal. Each ingredient has sub ingredients that I want to display under the "complete" ingredient. Below is a general idea of the tables. I am not actually making an app related to food but this is just to simplify things. Meal Table +---------+-----------------------+ | mMealID | mMealName | +---------+-----------------------+ | 0001 | English Big Breakfast | +---------+-----------------------+ | .... | ... | +---------+-----------------------+ Ingredient Table +-----------------+-------------------+-----------+ | ingIngredientID | ingIngredientName | ingMealID | +-----------------+-------------------+-----------+ | 0001 | Bacon | 0001 | +-----------------+-------------------+-----------+ | 0002 | Baked Beans | 0001 | +-----------------+-------------------+-----------+ | 0003 | Sausage | 0001 | +-----------------+-------------------+-----------+ | 0004 | Coffee | 0001 | +-----------------+-------------------+-----------+ | .... | ... | .... | +-----------------+-------------------+-----------+ Sub Ingredient Table +-------------------+---------------------+----------------+----------+ | siSubIngredientID | siSubIngredientName | siIngredientID | siMealID | +-------------------+---------------------+----------------+----------+ | 0001 | Fat | 0001 | 0001 | +-------------------+---------------------+----------------+----------+ | 0002 | Pork | 0001 | 0001 | +-------------------+---------------------+----------------+----------+ | 0003 | Salt | 0001 | 0001 | +-------------------+---------------------+----------------+----------+ | 0004 | Tomato Sauce | 0002 | 0001 | +-------------------+---------------------+----------------+----------+ | .... | ... | .... | .... | +-------------------+---------------------+----------------+----------+ … -
Proxy model for Multiple models in Django
I would like to display a model in the django admin but with the logic to choose between 2 models to display. Current Implementation: Models class User(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=30, blank=True) class ExpectedNames(User): class Meta: proxy=True` Admin @admin.register(ExpectedNames) class ExpectedNamesAdmin(admin.ModelAdmin): date_hierarchy = 'created' What I Would like to DO: # something like this Models class User(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=30, blank=True) class User2(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=30, blank=True) class ExpectedNames(User): class Meta: proxy=True if name == "Rick": return User else: return User2 Admin @admin.register(ExpectedNames) class ExpectedNamesAdmin(admin.ModelAdmin): date_hierarchy = 'created' Any suggestions not sure if this is the correct way to do this. -
how to open relportlab generated encoded pdf in jquery in django powered website
i am generating an pdf with ajax call to my python end and getting the reportlab generated code on success. But i dont know how to show it so i can get the pdf from it. %PDF-1.4 %���� ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R /F2 4 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /BitsPerComponent 1 /ColorSpace /DeviceGray /Filter [ /ASCII85Decode ] /Height 23 /Length 223 /Subtype /Image /Type /XObject /Width 24 >> stream 003B00 002700 002480 0E4940 114920 14B220 3CB650 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 1E1800 1FF800> endstream endobj 4 0 obj << /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font >> endobj 5 0 obj << /Contents 12 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 11 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject << /FormXob.c7485dcc8d256a6f197ed7802687f252 3 0 R >> >> /Rotate 0 /Trans << -
Why prefer factories over fixtures in Python testing?
From The Best of the Best Practices (BOBP) Guide for Python (https://gist.github.com/sloria/7001839), why should we prefer factories over fixtures? The link is to Factory Boy (https://github.com/FactoryBoy/factory_boy ) but I'm not clear on why, and in what scenarios, one should prefer factories over fixtures for tests. Is this always the case? When is it not? -
Django: Importing models in models.py from outside project does not work
I'm trying to define some Django models outside of a Django project folder (I'm just using Django ORM capabilities without web application functionality) and import them into the models.py of an app within Django project. I know that models.py can be 'split up' by creating a models package, having multiple modules defining models and importing into init, so I thought this would work the same way. Directory structure is like: - root - tasks - taskA - models.py - taskB - models.py - orm - apps - app1 - models.py - base_models.py - app2 - models.py - base_models.py - manage.py - settings.py Basically the Django apps categorise the type of model (an abstract base model is defined in appX.base_models.py), and the tasks define and use their own versions /subclasses of the different model types, which are then imported into the django app models.py to be managed by Django so for example: in root.orm.apps.app1.models.py: from root.tasks.taskA.models import ModelType1A from root.tasks.taskB.models import ModelType1B However I try launch a task (which calls django.setup()) or manage.py makemigrations, I get: RuntimeError: Model class root.tasks.taskA.models.ModelType1A doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS And yes the apps are included in INSTALLED_APPS (it's … -
Django Infinity as datetime default
I'm struggling to see how I can add a datetime field with an infinity end date. Setting the default to 'infinity' results in a Django.core exception django.core.exceptions.ValidationError: ["'infinity' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] NB: This is not the same as defining it Null (None). It's specially supported in postgres as just a string condition check for example SELECT * FROM table WHERE dt = 'infinity'; // or SELECT * FROM table WHERE NOT isfinite(dt); Nulls won't show in this, nor can you do a between condition on a Null value unless you COALESCE it, but that will result in a sequential scan. Any ideas? -
Class Views and NoReverseMatch
I am new to coding and especially new to working with Django. I want to build a small "forum" for me and the other students and it works pretty fine. There is just one error I encounter over and over. Exception Type: NoReverseMatch Exception Value: Reverse for 'thread-create' with arguments '('',)' not found. 1 pattern(s) tried: ['forum/(?P[0-9]+)/add/$'] I can work around it using functions instead of class Views, but I doubt that's how its supposed to be done. I have the feeling I am missing something very important while working with class views. I really would appreciate if someone could help me out :-) It's the links that are not working. {% url 'user-posts' thread.author.username %} and more important: {% url 'forum:thread-create' thread.id %} also not working while using classes is: {% for thread in threads.thema_set %} (I only want to see the threads that are bind to a certain thema. That also works pretty well with functions) And you might asking why I not just use the functions. A) I want to know what I am doing wrong. B) I want to esay paginate my sited :-D models.py from django.db import models from django.urls import reverse from PIL import … -
Filter Django Admin queryset where related OnetoOne already exists
I'm looking to implement a filter on my queryset within django-admin to avoid the error message "already exists" The table is a master mapping table where IDs are mapped from different sources. IDs can only be mapped once thus most fields are OneToOne. I've set up my mapping model like so class Dim_Fund_Manager_Mapping(Trackable): fund_manager_id = models.AutoField(primary_key=True) sharepoint_fund_manager = models.OneToOneField(sharepoint_fund_manager, models.DO_NOTHING) evestment_fund_manager = models.OneToOneField(evestment_fund_manager, models.DO_NOTHING) approved = models.BooleanField(default=False) class Meta: unique_together = (('sharepoint_fund_manager', 'evestment_fund_manager'),) verbose_name_plural = 'Fund Manager Mapping Master' When a map is made in admin I would like those sharepoint_fund_manager and evestment_fund_manager to no longer appear in the queryset. @admin.register(Dim_Fund_Manager_Mapping) class ChampFundManagerAdmin(admin.ModelAdmin): def get_queryset(self, request): return qs = super().get_queryset(request).select_related( 'sharepoint_fund_manager', 'evestment_fund_manager', ) This is as far as I've gotten to with my knowledge. Does anybody have some code/help please -
validating errors in custom form class
I'm trying to check that each form field has an error or not and if it has an error ,then add a class to that field widget. for example: class ChangePasswordForm(PasswordChangeForm): class Meta: model = User fields = ('old_password' , 'new_password1' , 'new_password2') def __init__(self , *args , **kwargs): super(ChangePasswordForm , self).__init__(*args , **kwargs) self.fields['new_password1'].widget.attrs['style'] = 'direction:rtl' self.fields['new_password1'].widget.attrs['placeholder'] = '' self.fields['new_password1'].widget.attrs['class'] = 'form-control' if self.fields['new_password1'].errors: self.fields['new_password1'].widget.attrs.update({'class' : 'is_invalid'}) self.fields['new_password2'].widget.attrs['placeholder'] = '' self.fields['new_password2'].widget.attrs['class'] = 'form-control' self.fields['new_password2'].widget.attrs['style'] = 'direction:rtl;tex-align:right' self.fields['new_password2'].help_text = '' self.fields['old_password'].widget.attrs['placeholder'] = '' self.fields['old_password'].widget.attrs['class'] = 'form-control' self.fields['old_password'].widget.attrs['style'] = 'direction:rtl;tex-align:right' self.fields['old_password'].help_text = '' if self.fields['old_password'].errors: self.fields['old_password'].widget.attrs.update({'class' : 'is_invalid'}) I want to check that old_password has an error or not and if so it adds a class to it's widget. This code is wrong and it shows an error that CharField has no attribute errors. How I can write something like this? -
How to create a link to blog user's profile in the navigation bar when the users profile is visited?
I'm using django to build a blog and I want to add a feature where when you click on a user's profile their name stays in the navigation bar (linking to their profile) until another users profile is visited. I tried doing this: < a class="nav-link" href="{% url 'user-profile' user.id %}">{{ object.first_name }} {{object.last_name }} < /a > but the user's name goes away when the page is refreshed or another link is clicked and the link for it doesn't work at all. -
Server does not support SSL, but SSL was required
Attempting to spin up a sqlite server, and getting the following error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x110b0aa60> Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: server does not support SSL, but SSL was required