Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using attribute values as choices in Django model
I want the user to be able to add values to an attribute 'county' in model CountyChoices. I then want those values to surface as choices in a form for address for the attribute 'county' in model Address. I couldn't think of another way to explain this and so I had a hard time finding this in the documentation. What would this be called in the Django docs so that I can look this up? A link would be even better - Thanks in advanced. -
Django - PUT request in RetrieveUpdateDestroyAPIView
I am trying to make a PUT request to and RetrieveUpdateDestroyAPIView to my Student model. Model class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) college = models.CharField(max_length=100) branch = models.CharField(max_length=10) section = models.CharField(max_length=10) optedCourses = models.ManyToManyField(Course, blank=True, related_name='students') registrations = models.ManyToManyField(Course, blank=True, related_name='studentRequests') Serializer class StudentSignupSerializer(ModelSerializer): user = UserSignupSerializer() class Meta: model = Student fields = '__all__' def create(self, validated_data): user = User.objects.create(**validated_data.pop('user'), is_student=True) validated_data.pop('optedCourses') validated_data.pop('registrations') return Student.objects.create(user=user, **validated_data) VIEW class DetailStudent(RetrieveUpdateDestroyAPIView): queryset = Student.objects.all() lookup_field = 'id' lookup_url_kwarg = 's_id' def get_serializer_class(self): if self.request.method == 'GET': return StudentSerializer else: return StudentSignupSerializer I am trying to add more elements to the ManyToManyFields (optedCourses, registrations) by making PUT requests, but I am getting an error. { "user": { "username": [ "A user with that username already exists." ] } } Shouldn't PUT request update the existing elements? How do I approach on solving this problem? -
How to know the url path from a view function of another url in django?
I have a set of URLs: /home/ /register/ /login/ /puzzle/<pk> All of the first 3 urls can make a request to the last url. Is it possible to know which urls are calling the /puzzle/<pk>, from the view function attached to it? -
Django queryset iterator() doesn't work as expected
I have tested queryset.iterator() based on Django document. Oracle and PostgreSQL use server-side cursors to stream results from the database without loading the entire result set into memory. With server-side cursors, the chunk_size parameter specifies the number of results to cache at the database driver level. Fetching bigger chunks diminishes the number of round trips between the database driver and the database, at the expense of memory. On PostgreSQL, server-side cursors will only be used when the DISABLE_SERVER_SIDE_CURSORS setting is False. print(settings.DATABASES['default']['ENGINE']) # postgresql class TestModel(Model): age = IntegerField(default=1) # Insert 10 rows for i in range(10): TestModel().save() settings.DEBUG = True l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler()) # From now, every queries emitted by Django will be printed. print(settings.DISABLE_SERVER_SIDE_CURSORS) # False for i in TestModel.objects.all().iterator(chunk_size=2): print(i.age) (0.001) DECLARE "_django_curs_4369655232_3" NO SCROLL CURSOR WITH HOLD FOR SELECT "testmodel"."age" FROM "testmodel"; args=() I expected the above code will hit database 5 times for every 2 rows because of chunk_size=2(and the total number of rows are 10). However, it seems to emit just one query(above printed query). Do I misunderstand on queryset.iterator()? -
Trying to web scrape with Python from Heroku gives 'Connection aborted' error
I have a Django API application that web scrapes a website with the pythonic library RoboBrowser, which allows for easy log in and scraping from the page you get redirected to. The code that scrapes sits in the views.py file and the data is showed in an API view, using the Django REST framework. My application worked on my local network, but when I put the project up on heroku and tried to view the API view with the JSON data I got this error. 'Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) This is the traceback: Environment: Request Method: GET Request URL: https://restschool.herokuapp.com/results/ Django Version: 2.1.4 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'webapp'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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') Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 377. httplib_response = conn.getresponse(buffering=True) During handling of the above exception (getresponse() got an unexpected keyword argument 'buffering'), another exception occurred: File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 600. chunked=chunked) File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 384. six.raise_from(e, None) File "<string>" in raise_from File "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 380. httplib_response = conn.getresponse() File "/app/.heroku/python/lib/python3.6/http/client.py" in getresponse 1331. response.begin() File "/app/.heroku/python/lib/python3.6/http/client.py" in begin 297. version, status, reason = self._read_status() File "/app/.heroku/python/lib/python3.6/http/client.py" in _read_status … -
Django returns Page Not Found for mapped URL
I'm trying to render a basic html/css page in Django and I can't get it to work. It's set up seemingly the same as my index page which does work correctly and the debug explanation from the 404 response seems to show that it's pointing to the right url. Any thoughts on why this isn't working? *I'm using django 2.1 so I'm using path instead of the old regex url mapping *The html file exists and is located in templates\base_app\our-story.html From views.py: def OurStory(request): return render(request, 'base_app/our-story.html') From urls.py: from base_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('our-story', views.OurStory, name='our-story') ] From settings.py: TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') INSTALLED_APPS = [ (standard django apps) 'base_app' ] From debug message: Request Method: GET Request URL: http://127.0.0.1:8000/our-story.html Using the URLconf defined in base_app.urls, Django tried these URL patterns, in this order: admin/ [name='index'] our-story [name='our-story'] The current path, our-story.html, didn't match any of these. -
SelectDateWidget choices
I would manually like to set the date choices in my form according to my DB data. Here is a code snippet of the code I am using DATA_YEARS = ('2017', '2018') DATA_MONTHS = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12') class DateForm(forms.Form): year = forms.DateField(widget=forms.SelectDateWidget(years=DATA_YEARS)) month = forms.DateField(widget=forms.SelectDateWidget(months=DATA_MONTHS)) However, I reckon SelectDateWidget does not expect to receive these arguments. If not, how can I implement this properly? -
Refactor Django FormView Context
I currently email myself submitted form information as an admin so I can contact a customer. I could not figure out how to simply pass all of the form variables to the Django Email Template. I instead had to define the individually. Is there a way to pass all of the context variables so I don't have define each and every one of them? form_class = CustomProjectBuildRequestForm success_url = reverse_lazy('home') success_message = "Form successfully submitted!" def form_valid(self, form): form.save() context = { 'first_name': form.cleaned_data.get('first_name'), 'last_name': form.cleaned_data.get('last_name'), 'email': form.cleaned_data.get('email'), 'phone': form.cleaned_data.get('phone_number'), 'zip_code': form.cleaned_data.get('zip_code'), 'project_title': form.cleaned_data.get('project_name'), 'project_description': form.cleaned_data.get('project_description'), 'contact_method': form.cleaned_data.get('preferred_contact_method'), } template = get_template('request-custom-project/email_template.html') content = template.render(context) send_mail( 'New Custom Project Request', html_message=content, message=content, from_email=context['email'], recipient_list=['test@gmail.com'], fail_silently=False, ) return super(PMPIndex, self).form_valid(form) -
How to save data of the updated table to another table in Django
I just started in Django, I'm developing a web-application that want to create a Purchase Order and Masterlist. I started using the generic views and now I can create and update a Purchase Order. It has a status field of Pending and Received. If I created a new Purchase Order the default status is Pending and If I updated it to Received it should also save the data to Masterlist table. The thing is, it doesn't work. By the way, the received item should stay in Purchase Order table for history. Since I'm using the generic views in Django.. I tried to put the masterlist table in the update view of the purchaseorder but It has error saying No masterlist found matching the query Here is my class for the UpdateView class PurchaseOrderUpdateView(LoginRequiredMixin, UpdateView): model = PurchaseOrder model = Masterlist fields = ['item_no', 'description', 'dimension', 'unit', 'quantity', 'cost', 'project_site', 'po_date', 'supplier', 'status'] def form_valid(self, form): form.instance.prepared_by = self.request.user return super().form_valid(form) What I expect is, when I update the status field of my Purchase Order to received, it should also saved the data of it to Masterlist. Or If the item in Purchase Order exists in Masterlist it will update the … -
How to create model objects that belong to unique user
I am setting up a delivery app .I want to be able to create a Reciever that belongs to the user logged in when created. class CustomUser(AbstractUser): first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(blank=False) class Reciever (models.Model): name = models.CharField(max_length=256,blank=False) I want to create a Reciever object that belongs to a particular user. When i create a Reciever now , it is available to all users. -
How do I stay on the same tab in a webpage after submitting a form using Django?
When I refresh the page/submit a form for my django app, it always goes to the first tab instead of redirecting to the tab the user was currently on. Is there any simple fix for this because I haven't found any answers online -
UnboundLocalError at / local variable 'Profile' referenced before assignment
i am writing a django views as shown:- def feed(request): if request.user.is_authenticated: user=request.user profile=Profile.objects.filter(user=user) userfollowing=FollowingProfiles.objects.filter(Profile=profile) for following in userfollowing: username=following.ProfileName useraccount=User.objects.filter(username=username) Profile=Profile.objects.filter(user=useraccount) Post=post.objects.filter(Profile=Profile) comment=comment.objects.filter(post=Post) final_post_queryset=final_post_queryset+Post final_comment_queryset=final_comment_queryset+comment return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset}) else: redirect('signup') while template feed.html is:- {% extends 'base.html' %} {% block content %} {% load static %} {% for p in final_post_queryset %} {{ p.DatePosted }} <img src="{{ p.Picture.url }}"/> {% endblock %} while the error is:- so the error is in the 3rd line of view profile=Profile.objects.filter(user=user) -
Method GoogleOAuth2 uses to login user
I have GoogleOAuth2 login in my application (social_core.backends.google.GoogleOAuth2). I want to write a custom class that inherits GoogleOAuth2 class. I want it to check Users.is_active is True or False and sent custom error message if Users.ia_active=False. What method does GoogleOAuth2 use to login a user? -
Django User with is_active=False login via GoogleOAuth2
I have a Django app with login via GoogleOAuth2. In general, GoogleOAuth2 works fine. When I try to login as a user with User.is_active=True, it's all OK. But when I try to login as a user with User.is_active=False, I got nothing. No error, just login page again. What can be an issue? How I should handle this error? -
How to store historical data using Django
I am new to Django and am trying to figure out how to store historical data and be able to reference any data point from a date in the past. Say I want to store data on a kids height change as he grows and be able to compare his height at day 400 to his height at day 6xx. How would I set this up in Django? Would there need to be a foreign key relationship between height and the kid? -
Migrated from Django 1.11 to 2.1.4, Options requests giving 403
I Migrated my python codebase from Django 1.11 to 2.1.4, while updating python from 2.7 to 3.7. After resolving many code-level issues, now everything is working fine. When I am testing to GET data from the postman, it works perfectly. However, when I try to get it using my frontend code, it first sends options requests, which is failing, giving 403. So, backed sends nothing. Do I need to change any default Django settings to make options requests work like before? -
I'm updating my pg_hba.conf, but the file gets reset to default everyday
I've made my django instance accessible on pg_hba.conf. But every morning when I go to get started, I have to re-apply the changes because the file has reset back to its original content. This is a CentOS7 Server running Apache with cpanel, the django instance is setup with gunicorn and nginx on a separate port from Apache's httpd. I've applied the changes to pg_hba.conf and issued the following commands but they do not fix the issue. sudo systemctl restart postgresql sudo service postgresql restart here is the code I placed into pg_hba file: local all all peer host all all 165.227.123.167/32 md5 host all all ::1/128 md5 #That code successfully allows access to database once applied to file and this command following: sudo systemctl restart postgresql I expected the change to be permanent, but it actually needs to be done daily. -
Social Token failed to get expires_at field when using https.
When tried to add Facebook Account, expire date of access token is empty. django-allauth==0.38.0 Django 2.0 Python 3.6 -
Display Count of Foreign key in Other table
i want to display number of Users in that company for all companies. I am using User in-built Model. UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) Company Model class Company(models.Model): company_name = models.CharField(max_length=20, unique=True) company_description = models.CharField(max_length=100) View to display Companies class CompanyListView(LoginRequiredMixin, generic.TemplateView): template_name = 'company/company.html' def get_context_data(self, **kwargs): context = super(CompanyListView, self).get_context_data(**kwargs) context['companies'] = Company.objects.all() # Count of Users return context Display Count of Users for each company in single template -
Django: Tree stored in DB, derive JSON
I have a model like so: class Node(models.Model): parent = models.ForeignKey(Node, null=True) Let us assume I have the following tree stored using this DB structure: Tree Structure What is the most efficient way to obtain a JSON in the following structure, in a query written in Django's ORM? {"node": "A", "children": [ {"node": "B2", "children": [ {"node": "C1", "children": []}, {"node": "C2", "children": []} ]}, {"node": "B1", "children": []} ]} -
Heroku error 500 when running django raw query
I'm executing a raw query in django and it works fine. But when I deployed it on heroku I'm getting an error. Maybe it's happeninig because on heroku is running postgree, and I did the query to run on sqlite. If I'm right, which changes must I do in my query to works well? cursor = connection.cursor() cursor.execute('''select l_article.id, l_article.lei_id, l_article.article, l_article.is_titulo, laws_marcacao.is_marcado, laws_marcacao.description, laws_marcacao.votos, accounts_user.id , laws_marcacao.description from l_article inner join accounts_user left join laws_marcacao ON laws_marcacao.article_id = l_article.id and laws_marcacao.user_id = accounts_user.id where l_article.law_id = %s and accounts_user.id = %s;''', [law.id, request.user.id]) data = cursor.fetchall() That's the error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "where" LINE 5: where l_article.law_id = 1 and acco... -
Dynamic Bootstrap Modal URL
I have a datatable with information, and I want to be able to select an item, and click a button to update that table. Functionality seems to work, however, the issue is passing formURL an url that changes based on what the user have selected. I tried to do some dirty work and assign an onclick function to the button and call the Modalform everytime, it kinda worked. Except, you had to click multiple times before it actually updated to the newly selected item. Just assume that the getID() function knows how to get ID from the currently selected item. <button class="uppdatera-produkt btn btn-primary" type="button" name="button">Uppdatera Produkt</button> <script> $(document).ready(function() { $(".create-produkt").modalForm({ formURL: "{% url 'create_produkt' %}" }); $(".update-produkt").modalForm({ formURL: "{% url 'update_produkt' 12345 %}".replace(/12345/, getID()) }); table = $('#storage').DataTable( { }); $('#storage tbody').on( 'click', 'tr', function () { if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); id = table.row('.selected').data()['id']; } } ); </script> -
How to get data from the query set returned from elasticsearch django
I am trying to get data from elastic search in my application but its returning a query set which triggers an error in my serializers "Expected a list of items but got type \"Search\".". And when I print results returned from elastic search i get <django_elasticsearch_dsl.search.Search object at 0x1101f2b00>. I haven't used elastic search before and its giving hell... document.py from django_elasticsearch_dsl import DocType, Index, fields from elasticsearch_dsl import analyzer from .models import Unit, Rental units = Index('units') html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @units.doc_type class UnitDocument(DocType): rental = fields.ObjectField(properties={ 'property_type': fields.TextField(), 'city': fields.TextField(), }) class Meta: model = Unit fields = [ 'bedroom', 'bathroom', 'price', ] related_models = [Rental] def get_queryset(self): """Not mandatory but to improve performance we can select related in one sql request""" return super(UnitDocument, self).get_queryset().select_related( 'rental' ) def get_instances_from_related(self, related_instance): """If related_models is set, define how to retrieve the unit instance(s) from the related model. The related_models option should be used with caution because it can lead in the index to the updating of a lot of items. """ if isinstance(related_instance, Rental): return related_instance.car_set.all() In my views.py i have tried to capture the anticipated data. views.py class SearchView(APIView): permission_classes = (AllowAny,) … -
Django Rest Framework different serializers for on model
I have Model, like: def SomeModel(models.Model): serial_num = models.IntegerField(unique=True) count = models.IntegerField() And have to create 2 url which will work with this model. But, there are have to be 2 different serializers. For example: For first url user’data have to has both fileds (serial_num and count) For second url users’data have to has only one field (count). In second case serial_num will be generated in Serializers class. Is this good practice to make 2 different serializers for one model? And also question, what about validation? Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls). -
ERROR: ERROR: Could not find a version that matches djangomysqlrestframework
I am trying to install djangomysqlrest framework in my django project which is created inside pipenv. i tried the following command: pipenv install djangorestframework pipenv install djangomysqlrestframework but in both cases it is giving following error: x Locking Failed! .... .... ERROR: ERROR: Could not find a version that matches djangomysqlrestframework