Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
make api without making model and view in Django
I am going to make an api in django which currently only return hello world when the url is hit. I am new to python and django and find a bit difficult to work in django because of working in PHP and its frameworks for a long time. I have followed the tutorials but that takes me making the models, templates. but my requirement is simple. How can i achieve this. That when i hit the url of DJango app it return me the hello world or any json object in future. -
Django channels process tasks based on a time tag?
I know I can send tasks to a consumer and the consumer processes tasks in a first-come-first-serve basis. But can I somehow schedule a task and have the consumer process it when it's due? Can I have a consumer listen to a redis list and whenever the list is not empty, process the item with lowest score? I know I can use celery, but I am developing on windows and prefer not to use celery. I am using channels already and would be nice to process my scheduled tasks with channels. -
Getting error in url from HTML template to urls. No reverse match
I am trying to delete a record the on basis of primary key, so I am trying to pass a PK to url into a view function but getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'delete_view' with arguments '('',)' not found. 1 pattern(s) tried: ['essay/(?P<essay_id>[0-9]+)/delEssay/$'] My html code: <form method="POST" action="{% url 'essay:delete_view' teacher.id %}"> <div class="page-header"> <div class="span4"> <h1>Manage Essays</h1> </div> </div> <table> <tr> <th>Title</th> <th>Edit</th> <th>Delete</th> </tr> {% csrf_token %} {% for uploadassignment in teacher.uploadassignment_set.all %} <tr> <th for="uploadassignment{{ forloop.counter }}">{{uploadassignment.title}}</th> <th><input type="submit" value="Edit" class="btn btn-primary"/></th> <th><input type="submit" value="Delete" name="delEssay" id="delEssay" class="btn btn-primary"/></th> </tr> {% endfor %} </table> </form> URL: url(r'^(?P<essay_id>[0-9]+)/delEssay/$', views.delete_view, name='delete_view') View Function: def delete_view(request,essay_id): print("Delete") print(essay_id) object = UploadAssignment.objects.get(id=essay_id) object.delete() return render(request, 'essay/THome.html') -
Django Form field not required, but required in model
I have a page in which u can supply a number (we'll call it the ID). When you supply the ID in the form, a new record in the database will be made with that ID. But when you don't supply an ID and you post the page, the ID will be set on the highest ID + 1 (custom function get_new_id()). I don't want to add the highest ID + 1 as initial value in the form, as I want people to be able to leave the field empty. It's unclear for me how i set the ID if it's not supplied by the user. When I call form.is_valid() it's valid since the field is not required in the form, but it is required in the model so when calling form.save() I get the error "Column 'ID' cannot be null". I tried setting the form.data['id'] value, but that's not mutable. Where do i set the value of the form field ID before it's saved? -
How to trigger a periodic calculation function based on local timezones?
I have a function that is to be triggered midnight everyday for daily report calculation of different facilities of a factory. I have written this with the help of Celery and crontab so that it does this. But the problem is that the facilites lie in different timezones. I have another function that finds the timezone of each facility from its coordinates. But how to modify my Celery task so that it is triggered at midnight at each facilities local time zone. I can't get my head around it. Any advice is appreciated :) -
Django: include get_absolute_url() in abstract model?
I'm working on a project that allows the user to fill in and save checklists needed in gastronomy. As the checklists' content differ from one another, I decided to create an abstract base class 'checklists' with shared fields and have child models for differing attributes. I want to find a way to dynamically create unique urls for each checklist through the abstract model. The only way I can make it work so far is to include a get_absolute_url() in each child model - but this way I have to manually define a url in my urlpatterns and different views for each child model. Feels like unnecessary repetition. I tried including the get_absolute_url() in my abstract model. However, this does not work because I can't seem to access the child's attributes in the abstract model. Is there a way to include get_absolute_url() in my abstract base class? I appreciate your help! Thanks a lot! This is part of the code: models.py class Checklisten(models.Model): # abstract model that contains shared features of all checklists erlaubte_pruefer = models.ForeignKey(Pruefer, on_delete=models.CASCADE, verbose_name='Prüfer') pruefende_firma = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Unternehmen') raum_verbindung = models.ManyToManyField(Raeume, verbose_name='Ort') datum = models.DateField('Datum', auto_now_add=True, blank=False) class Meta: ordering = ['datum', 'pruefende_firma', 'raum_verbindung', 'erlaubte_pruefer'] abstract … -
Django: How to display the profile pic of particular user who have written the question?
This is my profile model: class Profile(models.Model): Date = models.DateTimeField(auto_now_add=True) Full_Name = models.CharField(max_length=32,blank=True) Name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) E_mail = models.EmailField(max_length=70,blank=True) image = ImageField(upload_to='user_images', null=True, blank=True) This is my Question model: class Consultancy(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Date = models.DateTimeField(auto_now_add=True) Questions = models.TextField() I am creating a simple consultancy application...I want to display the profile picture of the users who have written the question.. What do I have to do in my template to make this possible.. Any idea anyone??? -
Python bytes to geojson Point
I have a MySQL database where I have Point type location data and a Django (Django Rest Framework) backend where I am trying to retrieve that data. If I try to get that location data from phpMyAdmin the returned location is something like this POINT(23.89826 90.267535). In my Django backend however, I get a bytes as the returned location. The returned value is something like this b'\x00\x00\x00\x00\x01\x01\x00\x00\x00\x12N\x0b^\xf4\xe57@C\xe2\x1eK\x1f\x91V@' The database uses utf8mb4_unicode_ci collation. If I try to convert the returned bytes to a string with .decode('utf-8') I get UnicodeDecodeError >>> s = b'\x00\x00\x00\x00\x01\x01\x00\x00\x00\x12N\x0b^\xf4\xe57@C\xe2\x1eK\x1f\x91V@' >>> s.decode('utf-8') Traceback (most recent call last): File "<console>", line 1, in <module> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf4 in position 13: invalid continuation byte I get the same bytes array even if I perform a raw query from Django with the MySQL function St_AsGeoJson(location). I then tried geojson. When I feed that bytes to geojson.Point() I get a geojson back but instead of 2 floats the coordinates array consists 25 integer values. >>> s = b'\x00\x00\x00\x00\x01\x01\x00\x00\x00\x12N\x0b^\xf4\xe57@C\xe2\x1eK\x1f\x91V@' >>> geojson.Point(s) {"coordinates": [0, 0, 0, 0, 1, 1, 0, 0, 0, 18, 78, 11, 94, 244, 229, 55, 64, 67, 226, 30, 75, 31, 145, 86, 64], "type": "Point"} … -
Custom error messages based on object status
As for example I've got a model with several statuses. class Task(models.Model): TO_DO = 'to_do' IN_PROGRESS = 'in_progress' DONE = 'done' TASK_STATUSES = ( (TO_DO, _('To do')), ... ) status = models.CharField(max_length=256, choices=TASK_STATUSES) creator = models.ForeignKey('user.User', on_delete=models.CASCADE) def is_to_do(self): return self.status == self.TO_DO def is_in_progress(self): return self.status == self.IN_PROGRESS def is_done(self): return self.status == self.DONE And I've got endpoint where I want to perform an action on my task. Before this I want to check if this action is allowed to perform based on object status and other stuff. I may have several if statements like: obj = get_object() if object.is_in_progress() and object.creator.name = '...': raise NotAcceptable(detail=_('...')) if ... ... else: obj.update_status() Each exception may have it's own error message. I can store this messages on model but I still have a lot of if which only raise exception. So what is best way to perform such checks and keep my api views clean? -
Django DRF Foreign Key
This question or many like it has been asked multiple times but for some reason I am unable to find the answer. I do have this working to an extent in the way that if you go on the api pages, it renders, creates and updates without problem. The issue is displaying a field (title) from the nested object instead of just the primary key on the front end. Some background before getting into the code: Races is a finite list (e.g. Race1, Race2, Race3) and the front end does not have the ability to add more. Cards is not finite, but each card must link to an existing Race (this currently does so by Primary Key). The front end should display the card_text and race title of the linked race. It also has the ability to add a new card but this works fine. I have had this working with separate serializers for read and create/update where the read has a 'depth: 1' to pull through the entire object but the create/update doesn't and you then parse the object and send the primary key back (I couldn't find a way of doing this in the serializer, is it possible?). … -
Sending server side messages with Django channels
My Django application needs to send messages to a logged in users in a round robin fashion. Upon receiving the message, the user should have a fixed time to respond before the message is sent to the next user. My current consumer class is as below, class MessageConsumer(WebsocketConsumer): def connect(self): self.accept() global_list.add(self) def disconnect(self, close_code): global_list.remove(self) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) I have a HTTP end point which on receiving a POST request with a token, loops through the global_list and calls self.send(text_data='Notification Sent') which is not working. What is the right way of doing this? -
Django filter more than one time mapping with ManyToMany
Suppose I have something like this in my models.py: class A(models.Model): name = CharField(max_length=20) class B(models.Model): a = models.ManyToManyField(A) I want to get A which has more than one time mapped with B. -
Django - images not displayed
I work on a Django project and I want to display some images to templates, but although I can upload them, I can not display them. class Sindiasmoi(models.Model): sindid = models.AutoField(db_column='sindID', primary_key=True, db_index=True) # Field name made lowercase. descr = models.CharField(max_length=100) shortdescr = models.CharField(db_column='shortDescr', max_length=50) # Field name made lowercase. photo = models.ImageField(db_column='photo',upload_to='sindiasmoi',default='elections.jpg',null=True, blank=True) eidos = models.IntegerField(default=1) def __str__(self): return self.descr class Meta: managed = True db_table = 'SINDIASMOI' My view is: def pososta_telika(request, eklid): # φιλτράρισμα επιλεγμένης εκλ. αναμέτρησης selected_ekloges = Eklogestbl.objects.get(eklid=eklid) # επιλογή όλων των εκλ. αναμετρήσεων με visible=1 και κάνω φθίνουσα ταξινόμηση αν δεν δοθεί παράμετρος all_ekloges = Eklogestbl.objects.filter(visible=1).order_by('-eklid') #ανάκτηση εγγραφών επιλεγμένης εκλ. αναμέτρησης από το σχετικό database view all_pososta = EklSumpsifodeltiasindVw.objects.filter(eklid=eklid).order_by('-posostosindiasmou') context = {'all_pososta':all_pososta, 'all_ekloges':all_ekloges, 'selected_ekloges':selected_ekloges.eklid} return render(request, 'Elections/pososta_telika.html',context) My template code has code below: {% for p in all_pososta %} <img src="{{ p.sindid.photo}}" alt="image"/> {% endfor %} Als I added row below in my settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And finally my urls.py has code below: urlpatterns = [ path('admin/', admin.site.urls), path(r'', include('Elections.urls')), path('admin_tools/', include('admin_tools.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', … -
django leaflet maps display images
i want to use leaflet image overlay plugin for display a image and i follow this reference and i create a simple html file and work perfect. html code : <!DOCTYPE html> <html> <head> <title>Image Overlay Example</title> <link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/> <script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> </head> <body> <div id = "map" style = "width:900px; height:580px"></div> <script> // Creating map options var mapOptions = { center: [17.342761, 78.552432], zoom: 8 } var map = new L.map('map', mapOptions); // Creating a map object // Creating a Layer object var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); map.addLayer(layer); // Adding layer to the map // Creating Image overlay var imageUrl = 'my/path/out.jpg'; var imageBounds = [[17.342761,552432], [17.542761,78.752432]]; var overlay = L.imageOverlay(imageUrl, imageBounds); overlay.addTo(map); </script> </body> </html> but if i use that html code in django to return a simple that static html page then image don't display in the map . any idea why happen that ?because is the some code thanks django view : def map_details(request,pk): app_de=MyModel.objects.all() apps=get_object_or_404(app_descripts, slug_name=slug,id=pk) return render(request, 'map.html',{'app_des':app_de,'apps':apps}) -
Using Pandas with imported excel file from Django and creating output file for user to download.
I am interested in creating an app through Django to do the following workflow. Would be interested to know if there are any packages/framework that makes this whole process less complicated. 1.) Allow user to upload an excel file. 2.) Reads the file and stores it into a pandas dataframe. 3.) Connect to an existing database (I use mssql 2016) and store certain data into Pandas dataframes. 4.) Manipulate stored dataframes to create a final dataframe. 5.) Create an excel file using the final dataframe for user to download I am mainly interested in frameworks that makes step 2,3,5 easier. Thanks -
How to verify outgoing HTTP request from python's module?
I need to write Python equivalent code for below mentioned working curl(I have replaced the credentials for obvious reason, but it gives back 200 status.). curl -X POST \ 'https://api.lever.co/v1/candidates?dedupe=true&perform_as=user_123' \ -H 'Authorization: Basic token_123' \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: multipart/form-data' \ -H 'Postman-Token: 58cafa90-7ae4-47db-a144-4e9d430ffc94' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -F 'files[]=@/Users/gaurav/lever_resume.pdf' \ -F 'emails[]=a@b.com' So, I ended up in writing this snippet. user_email = 'user@domain.com' admin_id = '20f3975a-543f-4ca8-b215-2f851232a0ad' client_id = '893728937298' client_secret = '32032' file_path = '/Users/ttn/Desktop/a.txt' file_name = 'a.txt' logging.basicConfig(level=logging.DEBUG) url = "https://api.lever.co/v1/candidates" files = { 'files[]': (file_name, open(file_path,'rb')), } auth = HTTPBasicAuth(client_id, client_secret) querystring = { "perform_as": admin_id, "dedupe": 'true' } payload = { 'emails[]': user_email } headers = { 'Content-Type': "multipart/form-data", "Cache-Control": "no-cache", "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" } response = requests.post(url, headers=headers, params=querystring, data=payload, auth=auth, files=files) req = response.request # print(curlify.to_curl(req)) print('\n==== Headers', req.headers) print('\n==== Body', req.body) print('\n==== form-data', str(req)) print(response.text) Question Since Python version of Curl is not working(giving 502 error instead of 200), so How can I compare the two? Can I generate the Curl out of Python's request`? Can someone spot mistake in my Python version? I am suspecting some problem at form-data being passed (to collect evidence, I need answer … -
Force in-browser viewing of Word and Powerpoint files in Django
We're currently developing a webapp (django) where an end-user can upload DOC, DOCx, PPT, PPTx, and PDFs. We're trying to figure out a way so that an end-user can just click a link for that uploaded document file and be able to view its contents within the browser. PDF opens inside the browser so that's all good. However, we don't quite know where to start to make it so people can open DOC/x and PPT/x files inside their browsers. We're open to the idea of the files being sent to a Google Drive and being converted to a Google Doc or Google Slide file and then opened; We're also open to the idea of converting said files to the necessary file-type on upload, instead. Maybe something like convert DOC to ODT then open using view.js? What do you think? -
Django - How to reload uwsgi in Ubuntu 16.04
I have a project running in Ubuntu 16.04 and want to reload everytime I have changes in my Django project. When I was still using ubuntu 14.04, I can just use the following commands. to reload: sudo reload projectname to restart sudo restart projectname now when I try to restart in Ubuntu 16.04 sudo systemctl restart uwsgi When I try to reload using this command sudo systemctl reload uwsgi This is the error message Failed to reload uwsgi.service: Job type reload is not applicable for unit uwsgi.service. Screenshot of the error message. -
Django migration error in change model ('Duplicate key name')
I have a field of a model in Django that I have changed and added unique = True, because I want everything now entered in that field to be different. The problem is, if I have in the database equal values in that field that are saved from the past, I miss an error in the migration. My question is whether there is any way to make a condition for that in the migration or the model, and if there are values of the same field in the database before, that ignore or save the first and put the others to NULL. Thanks in advance for the help. -
Django UserChangeForm custom validation
ValueError: The Custom_User could not be changed because the data didn't validate. Hi guys, so I am trying to make a UserChangeForm to allow customers to edit their address, contact or password. However, for the field "postal code" I have set a restriction where there are only certain postal addresses I want to service. #forms.py #Extract list of postal codes which are valid and put into a list valid_postal_code = [] postal_code_model = PostalCode.objects.all() for code in postal_code_model: valid_postal_code.append(code.postal_code) #form class EditAccountForm(UserChangeForm): class Meta: model = Custom_User fields = ( 'address', 'postal_code', 'unit_number', 'email', 'contact_number', 'password' ) def clean_postal_code(self): post_code = self.cleaned_data.get('postal_code') if post_code not in valid_postal_code: print('hello') raise forms.ValidationError('Sorry we do not serve this postal code right now D:') return post_code If the user inputs a postal code that is not in the valid_postal_code list, I would like that the form be able to raise an Error message on the form. However, I get the above error(which is to be expected), straight away without the raising for error. #views.py def edit_info_page(request): if request.method == 'POST': form = EditAccountForm(request.POST, instance=request.user) if form.is_valid: form.save() print('form changed') return redirect('home:edit_info_page') else: form = EditAccountForm(instance=request.user) return render(request, 'sign/edit_info.html', {'form':form}) #models class Custom_User(AbstractUser): postal_code = … -
How to get templates showing on Heroku. Site deploys but none of templates are showing up, including context_processors
I've been working on trying to figure out why the templates aren't being rendered and the context_processors don't seem to work either. I've deployed other static simple sites but this one has many apps and for some reason although Heroku deploys, none of the templates are showing up. Looked everywhere but none of the solutions work.I looked up Heroku Django static files but doesn't work. The site's not even giving me any error about templates, it's just not loading it. Here's the link to my server. Link to Heroku site Settings.py import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'shop.context_processors.menu_links', 'cart.context_processors.counter', STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') django_heroku.settings(locals()) Above is what it should be. Below is what comes out on Heroku server. I've tried various methods of making changes to Template Directory, moving the html templates files around to different directories, installing White noise and adding it to Middleware. None of it works and I can't seem to figure it out. I've got other simple … -
Unable to print the variable passed from view to template
I am trying to pass the variable ,I am obtaining from view to the template but it is showing in the preview of the web-browser(chrome) but not on actual screen. Following is my view file: analyzer=SentimentIntensityAnalyzer() data={} with open('today_5th_oct_new.csv','r',newline='', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: data[row[0]]=float(row[1]) analyzer.lexicon.update(data) def index(request): return render(request, "gui/index.html") @csrf_exempt def output(request): sentences = request.POST.get('name',None) senti = analyzer.polarity_scores(sentences) context_dict = {'sentiment': senti} return render(request,"gui/index.html", context = context_dict) Following is my template- <!doctype html> <html> <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <form action> Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br> <input onclick = "testfunction()" type = "button" value = "Submit" > </form> <div><strong>Score is {{ sentiment }}</strong></div> </body> <script> var testfunction = () => { var test = document.getElementById("name").value console.log(test) $.ajax({ type: "POST", dataType: "json", url: 'output/', data:{ csrfmiddlewaretoken: '{{ csrf_token }}', 'name': test }, success: function(response) { console.log("Succesful return firm ajax call"); }, error: function(result){ console.log("Failure"); } }); } </script> I am observing the desired output in preview but not on actual page. How to resolve that ? -
adding multiple data into a model using serializer
the below code is the object in which the dummy data is stored and to be added into the database. obj = [ { "activity_name": 'test-for-33', "created_by": 1142, "activity_start": "2018-10-10 07:56:11+00 ", "activity_end": "2018-10-10 07:56:11+00 " }, { "activity_name": "test-for-55", "created_by": "1142", "activity_start": "2018-10-10 07:56:11+00 ", "activity_end": "2018-10-10 07:56:11+00 " } ] views.py @api_view(['POST', 'GET']) @parser_classes((JSONParser,)) def insert_data_activity(request): # Check if seats is a list # if isinstance(request.data['seat'], list): # seats = request.data.pop('seat') if obj is not None: models = [] for i in obj: # validate each model with one seat at a time print(i['activity_name']) request.data['i.activity_name'] = i['activity_name'] serializer = ActivitySerializer(data=request.data) serializer.activity_name = i['activity_name'] print("msmssmmmmmmmmmmmmmmm", serializer.activity_name) serializer.is_valid(raise_exception=True) serializer.save() print("saved") models.append(serializer) # Save it only after all seats are valid. # To avoid situations when one seat has wrong id # And you already save previous saved_models = [model.save() for model in models] result_serializer = ActivitySerializer(saved_models, many=True) # Return list of tickets return Response(result_serializer.data) # Save ticket as usual serializer = ActivitySerializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) here the model is getting updated with the object but it is taking null as an input and storing it into the database as shown below. { "id": 39, "activity_name": null, "acttivity_start": null, "activity_end": null, … -
Django ForeignKey data grouping
Django ForeignKey need to grouping from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) I want to list of all reporter with their all article. How It possible? -
Jupyter notebook with Django and Python 3
I want to launch Jupyter notebook with Django so I can e.g. access Django database within Jupyter notebook. I've read this post: How to setup Jupyter/IPython notebook for Django? but seems like its solutions assume working with Python 2. So when I run it I get an error "Could not find a kernel matching Python 2". So, what are the steps to bind Jupyter notebook to Django application and Python3?