Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the use of the classes 'wide' and 'extrapretty' within a fieldset?
Within a fieldset i've added the classes wide and extrapretty like so: @admin.register(PeerReviewProject) class PeerReviewProjectAdmin(admin.ModelAdmin): date_hierarchy = 'creation_date' list_display = ('name', 'creation_date', 'open', 'random', 'deadline') inlines = [PeerReviewGroupInline] fieldsets = ( ('Project eigenschappen', { 'classes': ('extrapretty', 'wide',), 'fields': ('name', 'open', 'random', 'deadline'), }), ) But i can't see how this makes any display look different. The admin page looks the same with or without those 2 classes. So what is their use exactly? -
How to catch complete url in Django view which includes?
I've got a simple Django application in which I want to catch the complete url and get some information from it. The url will be of the following form: ourdomain.com/2/abc:AB$12345$AB12345678_01.xyz/abc/1000,1000/1/a.xyz So in my urls.py I catch the url like this: path("<path:the_url>", views.index, name='the_endpoint'), In my unit tests it all works flawlessly. I then tested it manually by doing a call and printing out the url I get in the view: def index(request, the_url): print(the_url) return HttpResponse("Some response", status=200) But then I get this printed in the terminal: 2/abc:AB2345.xyz/abc/1000,1000/1/a.xyz instead of the expected: 2/abc:AB$12345$AB12345678_01.xyz/abc/1000,1000/1/a.xyz I removed the dollar signs from the request url, and then I get the url I expect. So the dollar signs are the source of trouble. I'm unsure how I can fix this though. Does anybody know how I can get the full url when it includes dollar signs? -
Apply regular expresion django model lookup stored in a dictionary as an unicode
I have a regular expresion django model lookup stored in a dictionary as an unicode: print(mydict) {u'mycharfield__regex': u"r'^.{13}[S]'"} and I want to apply my regular expression as a Django model queryset filter like this: queryset.filter(mydict["regex"]) The idea is to get the same result as doing this: queryset.filter(mycharfield__regex: r'^.{13}[S]') But the problem is that I have it stored as a string, and then it doesn't work. How could I "cast" my regular expression? -
How to let user select a city and redirect him to the related page?
I want to make an application on Django, where a user, by going to the main page of the site, could choose his city (from specified class City). Then he is redirected to the page mysite.tld/city, where he can view the services associated with the selected city. It is not clear how to load a city using Ajax and redirect the user to the page of the selected city. What is the way to implement this? -
How to access Many-to-Many relationship from different related models?
I have the following models: class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) instrument = models.ManyToManyField('Instrument', through='InstrumentMap') class InstrumentMap(models.Model): instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), related_name='instrumentmap', null=True, blank=True, on_delete=models.PROTECT) instrument = models.ForeignKey(Instrument, verbose_name=_('instrument'), related_name='instrumentmap', null=True, blank=True, on_delete=models.PROTECT) numbers = models.IntegerField(null=True, blank=True) class Work_Music(MPTTModel, Work): instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), related_name='work', null=True, blank=True, on_delete=models.PROTECT) How do I get access to all the instruments under an instrumentation object from work? For example: piece = Work_Music.objects.get(pk=self.kwargs['pk']) I tried piece.instrumentation_set.all. That didn't work? How do you get access from instrumentation? instrumentation = Instrumentation.objects.get(instrumentation__work=self.kwargs['pk']) I guess you do a for loop when you can grab the object. How do you get access from instrumentmap? InstrumentMap = InstrumentMap.objects.filter(instrumentation__work=self.kwargs['pk']).order_by('order') -
Django - serialize model objects with dependencies
In serializing a queryset of TestChild model objects, I'd like the json to include dependent TestParent objects. Here's my code: from django.db import models class TestParentManager(models.Manager): def get_by_natural_key(self, field1, field2): return self.get(field1=field1, field2=field2) class TestParent(models.Model): field1 = models.CharField(max_length=20, blank=True, default='') field2 = models.CharField(max_length=20, blank=True, default='') field3 = models.CharField(max_length=20, blank=True, default='') objects = TestParentManager() def natural_key(self): return (self.field1, self.field2) class Meta: unique_together = [['field1', 'field2']] class TestChildManager(models.Manager): def get_by_natural_key(self, field1, field2): return self.get(field1=field1, field2=field2) class TestChild(models.Model): parent = models.ForeignKey(TestParent, on_delete=models.CASCADE) field1 = models.CharField(max_length=20, blank=True, default='') field2 = models.CharField(max_length=20, blank=True, default='') field3 = models.CharField(max_length=20, blank=True, default='') objects = TestChildManager() def natural_key(self): return (self.field1, self.field2) natural_key.dependencies = ['environ_tool.testparent'] class Meta: unique_together = [['field1', 'field2']] When I run serializers.serialize( 'json', eModels.TestChild.objects.all(), use_natural_foreign_keys=True, use_natural_primary_keys=True, ) the resulting json is like so (no TestParent objects): [{u'fields': {u'field1': u'f1', u'field2': u'f2', u'field3': u'f3', u'parent': [u'foo2', u'']}, u'model': u'environ_tool.testchild'}] but I would like to see the TestParent object that the TestChild object depends on in the json too, like so: [{u'fields': {u'field1': u'foo2', u'field2': u'', u'field3': u''}, u'model': u'environ_tool.testparent'}, {u'fields': {u'field1': u'f1', u'field2': u'f2', u'field3': u'f3', u'parent': [u'foo2', u'']}, u'model': u'environ_tool.testchild'}] The django docs lead me to believe this is supposed to happen in serialization but no luck. … -
How do you extend a Django third party model?
I'm using Python 3.7, Django 2.0 and the django-address==0.2.1 module (https://pypi.org/project/django-address/). The address module seems to auto-create migrations and import models for my app, which is nice. I would like to create a def get_by_natural_key(self, name): return self.get_or_create(...fields...)[0] method for the AddressField model (for the purposes of making creation of YAML data easier). Is it possible to add this into the AddressField model without altering the core files that download as part of installing this app? The MySQL table created for that model is + | address_address | CREATE TABLE `address_address` ( `id` int(11) NOT NULL AUTO_INCREMENT, `street_number` varchar(20) COLLATE utf8_bin NOT NULL, `route` varchar(100) COLLATE utf8_bin NOT NULL, `raw` varchar(200) COLLATE utf8_bin NOT NULL, `formatted` varchar(200) COLLATE utf8_bin NOT NULL, `latitude` double DEFAULT NULL, `longitude` double DEFAULT NULL, `locality_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `address_address_locality_id_5dd79609_fk_address_locality_id` (`locality_id`), CONSTRAINT `address_address_locality_id_5dd79609_fk_address_locality_id` FOREIGN KEY (`locality_id`) REFERENCES `address_locality` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin | +-----------------+------------------------------------- although not sure how relevant this table structure is to my question. -
Application hosting in GitHub
Please! I want to host my code in Github,I have registered already but I do not know how to import the 'blog' application which I created,following the instruction on the 'djangogirls tutorial' am a bit lost on the instruction using the command prompt. -
How can I post multiple data of same fields to django rest framework from react?
I am trying to post code,course and date fields from react to django,but not able to understand how.I am storing the branch and semester in states.Code course and date fields are stored in an array. A basic idea of how to implement this would help me a lot.Thank you Screenshot of implementation -
Django, tailwindCSS : How to customize input type : "date"
I make a date-picker with input type 'date' but I wish to make it beautiful. How can I make it possible? ... widgets = { ... "start_date": forms.DateInput(attrs={"type": "date", "style": "width:100%"}), "end_date": forms.DateInput(attrs={"style": "width:100%"}), } -
How to fix django-admin ModuleNotFoundError on fresh install
I am trying to run Django for the first time. I named my first project djangotest. It's python 3.6 ./manage.py runserver works fine, but anything using django-admin (e.g. django-admin check) is returning a ModuleNotFoundError: No module named 'djangotest' error. How do I fix this ? I have no idea what you might need from my config files so don't hesitate to ask me. NB : I already had a look on the internet. Tried to edit my virtual environment syspath, but it won't stay permanently changed (I don't know why) >>> import sys >>> sys.path.append('/home/myusername/PythonProjects/djangotest') Anyway, This is a fresh django install. I should not be messing with anything else than configuration files, should I ? -
In django admin autocomplete exclude parent or children if instance exists
class Name(MPTTModel): parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children", verbose_name=_("Parent Name"), ) name = models.CharField(max_length=24, unique=True) class MPTTMeta: order_insertion_by = ["name"] class NameAdmin(MPTTModelAdmin): search_fields = ["name"] autocomplete_fields = ["parent"] def get_search_results( self, request, queryset, search_term, ): queryset, use_distinct = super().get_search_results( request, queryset, search_term, ) # Can I try to acquire an obj_id here in order to do something like: if obj_id: queryset = queryset.exclude( id__in=Name.objects.get(id=obj_id).get_family() ) return queryset, use_distinct In the autocomplete box of parent, if I select self, a parent or a child instance and hit save, I get an InvalidMove error. If an object already exists, can I exclude get_family() from the autocomplete queryset? -
Data manipulation in Django json response
I want to iterate over device object and add a comparison. The json looks like below. I want to compare let's say if status is 1 to add new field for each device "status" : "available" else "status" : "Occuppied". How can i manipulate json response? View: from django.core import serializers def ApplicationDetail(request, application_id, cat): device = Device.objects.all().filter(category=cat) data = serializers.serialize('json', device) return HttpResponse(data, content_type='application/json') JSON: [ { "model":"applications.device", "pk":"70b3d5d720040338", "fields":{ "icon_name":"amr.jpg", "application_id":13, "status":1 } }, { "model":"applications.device", "pk":"70b3d5d72004034c", "fields":{ "icon_name":"amr.jpg", "application_id":13, "status":0 } } ] -
Django ModelForm initial or custom field value
I have a simple model and even simpler model form, but I just can't figure it out how to set initial, or custom value to my form field. I tried with form.cleaned_data['fieldname'] = value, initial={'field':value}, form.fields['field'].initial = value, even indexing it like this form.cleaned_data['status'] = Locked.STATUS[0][0] but I couldn't make it work. For the record, I want to use choice field from my model. The field name is 'STATUS', and I want to set first value('odlozen') to be used as a form field value, in my views.py. So form.cleaned_data needs to be STATUS value of 'odlozen', when this function triggers. PS. Don't mind me for not declaring my whole code, since it not necessary for this question. Thanks! Lets start with my code : models.py class Locked(models.Model): STATUS = ( ('odlozen', 'Odložen'), #this is the value ('u_procesu', 'U procesu'), ('ne_javlja_se', 'Ne javlja se'), ('zakazan', 'Zakazan'), ('odustao', 'Odustao'), ('default', 'Izaberite status.'), ) ... status = models.CharField(max_length=50, choices=STATUS, blank=True) #I set blank=True for no reason, it can be False also. ... class Meta: verbose_name = 'Locked' verbose_name_plural = 'Locked' get_latest_by = 'locked_name' def __str__(self): return smart_str(self.locked_eluid) This is my forms.py : class OppDetaljiForm(forms.ModelForm): class Meta: model = Locked fields = [... ,'status', … -
How to show a non_field_errors ValidationError raised in model.clean() in inline admin
Using Django 2.2 I added a custom clean() method to a model. class MyModel(Model): employees = models.ManyToManyField(Employee) def clean(self): raise ValidationError({'non_field_errors': _("Error message here.")}) super().clean() I am showing this model in the Django admin using an InlineModelAdmin, TabularInline to be precise, code looks like this: class MyModelInline(BaseModelTabularInline): model = MyModel.employees.through And in EmployeeAdmin: @admin.register(Employee) class EmployeeAdmin(BaseModelAdmin): inlines = (MyModelInline) I've hidden some code, don't know if my employer would like me to share it. But when I now try to save an instance of MyModel using the InlineModelAdmin, I get an error 'MyModelForm' has no field named 'non_field_errors'. Can anyone tell me how to have this field available, so that I can display potential validation errors (coming from MyModel.clean()) PS. I notice that raising ValidationErrors for other fields (that are on my model) works perfecly, example: raise ValidationError({'confidential_level': _("Error message.")}) -
Django on Kubernetes Deployment: Best practices for DB Migrations
My Django deployment has x number of pods (3 currently)running a Django backend REST API server. We're still in the development/staging phase. I wanted to ask for advice regarding DB migration. Right now the pods simply start by launching the webserver, assuming the database is migrated and ready. This assumption can be wrong of course. Can I simply put python manage.py migrate before running the server? What happens if 2 or 3 pods are started at the same time and all run migrations at the same time? would there be any potential damage or problem from that? Is there a best practice pattern to follow here to ensure that all pods start the server with a healthy migrated database? -
Unable to import Excel to database
I have a system whereby it allows to import the student attendance file into the system. However, it did not import it successfully. I tried to debug and i found out that when it goes to the importer.py function, it only run the first code and did not go to the other part. importer.py class AttendanceImporter(CsvImporter): field_names=["username", "mark"] #it does not go to the method. def _handle_row(self,row): print("this") if (not self._is_row_valid(row)): return self._FAILED username=row["username"] if (self._is_username_exist(username)): if (self._is_mark_exist(username)): if (self._do_update(row)): return self._UPDATED else: return self._FAILED else: if (self._do_save(row)): return self._CREATED else: return self._FAILED else: return self._FAILED def _is_row_valid(self, row): for item in self.field_names: if (len(row[item])==0): return False return True def _is_username_exist(self, username): return len(User.objects.filter(username=username))>0 print(username) def _is_mark_exist(self, username): user = User.objects.get(username=username) return len(Attendance.objects.filter(user=user))>0 print(username) def _do_save(self, row): # create attendace mark try: attendance=Attendance() user=User.objects.get(username=row["username"]) attendance=Attendance.objects.create(user=user, mark=row["mark"]) print("save?") attendance.save() except: return False return True def _do_update(self, row): # update attendance mark try: user=User.objects.get(username=row["username"]) attendance=Attendance.objects.get(user=user) attendance.mark = row["mark"] attendance.save() except Exception as e: print(e) return False return True Views.py @transaction.atomic @csrf_exempt def data_import(request, file_type): # TODO: currently only support importing users, later can support importing groups fields_required = None if(file_type == "user"): fields_required = "username, password, email, matric_number, fullname, groups" elif (file_type … -
Pre-loader loads behind block content and navbar
I have a preloader which is loading in front of the <body> but not in front of the site <navbar> or the {% block content %}. #preloader{z-index:999;} HTML: <header> <div class="flex-center" id="preloader"> <div class="preloader-wrapper active"> <div class="spinner-grow text-warning" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> </header> JS: $(window).on('load', function() { $('#preloader').addClass('loaded'); setTimeout(function(){ $('#preloader').addClass("notta"); }, 2000); }); CSS: #preloader:before { content: ''; z-index: 999; display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,1); } #preloader.loaded { opacity: 0; transition: .3s ease-in 1s; } #preloader.notta { display: none; } If I put the preloader at the bottom of the <body> it will load on top of the {% block content %} but underneath the navbar. I assume this means it has to do with the order of loading? How do I get it to show up above everything on the site? -
django-enumeields Removing default field makes migration fail with ValueError: '' is not a valid Regions
I'm trying to make a dropdown form to use as a region filter on a project. I got some advice pointing me in the direction of django-enumfields. At first, I set a default value for this but I later realized that I need it to not have a default value, due to how I have to design the POST functionality. I'm using python 3.8.1 and django 3.0.2 This is the relevant code from models.py: from django.db import models from enumfields import EnumField, Enum class Regions(Enum): LATAM = 'LATAM' EU = 'EU' NA = 'NA' SEA = 'SEA' JP = 'JP' KR = 'KR' ANZ = 'ANZ' SK = 'SK' NOT_DEF = 'NOT_DEF' class Labels: LATAM = 'LATAM' EU = 'EU' NA = 'NA' SEA = 'SEA' JP = 'JP' KR = 'KR' SK = 'SK' ANZ = 'ANZ' NOT_DEF = 'NOT_DEF' class Team(models.Model): ... team_region = EnumField(Regions, blank = True, default = Regions.NOT_DEF) ... So the only thing I want to change is removing the default value from the Team object: class Team(models.Model): ... team_region = EnumField(Regions, blank = True) ... Now, when I try to migrate, I get: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, stats … -
Django Model Design for Nested Json Output
I would like to design models in order to get json output as below. I've been trying different alternatives, using foreignkey or manytomany fields but couldn't get it worked. This is what I want to get. Every user may have different trainings and each training for the subject user may have more than one date. { "userid": "12345", "username": "John", "trainings": { "trn1": [ "20-01-2018" ], "trn2": [ "20-01-2018", "20-01-2019" ], "trn3": [ "20-01-2018", "20-01-2019", "15-04-2019" ] }, "notes": "a note about the user" } -
Django: How will django protect from knowing the passwords by using hashes if someone have access to the database
I found Django uses the format <algorithm>$<iterations>$<salt>$<hash> to store the hashed password Assuming some one has the access to database. From the above format one knows the salt, algorithm and iterations. So will it be difficult to find the password from either brute force attack or rainbow tables -
Django request.POST.get() is empty for field values set by javascript
I have a html form where user provides length, width and height and there is onkeyup event linked to a javascript function which in return provides volume in a disabled textbox. Now, the values are shown in the textbox and they do change dynamically but when I am submitting the form and accessing it in the views using POST method, I am only getting values for input fields which are filled by user and the disabled textbox returns None. I have to store that volume in session and pass it to next view on requested but since the request.POST.get() is None, I am not able to retrieve it. Note: I am just using volume calculation as an example to explain the issue. # html <head> <script> calcVolume(){ var Length = Number(document.getElementsByName('length')[0].value); var Width = Number(document.getElementsByName('width')[0].value); var Height = Number(document.getElementsByName('height')[0].value); if (Length != '' && Width != '' && Height != '') { var Volume = Length * Width * Height document.getElementsByName('volume')[0].value = Volume; } } <script> </head> <form method="POST" action=""> {csrf_token} <table> <tr> <td><input name="length" onkeyup="calcVolume();"></td> <td><input name="width" onkeyup="calcVolume();"></td> <td><input name="height" onkeyup="calcVolume();"></td> <td><input name="volume" value="0" disabled></td> <td><button type="submit">Next</button></td> </tr> </table> </form> # views.py def vol(request): if method.request == "POST": request.session['l'] … -
Problem with displaying coordinates in leaflet map in Django from mysql database
I have a mysql database which contains coordinates, I want to view these coordinates in a Leaflet map. Below here I have two views. vessel_details_location sent the coordinates to my template and the one under that some other details. I realize that this is totally incorrect but I am still learning. The idea is that I want to use data from one model (VesselTable) and data from another (LocationTable) in the same template. But the information from location table I need to send as geosjon and has to be filtered. def vessel_details_location(request): location = serialize('geojson', LocationTable.objects.filter(mmsi=mmsi).values()) return HttpResponse(location, content_type='json') def vessel_detail(request, mmsi): vessel = get_object_or_404(VesselTable, mmsi=mmsi) periods_vessel = PeriodTable.objects.filter(mmsi=mmsi).values() context = { 'vessel': vessel, 'periods_vessel': periods_vessel, } return render(request, 'vessels/vessel_detail.html', context) These are my current urls: urlpatterns = [ path('', views.index, name='index'), path('<int:mmsi>/', views.vessel_detail, name='detail'), path('locations/', views.vessel_details_location, name='detail_loc'), ] And this is my template: <!DOCTYPE html> <html lang="en"> {% load static %} {% load leaflet_tags %} <head> <meta charset="UTF-8"> <title>Title</title> {% leaflet_js %} {% leaflet_css %} <style type="text/css"> #gis {width: 80%;height:600px;} </style> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}"> </script> </head> <body> <h3>Vessel details</h3> {% if vessel %} <p>{{ vessel.name }}</p> {% if periods_vessel %} <ul> {% for period in periods_vessel … -
Django Segmentation fault when changing database to mysql in settings.py
My question is similar to the one at error connecting mysql to django which has gone unanswered. I am using python 3.6.5, mysql server-5.7.29 and Ubuntu 18.04 LTS. I am trying to setup mysql for my django application but I am receiving Segmentation fault. (env) monu@monu:~/Desktop/ShubhamProject/ShubhamProject$ python manage.py runserver Segmentation fault (core dumped) If I use the default sqlite3 database, server comes up. Database section in settings.py looks like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sports_website', 'USER': 'nonroot', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } Using the following packages asgiref==3.2.3 Django==3.0.3 django-crispy-forms==1.8.1 mysqlclient==1.4.6 pytz==2019.3 sqlparse==0.3.0 -
TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not function
I have seen other people in here with this issue but I couldn't seem to get any of the solutions to their problems to work for me. I am developing a todoapp in python, and I have reached a point at which, whenever I run the "manage.py runserver" command in CMD(yeah I'm using cmd. I'm pretty cool like that) I get the following error: TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not function To my understand, the issue is most likey in my settings.py-file, which looks like this: import os import mimetypes mimetypes.add_type("text/css", ".css", True) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&1b&@3slc&-p8hs^wqru#l%(b$3mc+uuk2t+uvr2vys+_dv$^e' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todolist', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.storage.CompressedManifestStaticFilesStorage', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'todoapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, …