Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How granular should Django apps be?
Per the answer to a similar question, should a new app be made for every model unless they are closely related (i.e. logically one unit)? What are the benefits of doing so? Say you have the following models class Address(models.Model): street = models.CharField(max_length=100) city = models.CharField(max_length=100) state = models.CharField(max_length=100) class Employee(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.PROTECT) company = models.ForeignKey(Address, on_delete=models.CASCADE) class Company(models.Model): name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.PROTECT) Should each model be put into its own app? Should Address be in one app with Company and Employee in another? Are they all closely related enough to belong to the same app? What is the recommended granularity for apps in a good Django project? -
Django postgress - dynamic SearchQuery object creation
I have a app that lets the user search a database of +/- 100,000 documents for keywords / sentences. I am using Django 1.11 and the Postgres FullTextSearch features described in the documentation However, I am running into the following problem and I was wondering if someone knows a solution: I want to create a SearchQuery object for each word in the supplied queryset like so: query typed in by the user in the input field: ['term1' , 'term2', 'term3'] query = SearchQuery('term1') | SearchQuery('term2') | SearchQuery('term3') vector = SearchVector('text') Document.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank').annotate(similarity=TrigramSimilarity(vector, query).filter(simularity__gt=0.3).order_by('-simularity') The problem is that I used 3 terms for my query in the example, but I want that number to be dynamic. A user could also supply 1, or 10 terms, but I do not know how to add the relevant code to the query assignment. I briefly thought about having the program write something like this to an empty document: for query in terms: file.write(' | (SearchQuery( %s )' % query )) But having a python program writing python code seems like a very convoluted solution. Does anyone know a better way to achieve this? -
Override clean_<fieldname>() in django so that it does not return an error when an existing entry is entered
I have a django form which takes a charfield: panel_name = forms.CharField(required=True, label='Panel Name') I want this form to be able to take existing panel_names as well as add new ones. However when I add a panel that is already in my Panel table, calling: if form.is_valid(): raises an error which renders to this next to the HTML input field: <span id="error_1_id_panel_name" class="help-inline"><strong>Panel with this Panel name already exists.</strong> How can I override this using "cleaned_panel_name"? I have tried it doing the following, but it still happens: def clean_panel_name(self): panel_name = self.cleaned_data['panel_name'] try: Panel.objects.get(panel_name=panel_name) print("INFO: Panel exists.") return panel_name except ObjectDoesNotExist: pass return panel_name thanks -
update model instance which has m2m fields also
I want to update my model instance using .update(**kwargs) for non-realted fields and .clear() followed by .add() for related fields. My problem is that only one of them is getting executed at a time. When I do the following its working and updating the m2m fields: def preview(request): worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id)) worksheet_object.question.clear() worksheet_object.question.add(*question_pk_list) #other m2m fields But I want to update the non-related fields also and its not working when I do the following: def preview(request): worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id)).update( classroom=worksheet_data['classroom'], category=worksheet_data['category'], #other fields) worksheet_object.question.clear() worksheet_object.question.add(*question_pk_list) #other m2m fields I am using this answer and this answer to do the same in my view. Can anyone help figure out what I am doing wrong? and how it can be corrected? -
How to set oninput event on a field in DjangoAdmin?
Because Django html is generated in the back, I don't have much control over how each field is generated. Because of this, I'm trying to set the element's oninput in a <script> tag but it's not working. Does anyone know how to get the following to work? <input type="number" name="area_hct" value="0.70" step="0.01" required id="id_area_hct" /> <input type="text" id="country" value="Norway" readonly><br> <script> function octest() { var hct = document.getElementById("id_area_hct") var country = document.getElementById("country") country.value = hct.value } var hct = document.getElementById("id_area_hct") hct.oninput = octest() </script> -
Select ROI on a Webpage using Django and OpenCV
Recently, I am trying to create a webapp using Django where my workflow is something like this: User opens up a page [localhost:8000/some_name] My Django app which is running on Raspberry Pi clicks the image. The image which is snapped is shown on the page The user should be able to select the ROI field of the image Once selected I should get the following x1, y1, x2, y2 . I am able to do it using OpenCV as a standalone script but unable to add the same to my page in Django app. Hope I am clear with the statement. Here's my views.py code which I have tried : from django.shortcuts import render import cv2 import numpy as np from picamera import PiCamera from time import sleep def get_roi_option(request): camera = PiCamera() camera.start_preview() sleep(5) camera.capture('picture_initial.jpg') camera.stop_preview() # Read image im = cv2.imread("<path_to_pic>") # Select ROI r = cv2.selectROI(im) # Crop image imCrop = im[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])] print(int(r[1])) print(int(r[1] + r[3])) print(int(r[0])) print(int(r[0] + r[2])) dict_of_values = {'r1': int(r[1]), 'r2': int(r[1] + r[3]), 'r3': int(r[0]), 'r4': int(r[0] + r[2])} context = {'ctx': dict_of_values} # Display cropped image cv2.imshow("Image", imCrop) cv2.waitKey(0) return render(request, context, 'base.html') -
Django Error While Creating Pages
I encountered this issue while creating a page in tango_with_django_project. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/rango/category//add_page/ Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order: admin/ ^rango/ ^$ [name='index'] ^rango/ about/$ [name='about'] ^rango/ ^add_category/$ [name='add_category'] ^rango/ ^category/(?P<category_name_url>\w+)/$ [name='category'] ^rango/ ^category/(?P<category_name_url>\w+)$/add_page/$ [name='add_page'] ^media\/(?P<path>.*)$ The current path, rango/category//add_page/, didn't match any of these. Please have a look at my files. The following is my views.py. def add_page(request, category_name_url): context = RequestContext(request) category_name = decode_url(category_name_url) if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): page = form.save(commit=False) try: cat = Category.objects.get(name=category_name) page.category = cat except Category.DoesNotExist: return render_to_response('rango/add_category.html', {}, context) page.views = 0 page.save() return category(request, category_name_url) else: print (form.errors) else: form = PageForm() return render_to_response( 'rango/add_page.html', {'category_name_url': category_name_url, 'category_name': category_name, 'form': form}, context) This is my urls.py from django.conf.urls import url from rango import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'about/$', views.about, name='about'), url(r'^add_category/$', views.add_category, name='add_category'), url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'), url(r'^category/(?P<category_name_url>\w+)$/add_page/$', views.add_page, name='add_page'), ] This is my add_page.html <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <h1>Add a Page to {{category.name}}</h1><br/> <form id="pageI encountered this issue while creating a page in tango_with_django_project. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/rango/category//add_page/ Using the … -
Like/Unlike Button with jQuery in a Django App
I'm trying to create a Like/Unlike button with jQuery! Here's what I did, Here's the HTML, <span class="like-button">{% if request.user in content.likes.all %}Unlike{% else %}Like{% endif %}</span> Here's the jQuery, $('.like-button').click(function(){ var x = $(this); x.toggleClass('like-but'); if(x.hasClass('like-but')){ x.text('Like'); } else { x.text('Unlike'); } }); This code seems working fine but the problem is when i like some content (it shows Unlike, fine) & then refresh the page (still shows Unlike, fine), But when I press Unlike after refreshing page it doesn't work. It takes 2 clicks not 1 to change from Unlike to Like. -
how to use model's serializer fields content?
I have a serializer like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') and a function like this: def check (self , request): if unique('username' , 'email'): return True return False how could I pass 'username' and 'email' content through the function? -
Difference between child model types in Django
I am building a control panel that will have multiple sub-applications in Django. One of my models is an application, which will have important settings like name, description, install_path and id (so that I can associate specific settings and configuration values to this application. Right now I'm struggling in trying to figure out how to declare this particular model. Each application will do something completely different than each other application. One might manage specific CMS settings and another may handle password resets for our development environment. The goal is to get the commonly used things in one place. My question is, what is the difference between declaring my applications using abstract base class models vs. proxy models. The main information for each application will be the same. Each will have a name, description, etc. The difference will be what they do and what settings they use. The settings are in their own model though, with a link back to the application via foreign key. -
import error rest_framework_httpsignature.authentication django rest frame work?
i am importing from rest_framework_httpsignature.authentication import SignatureAuthentication in django 1.8v and python 2.7.6 ,it causeing importing error only to this class SignatureAuthentication in vs studio , please help but i can able to import this class rest_framework.authentication -
Lightweight alternative to geodjango for MVP (minimal viable product)
For a django-based webapp MVP I need a global city/country database. It has two requirements. It should be as simple as possible to get up and running. Ideally without much installation, but maybe as initial data in fixtures, which can be pushed to collaborators. The user generated location information (eg their home city), should later on be transferable to a more involved geodatabase like geodjango. Do you know a good option? Thank you! -
Creating answer related questions
this is my third post about the tool I am writing and until now you have helped me so much. I am writing a QuizTool which has to handle Polls, Multiple Choice Questions and Branched Questions. So far I am able to list my surveys, loop through questions and post the related answers to save them in my model. Also i am able to create multiselect fields for the Multiple Choice Questions. But its realy hard to figure out how the Branched Questions work for me. Let me explain how I approach to this problem. Here is the relevant part of my model: class Answer(models.Model): answer_id = models.AutoField(blank=False, null=False, primary_key=True) answer_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Antwort')) # Internal fields date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am')) date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am')) def __str__(self): return self.answer_text class Meta: # db_table = 'data' verbose_name = _(u'Antwort') verbose_name_plural = _(u'Antworten') ordering = ['answer_id'] class Question(models.Model): question_id = models.AutoField(blank=False, null=False, primary_key=True) # Fields answer = models.ManyToManyField('Answer', through='Question_Answer', related_name='+') question_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Frage')) # Internal fields date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am')) date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am')) #Typunterscheidung der Fragen QUESTION_TYPES = ( ('0', … -
Centralized Authentication in Django 2.0
I need some help with building something (That I call) Centralized Authentication Server in Django 2.0, which will support the following: Say There are 2 services: Service A - which is the frontend application. It's a simple Django project the has only one view that serves a VueJS application. Service B - which is the API. Service A is sending AJAX requests to Service B. The 2 services are totally separate, and ideally I would like to not handle any User model in none of the services. What I would like is to use Service C, which is a service that handles all the Authentication and the User model. When a user goes to Service A and he is not logged in, he will be redirected to Service C and login to the system using his credentials (User/Password) and then will be redirected back to Service A, alongside with a token that will enable him to speak with service B. Then service B will get this token, and authenticate it against service C. (In each request, or only in the first request / dedicated 'login' request). I read a lot about django-mama-cas + django-cas-ng, and tried to implement it. But … -
Anonymise email data with django allauth
I am migrating an old database to django allauth using the email address as the username. However, the database has a load of old users that have used the same email address to register for separate accounts, so the migration is failing. I'd quite like to anonymise the duplicate accounts (and it's something I think is worth being able to do anyway, with GDPR in mind) but I'm not sure how to go about it. The only thing I can think of is to set their email address to something (unique) that my system can then check for and not send emails to. But that feels really hacky to me. Is there a better way? -
Heroku django program deployed,but returned a 400 error
The thing is,I wrote a very simple django blog.And I put it on Github.Then I tried to deploy it on Heroku.When I finished it,I only saw 400 Bad Request.I'm confused.The log is here: 2018-03-13T11:56:51.929117+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=guoguoblog.herokuapp.com request_id=85b467df-9cd5-4bae-8cd8-e33a9c89d1a9 fwd="112.9.115.29" dyno=web.1 connect=1ms service=20ms status=400 bytes=154 protocol=https 2018-03-13T11:56:51.928540+00:00 app[web.1]: [13/Mar/2018 19:56:51] "GET /favicon.ico HTTP/1.1" 400 26 And repeat again when I flush my page. What can I do? Oh,this is my github project.https://github.com/qwedc001/DjangoBlog Can anybody help me? Eric -
building big xml file with python 2
im trying to get the best performance to build a big XML file in python 2/django. the XML file produced have ~500mb and the 1st approach used was with lxml. took over 3H30. then i tested with xml.sax and took over the same time, 3h30. im trying to find the fastest way and with less memory consumption. i searched over several days and the best ways i found were these two, but then i found that lxml have xml.sax implementation aswell. any ideas to help? thanks! -
What is the best way to manage permissions for user and multiple admin for object instances for a web application
I am looking for best way for my web application. It has many admin and users. the workflow is like there is super admin who create account for company admin (this can be many or one). the company admin can have many end user's who access departments of that company. the company admin set or remove permission for end user like user1 can access dept but not dept2. So what would be the best structure/design to build this system. (I am going to use django for this) -
Bootstrap modal dialog dismiss not working but submit button
I have a problem which I seam to find no answer to. I have modal which contains a form for submitting data to the server. The submitting part is working just fine. All data gets send and the server takes the correct steps. However, the buttons to close/dismiss the modal do not work. The form gets pulled by ajax request from the server and is embedded in the current page <!-- Dialog for user input of forms--> <div id="form-modal" class="modal fade" role="dialog"> </div> Ajax pulled form <div class="modal-dialog" role="document"> <!-- Content of dialog --> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Datensatz erstellen</h4> <button type="button" class="close" data-dismiss="modal">&times </button> </div> <div class="modal-body"> <form action="{% url 'knowledgeedit' %}" method="POST" id=""> {% csrf_token %} {% for field in form %} <div id="{{ field.auto_id }}_container"> {{ field.help_text }} <div> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> </form> <div class="modal-footer"> <button class="btn btn-success" type="submit" name="{{ requestedForm }}">Speichern</button> <button class="btn btn-default" type="button" data-dismiss="modal">Abbrechen</button> </div> </div> </div> </div> css: body { font-family: 'Open Sans', serif; padding-top: 54px; color: #868e96; } .btn-primary{ background-color: #bd5d38 !important; border-color: #868e96 !important; } /* Sections */ @media (min-width:992px) { body { padding-top: 0; padding-left: 17rem; } }h1, h2,h3,h4, h5, h6 … -
Filtered records in django template
I am building a races app, where in a webpage I want to display records from the db, grouped based on the year a race took place and on the type of the race, so as to calculate some stats. Which is the best way to pass these groups of records in the template and build the methods for the calculation of the stats? a) Passing a dictionary through views? b) Applying a custom filter? c) Applying a simple tag? d) Building a custom Manager? e) Building the stats methods in models.py, and if so, how can I apply the group filters? f) any other way? Please, provide a working example if possible. -
How to iterate ElasticSearch data in Python/Django?
I have ElasticSearch iterated data like this: (Pdb) data[0] {'_index': 'publishserdata-index', '_type': 'publishser_data_index', '_id': '35', '_score': 1.0, '_source': {'publisher': 'Admin', 'department': 'IT', 'subdepartment': 'Full Stack Developer', 'inventory_ID': 'IT003', 'title': 'Why Should I Use Celery?', }} I want get publisher,department,title data. I tried data[0]._source try to user dict data[0].__dict__ but it's showing error. -
saving form - many to many relationship
I am trying to save form based data in many to many relationship. My models is as follow: class Student(models.Model): stuName = models.CharField(max_length=100) stuCity = models.CharField(max_length=100) stuPhone = models.IntegerField(max_length=10) stuNationality = models.CharField(max_length=50) stuCreatedt = models.DateTimeField(default=timezone.now) def __str__(self): return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course(models.Model): courseId = models.AutoField(primary_key=True) courseName = models.CharField(max_length=100) enrolledStu = models.IntegerField(max_length=3) students = models.ManyToManyField(Student) dept = models.ForeignKey(Dept, on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept) which i am trying to save. my view is def addStudent(request): if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): print(form.cleaned_data) course = form.save(commit=False) course.courseName = request.courseName course.save() form.save_m2m() return redirect('lstDetail') i tried without form.save_m2m() method but still its giving error. AttributeError at /stuApp/new/ 'WSGIRequest' object has no attribute 'courseName' Request Method: POST Request URL: http://127.0.0.1:8000/stuApp/new/ Django Version: 1.11.10 Exception Type: AttributeError Exception Value: WSGIRequest' object has no attribute 'courseName Exception Location: C:\Users\PycharmProjects\learning\stuApp\views.py in addStudent, line 22 Python Executable: C:\Users\PycharmProjects\learning\venv\Scripts\python.exe Python Version: 3.6.4 this is from html page. on console there isn't any error its just prints the query. basically i am unable to save data with many to many fields and relationship. my … -
Django save previous object from models
In a Django admin site, I have this class. I want to save a previous version of a object (Servers) which is a manytomany field to find changes on the object. With normal CharField this work, but for manytomany fields I got this error: "<SourceDestinationGroup: asdas>" needs to have a value for field "id" before this many-to-many relationship can be used. here is my objectclass class SourceDestinationGroup(models.Model): STATE_CHOICES = ( ('C', 'in Change'), ('F', 'Finished') ) ServerGroupName = models.CharField(max_length=256) Description = models.CharField(max_length=256,blank=True) Servers = models.ManyToManyField(Server) Status = models.CharField(max_length=1, choices=STATE_CHOICES, default='C') def __init__(self, *args, **kw): super(SourceDestinationGroup, self).__init__(*args, **kw) self._old_Servers = self.Servers def save(self, **kw): if self.Servers != self._old_Servers: self.Status = 'C' self._old_Servers = self.Servers super(SourceDestinationGroup, self).save(**kw) def __str__(self): return self.ServerGroupName -
Django forms validation is not showing up in the template
My problem is, when I validate forms for errors, some text with warning would show up, But id does not. I was searching for 2 days for some good answers and i tried also everything, so I thing that is some really silly mistake. Can anyone help me with this problem? I was trying to implement validation in my register subpage so.... First image is my model.py for registration Second image is my inputForms.py with simple validation Third image is my view.py And fourth is my template.html for registration Someone please help me with this mistake. Thank you very much. -
how to dispatch a specific method with csrf_exempt in django class based view
Hello i am trying to set csrf_exempt on class based view in django i've tried this one now my class is look like this: class UserView(View): # Check csrf here def get(self, request, pk): #code here # I want to exempt csrf checking only on this method def post(self, request): #code here Meanwhile if I use @method_decorator(csrf_exempt, name='dispatch') it will applied to every methods in the class. What's the best approach to exempt only for specific method in a class based view in Django?