Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering using multiple foreign keys in Django
So I already have an Exam stored, and able to filter out the questions that are from only from that exam, however, how would I only print out the answer choices to their designated question? When I try to print it out in my template all of the answer choices print under each of the questions instead of filtering out, would I need a for loop/if statement within the template to correctly do this or? I've tried a number of things and the Docs most likely have the answer but I just need help understanding from django.db import models class Exam(models.Model): name = models.CharField(max_length=64, verbose_name=u'Exam name', ) slug = models.SlugField() def __str__(self): return self.name class Question(models.Model): question_text = models.CharField(max_length=256, verbose_name=u'Question\'s text') is_published = models.BooleanField(default=False) exam = models.ForeignKey(Exam, related_name='questions') def __str__(self): return "{content} - {published}".format(content=self.question_text, published=self.is_published) class Answer(models.Model): text = models.CharField(max_length=128, verbose_name=u'Answer\'s text') is_valid = models.BooleanField(default=False) question = models.ForeignKey(Question, related_name='answers') def __str__(self): return self.text How would I be able to print the Exam on the template, and filter it in order to print questions, and the answers related to it from the foreign key -
(Django) Solve Lazy Reference pointing to deleted model
I accidentally deleted a model in an app before removing all the relationships pointing to it. Now I am getting a lazy reference error since the model is already deleted. I am using Django 2.2 with PostgreSQL. So I have a Core app with a model called Analysis inside it. I had another app named Projects, and inside I have a model named Project with m2m relationship pointing to Analysis of Core like below. core_analysis= models.ManyToManyField(core.Analysis,verbose_name="Core Analysis", blank=True). I deleted Analysis from Core, and removed m2m core_analysis from Project. Accordingly, django created DeleteModel migration in Core and RemoveField migration in Projects. However, I only ran migration in Core, and now when I tried to resume migration Project throws Lazy Reference Error. ValueError: The field projects.Project.core_analysis was declared with a lazy reference to 'core.analysis', but app 'core' doesn't provide model 'analysis'. Is there a way to fix this issue while not having to lose any data. -
Searching through Django admin spinner selector
Is it possible to search in Django admin spinners or selectors? When there is a lot of items it becames a nightmare: -
How to create robust composite primary key in Django?
I would like to create in Django model a composite primary key, which is a text prefix and then an index within that prefix. For example, I would like that the model upon save() generates this order: prefix - id ABC - 1 ABC - 2 ABC - 3 ABC - 4 XYZ - 1 ABC - 5 XYZ - 2 XYZ - 3 ABC - 6 XYZ - 4 XYZ - 5 etc. I have already tried to create a metadata with unique_together = [['Prefix', 'Id']] That works for uniqueness, but it does not compute the lowest id per prefix, the id is just always incremented: prefix - id ABC - 1 ABC - 2 ABC - 3 ABC - 4 XYZ - 5 ABC - 6 XYZ - 7 XYZ - 8 ABC - 9 XYZ - 10 XYZ - 11 etc. class Invoice(models.Model): prefix = models.CharField(max_length=12, default='') invoice_ref = models.CharField(max_length=40, default='') class Meta: unique_together = [['prefix', 'id']] I could compute the id in the overloaded save() method, however how much robust is that approach? There would be several non-atomic queries to database: def save(self): try: m = Invoice.objects.last(prefix=self.prefix) self.id = m.id + 1 except Exception as e: … -
Django - In the admin page, how do I widen the dropdown choices?
How do I increase the width of the django foreign key dropdown text? For example, I want to be able to see the full line of text: How many possum? - I have known for a long time that, while wealth is unlikely to decrease happiness, one can acquire happiness for almost no financial cost. Currently, the above text is abridged in the dropdown: !(https://i.imgur.com/BTVSko3.png) As background information, the dropdown shows foreign keys that are linked to other foreign keys. Code (truncated): admin.py @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): form = CustomQuestionAdminForm fieldsets = [ (None, {'fields': ['parent_option', 'question_bank', 'question_text', 'category', 'date_published']}), ] inlines = [OptionInline] list_display = ('question_text', 'category', 'date_published') search_fields = ['question_text'] class CustomQuestionAdminForm(forms.ModelForm): class Meta: model = Question fields = [ 'question_text', 'parent_option', 'question_bank', 'date_published', 'category' ] def __init__(self, *args, **kwargs): super(CustomQuestionAdminForm, self).__init__(*args, **kwargs) self.fields['parent_option'] = ModelChoiceFieldOptionsAndQuestionText( queryset=Option.objects.exclude(question=self.instance), required=False, ) Actual -> Dropdown display does not show all of the choice text (see screen shot above) Desired -> The dropdown display shows all of the choice text, preferably regardless of its length. -
How to show model field's in admin list view, but show only related models inside its detail / change form?
assume we have the following: Models.py class Father(models.Model): name = models.Charfield(...) ... class Child(models.Model): one = ForeignKey(Father, ...) ... class GrandChild(models.Model): one = ForeignKey(Child, ...) ... I registered all Father() objects in the admin, and it shows the father's name and other fields on the list page (works fine)... But when clicking it into the change form, I only want it to show all Child() and GrandChild() objects as if they were inline (according to each parent class), and to allow / disallow changing of those forms when hitting save... Keeping the Father() fields on this page as readonly is fine too, but not required. Normally, the easiest way is to use an inline, but I can't do that here. The problem is due to the @admin.register(Father) decorator, because when I change the ModelAdmin.form to the ChildForm(), it always gives an error saying the Father() fields are required: ERRORS: : (admin.E108) The value of 'list_display[0]' refers to 'a_field', which is not a callable, an attribute of 'FatherAdmin', or an attribute or method on 'app_name.Father'. Anyone know of any ways to do this?? I know I can do this by manually making my own views and templates, but I'm trying to … -
Django model reference to a postgres foreign table (clickhouse_fdw)
I have a Django project. I've connected a clickhouse table with a postgres table using clickhouse_fdw. It's working using psql commands, but now I want to access from django. I've added a new model for clickhouse table and ignored migrations and managment for it in django. Then in django shell I've tried: MyModel.objects.raw('SELECT * FROM mytable LIMIT 1')[0] and I get: ProgrammingError: permission denied for foreign table mytable Any suggestions? -
Country wise access restriction in Django project
When an user open any link of Django project, before open this link, I want to apply country wise restriction. Admin has right to add country in Database table, if country is available in table, then url will open otherwise it will show a message, restricted country -
Unable to display foreign key attribute on a django app
I have two models in my db. They are:- Modules Topics Topics is a foreign key of Modules. This is my models.py from django.db import models class Modules(models.Model): name = models.CharField(max_length=500,null=False) def __str__(self): return self.name class Topics(models.Model): modules = models.ForeignKey(Modules,on_delete=models.CASCADE) name = models.CharField(max_length=500) Here is my HTML code:- {% extends "algorithms/header.html" %} {% block content %} {% if all_topics %} <div class="row"> {% for topic in modules.topics_set.all %} <div class="col s12 m6"> <div class="card cyan lighten-4"> <div class="card-content black-text"> <span class="card-title"><b>{{ topic.name }}</b></span> <p>{{topic.algorithm_content|safe}}</p> </div> <div class="card-action"> <a href="/algorithms/{{ module_name }}/{{ topic.name }}/">View</a> </div> </div> </div> {% endfor %} </div> {% else %} <h3>The admin has not uploaded any courses yet</h3> {% endif %} {% endblock %} I am unable to see any data of 'Topics' model. -
wagtail error in postgres_search update_index
I'm migrating my site from wagtail 1.10/django 1.11/python 2.7 to wagtail 2.5.1/django 2.2.3/python 3.7. I've been using the wagtail postgres_search backend. All my tables migrated successfully except postgres_search. To get things to work on my development machine I had to drop the postgres_search table, re-run the postgres_search migrations, and then run update_index. On the server I did the same thing, but update_index throws an exception. The main difference between my machines is that I'm running Postgres 11 on my development machine, and stuck on 9.4 on the server. Whatever is causing this problem is also (I think) causing a TransactionManagementError whenever I try to save any changes to pages on the server. If I use the default database search backend on the server, everything works fine. I'm wondering if my problem could be related to this django ticket: https://code.djangoproject.com/ticket/30446 Any suggestions would be greatly appreciated. Here's my traceback: (venv) [aapa@web552 physanth2]$ python3.7 aapa/manage.py update_index Updating backend: default default: Rebuilding index physanth default: physanth.StandardIndexPage Traceback (most recent call last): File "aapa/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/aapa/webapps/physanth2/venv/lib/python3.7/site-packages/django/core/management/base.py", line … -
How to take info from sub-object in request before validating in Django?
I'm writing an api in Django for which I use the django-rest-framework. I've got a simple model as follows: class PeopleCounter(models.Model): version = models.CharField(max_length=10) timestamp = models.DateTimeField(db_index=True) sensor = models.CharField(max_length=10) count = models.IntegerField() And I've got a serializer as follows: class PeopleCounterSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PeopleCounter fields = [ 'version', 'timestamp', 'sensor', 'count', ] When I post the following data to this endpoint it works great: { "version": "v1", "timestamp": "2019-04-01T20:00:00.312", "sensor": "sensorA", "count": 4 } but unfortunately I need to adjust the endpoint for the data to arrive as follows: { "version": "v1", "timestamp": "2019-04-01T20:00:00.312", "data": { "sensor": "sensorA", "count": 4 } } I thought I needed to add a create method to the serializer class. So I tried that, but when I post the json with the "data" object I get a message that the sensor field and the count field are required. Does anybody know where I can normalize this data so that I can insert it in the database correctly? Also, what if I want to serve the data through the same endpoint like this as well, where would I be able to define that? All tips are welcome! -
'NoneType' object has no attribute 'slug'
I got this error " 'NoneType' object has no attribute 'slug'" in create_path, line 48: return 'uploads/{0}/{1}'.format(instance.game.slug, filename) model.py def create_path(instance, filename): return 'uploads/{0}/{1}'.format(instance.game.slug, filename) class OnlineGame(models.Model): name=models.CharField(max_length=120) slug=models.CharField(max_length=25,unique=True) icon=models.ImageField(upload_to='uploads/onlinegame',blank=True,null=True) class Player(models.Model): slug=models.SlugField(unique=True,max_length=120) fullname=models.CharField(max_length=120,null=True,blank=True) game=models.ForeignKey(OnlineGame,null=True,blank=True,related_name='playergame',on_delete=models.PROTECT) -
Cant change Django debug language
my django settings is already in Portuguese and English, as you can see below: LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', 'English'), ] But when there is an error in the code, it comes in german. I am located in Germany, I have a German laptop, but my Windows is also configured in English. I don't know where this german is coming from. See an example here: https://ibb.co/cvhBcvd PLEASE, I don't need help with the error, I just would like to have all my errors in English. Thank you gurus. -
How to fix the issue "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet"?
I have deployed my django webapp to my heroku server and it was working fine until I added a websocket connection that shows the contents of a model object in a separate url as soon as that object is created. For this, I used Django channels with a redis server hosted on redislabs. To run asgi app, I tried to use daphne server but when I try to run the daphne server with the following command: $daphne smartResturant.asgi:channel_layer --port 8888 , it says "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" My asgi.py import os import django from smartResturant.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smartResturant.settings") django.setup() application = get_default_application() My settings.py ASGI_APPLICATION = 'smartResturant.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": ['redis://:xxxxxxxx@redis-13131.c85.us-east-1-2.ec2.cloud.redislabs.com:13131'] }, }, } It works fine when I run locally without using daphne server. But I found out that to run asgi based apps on a hosted server, you have to use daphne server and I am unable to run it. Any help will be appreciated! -
How to access object.pk in a function listview without having to iterate through the objects with a for loop?
I have a FBV using django-tables2 so the the template already call the objects but i need to add a button that triggers a modal so I need to call the pk of the objects inside the button here's the views.py def Patients_list(request): patients = Patient.objects.filter(user=request.user) table = PatientTable(patients) RequestConfig(request).configure(table) return render(request, 'patients/patients_list.html',{ 'table' : table, 'patients':patients, }) and the button is callable at the tables.py class PatientTable(tables.Table): FirstName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) LastName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) Telephone_no = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) delete = TemplateColumn('<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Deleta</button>',extra_context={'patient': 'Patient'}) class Meta: model = Patient attrs = {'class': 'table table-striped table-hover'} exclude = ("user", "Notes", "Adress") template_name = 'django_tables2/bootstrap4.html' and the template: {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} <div id="content"> {% if user.is_authenticated %} <h1> Patients list: </h1> <br> <a href="{%url 'patients:patient_create'%}" class="btn btn-info" role="button">Add Patient</a> <br> <br> {% render_table table %} {% else %} <h2>please login</h2> {% endif %} </div> <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete" aria-hidden="true"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete patient!</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Are you sure you want to delete this patient?</p> </div> … -
How can I grab the id of foreign key to use as a column for bulk file imports?
I'm working with the Django import / export library to bulk upload models using an XLSX/CSV file. I have two models - Company and Competitor. Competitor has a many-to-many relationship with Company. I want admin users to be able to upload a bunch of competitor names and be able to select which Company they all correspond to. I want the ID of the Company it corresponds to, to be marked in another column. How can I do this? I have followed the instructions on the library's Getting Started page but I just can't get the company ID to persist. These are my models: # app/models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=200) website = models.CharField(max_length=200) class Competitor(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name='The related company' ) competitor_name = models.CharField(max_length=200) competitor_website = models.CharField(max_length=200) In forms.py I've defined the custom forms allowing users to select from a list of already defined Company records. # app/forms.py from django import forms from import_export.admin import ImportForm, ConfirmImportForm from .models import Company, Competitor class CompetitorImportForm(ImportForm): company = forms.ModelChoiceField( queryset=Company.objects.all(), required=True ) class CompetitorConfirmImportForm(ConfirmImportForm): company = forms.ModelChoiceField( queryset=Company.objects.all(), required=True ) Set up my import-export resources in resources.py from import_export import resources from .models import Company, … -
angular-gettext does not pick the strings from .PO files
I have installed everything according to documentation. Some of the things are working as per the documentation. Is there something like Django translation which automatically replaces the translation for specific language if you select those lang Index.html <!DOCTYPE HTML> <html> {% load static %} <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script> <script src="{% static 'first.js'%}"></script> <script src="{% static '/angular-gettext/dist/angular-gettext.js'%}"></script> <script type="text/javascript" > angular.module('first').run(function (gettextCatalog) { gettextCatalog.setCurrentLanguage('fr'); gettextCatalog.debug = true; debugger; gettextCatalog.setStrings('fr', { "Hello!":"Bonjour !"}); }); </script> </head> <body> <div ng-app="first"> <translate>Hello!</translate> Sagar <h1 translate>Hello!</h1> </div> </body> </html> PO file msgid "" msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Project-Id-Version: \n" "POT-Creation-Date: \n" "PO-Revision-Date: \n" "Language-Team: \n" "MIME-Version: 1.0\n" "X-Generator: Poedit 2.2.3\n" "Last-Translator: \n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "Language: fr\n" #: ui/templates/admin/firsttranslate/index.html:24 #: ui/templates/admin/firsttranslate/index.html:26 msgid "Hello!" msgstr "Halo !" When I run my code It searches for Hello and Replaces with Bonjour But I want it to be replace automatically as Django does Thanks in advance. -
uwsgi_pass does not forward SCRIPT_NAME header
I'm trying to make my web app (Django/wsgi-based) available from some subfolder of the main domain. I'm using docker for my app, and static files, so I have main nginx on my server as reverse proxy, another nginx in "nginx" container which routes the stuff for my app and uWSGI in the second container which serves actual Django data And I want my app to be available externally as myserver.com/mytool, in the same time I do not want to hardcode mytool anywhere in my app. Usually SCRIPT_NAME header is used for this type of stuff, so here is nginx configuration on the host: server { listen 80; # Just for sake of simplicity, of course in production it's 443 with SSL location /mytool/ { proxy_pass http://127.0.0.1:8000/; include proxy_params; proxy_set_header SCRIPT_NAME /mytool; # <--- Here I define my header which backend should use } } Then in my docker-compose I expose 8000:80 for nginx and here is internal nginx configuration: server { listen 80; location / { include uwsgi_params; uwsgi_pass web:3031; } } With this configuration I would expect that my Django app receives SCRIPT_NAME header, but apparently it does not. In the same time if I define custom headers like … -
What programming language should I use? [on hold]
I need to create an application and I don't know which language is suitable for it. This application should have a page where the user fills a lot of forms (like dates, strings, numbers, an adjustable line graph, a table etc...) and at the bottom should be a "SAVE" button. When the user clicks this button these things should happen: 1)The application takes all the values that the user filled the forms with and should save them in variables (or in some other way) 2)The application should create a new pdf document with all these forms that the user filled and add the forms compiled by the user, for example: in the first page, form date: the users inserts 11-05-2019, in the new pdf document there should be at the bottom left of the page a String which says: "This document was created the 11-05-2019" 3)The application should automatically save the new pdf document just created in a folder without asking the user, but using the informations provided by the forms filled by the user, for example: in the first page there is form a which the user fills with: ABC so the folder in which the document must be … -
Can someone suggest how to implement custom Django PasswordResetView?
I want to send password reset link to only confirmed email address. And also user can request password reset link by searching by username or email address which is not available in default django. I have been trying and editing the default django password reset view and form for many days. But not working for me. -
CreateView not creating any object
This is my model: class ObjectCreateView(CreateView): template_name = 'dashboard/add.html' success_url = '/' form_class = ObjectCreateForm and this is how the view is called: <a href="{% url 'dashboard:add' request.resolver_match.kwargs.slug %}"> new </a> And the urls.py: path('<slug:slug>/object/new', views.ObjectCreateView.as_view(), name='add'), Is using slug the problem here ? -
Django shell keeps losing connection to DB
Django (or postgresql) keeps losing connection from manage.py shell. I've been trying to google but couldn't find an answer. Is there a change to Django2.0+ or postgresql10.0+ ? -
Django ModelForm - access custom field in form valid
I have added a custom field to a ModelForm as per the below, however I cannot access the field in my UpdateView. I have tried printing the object, but the field device_circuit_subnet isn't in there, also referencing it outside the object throws an error. is it possible to obtain the value for a custom field in a model form so I can use it before saving the object? Thanks forms.py class SiteServiceForm(forms.ModelForm): class Meta: model = DeviceCircuitSubnets fields = ['device','circuit','subnet','monitored','interface_name','get_bgp','wb_bgp','db_bgp','get_interface','wb_interface','db_interface','get_aws','wb_aws','db_aws'] def __init__(self, *args, **kwargs): self.is_add = kwargs.pop("is_add", False) site_id = kwargs.pop("site_id") super(SiteServiceForm, self).__init__(*args, **kwargs) self.fields['device'].required = False self.fields['circuit'].required = False self.fields['subnet'].required = False self.fields['device_circuit_subnet'] = DeviceCircuitSubnetField( queryset=DeviceCircuitSubnets.objects.filter(device__site_id=site_id).select_related( 'device', 'circuit', 'subnet' ), label='Device / Circuit / Subnet' ) self.helper = FormHelper(self) self.helper.form_id = 'site_service_form' self.helper.form_method = 'POST' self.helper.layout = Layout( Div( Div( Div(HTML('<i class="fa fa-bolt fa-fw"></i> Service'), css_class='card-header'), Div( Div( Div( Field('device_circuit_subnet', css_class='chosen'), css_class='col-lg-6' ), Div( ... views.py class AddSiteService(PermissionRequiredMixin, CreateView): form_class = SiteServiceForm template_name = "app_settings/tabs_form.html" permission_required = 'config.add_device_circuit_subnet' def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] return super(AddSiteService, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("config:site_services", args=(self.site_id)) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() kwargs['is_add'] = True kwargs['site_id'] = self.site_id return kwargs def form_valid(self, form): self.object = form.save(commit=False) print(vars(self.object)) dcs_id = … -
How can i store tournament standings
i have a model class class MobaTournament(Tournament): teams=models.ManyToMany(Team) if a tournament have 20 teams. I want to sort of rank 1st team, 2nd team, 3rd team... How do you suggest I do this? like; 1.XXX team 2.XXX team 3.XXX team -
Allow Redirect To Disallowed Urls
In Django I am writing a view that will redirect the user to a "file:///*" url using the redirect method, but i am getting the Disallowed Url error. I understand that Django does this on purpose(I assume for security reasons), but in my case the use is intentional and by design. So my question is, how can I allow certain disallowed url schema's in django? This server is an internal server with no access to the outside world, also only users with the mapped network drive will be able to benefit from this (otherwise the browser just wont find the folder). These being said, I don't really see a negative security implication of doing this. My redirect method is as follows: def get_job_folder(request,jobnumber): import os jobnumber = "23456" p = r"P:/Engineer/DWGS/00NEW_DWGS/" f = [name for name in os.listdir(p) if name.strip().startswith(jobnumber)] if f != []: ret = "file:///" + p + f[0] response = redirect(ret) return response else: return JsonResponse({'message':"error. job not found"})