Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework w/ no models - can't route to detail view
Following this tutorial, I'm trying to add a url to which one could make a POST request without a model: router.register(r'send_message', SendMessageViewSet, base_name='send_message') I don't need a GET, but I added one for debugging purposes: class SendMessageViewSet(ViewSet): def get(self, request, *args, **kwargs): return Response(HTTP_200_OK) def create(self, request, *args, **kwargs): ... Yet I'm able to get the "list" (url with no pk) but not the specific resource. Thanks! -
Django not a valid value for a primary key error in ModelMultipleChoiceField
I created a form consisting of two ModelMultipleChoiceFields of all the countries in the world. But after a POST request, Django doesn't deem the form valid with the error: "Algeria" is not a valid value for a primary key (or whichever country I select). Here is my form: class ComparisonForm(forms.Form): country_1 = forms.ModelMultipleChoiceField( queryset=WorldBorder.objects.values_list('name',flat=True) ) country_2 = forms.ModelMultipleChoiceField( queryset=WorldBorder.objects.values_list('name',flat=True) ) The list of countries is drawn from the db, which works fine. And my views: def lookup(request): if request.method == "POST": form = ComparisonForm(request.POST) if form.is_valid(): results = form.save(commit=False) country_1 = WorldBorder.objects.get(name=results.country_1) country_2 = WorldBorder.objects.get(name=results.country_2) country_1_name = country_1.name country_2_name = country_2.name multiplier = round(country_2.area / country_1.area, 1) return render( request, 'results.html', { 'country_1': dummy, 'country_1': country_1_name, 'country_2': country_2_name, 'multiplier': multiplier, } ) else: return render(request, 'error.html', {'form': form}) else: form = ComparisonForm() return render( request, 'lookup.html', {'form': form} ) And finally the html belonging to the form: {% extends "base.html" %} {% block content %} <h2>Compare the size of two countries here:</h2> <form id="comparison" action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" name="compare" value="Go compare!"> </form> {% endblock %} I am quite new to Django and somewhat at a loss as to how to solve this. From where … -
Django. Two queries in once. Is it right?
For example i will do something like this: class ProductInsertAndDeleteView(CreateView, DeleteView): # Create template_name = 'project/room_reserve.html' form_class = ReserveRoomCreateViewForm success_url = reverse_lazy('main:products') # Delete model = Product success_url = reverse_lazy('product:products') In short I have 2 requests. 1. Insert information to database 2. Delete information from database How to handle 2 requests? What to do in that situations? Is there any solution for that moments? Please explain what to do -
Post data to Djnago rest API via emberJS in desired format
I have EmberJS using Django REST API, I have few checkboxes which I am using to filter the data based on selection of checkbox. <label>Certificate</label> <div> <div> <div class="form-group-checkbox"> {{input type="checkbox" checked=certA id="certificate_A"}} <label for="certificate_A">A</label> </div> <div class="form-group-checkbox"> {{input type="checkbox" checked=certB id="certificate_B"}} <label for="certificate_B">B</label> </div> <div class="form-group-checkbox"> {{input type="checkbox" checked=certC id="certificate_C"}} <label for="certificate_C">C</label> </div> </div> </div> Currently I am getting below in querystring while calling the API: .../Search?certificate_A=true&certificate_B=true But the API needs string array for this parameter and it expects the parameter as mentioned below: ../Search?certification=certificate_A&certification=certificate_B How can I modify the emberJS code to generate the API request in above shown format? -
Method GET not allowed when PATCH Null Value in Django Rest Framework
I have a problem with PATCH Null Value in Django Rest Framework with Extend User Model. Please take a look my issues! Serializers:, Profile is extend User Model class UserEditSerializer(ModelSerializer): job_title = serializers.CharField(source='profile.job_title') class Meta: model = User fields = [ 'username', 'job_title', ] def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() if (validated_data.get('profile') is not None): profile_data = validated_data.pop('profile') profile = instance.profile profile.job_title = profile_data.get('job_title', profile.job_title) My viewsets: class UserUpdateAPIView(ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserEditSerializer permission_classes = (IsAuthenticated,) @detail_route(methods=['PATCH']) def edit(self, request): user_obj = User.objects.get(id=request.user.id) serializer = UserEditSerializer(user_obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return JsonResponse({'message': 'Error'}, status=500) My api patch request to server: { "job_title": "" } Error: { "detail": "Method \"GET\" not allowed." } Error Photo -
Bitnami instance downgrade from python 3 to python 2
Setting up a site on Google Cloud on a one install bitnami instance. The path for the python it's using is /opt/bitnami/apps/django/lib/python3.6/site-packages/ which is python 3.6 and when i check the default python with python --version it's 2.7.13 which I used when developing the site. I want to downgrade the version on the lib to 2.7 and depending on the error I get aftwerwards even lower the Django version to 1.8 or 1.9 since it's now using 2.0 I've just pointed the Apache conf files to my existing project and got an 500 internal error (from apache not django) and when I checked the error logs for Apache got the block of text below [Sat Jan 20 08:12:00.392061 2018] [ssl:warn] [pid 16792] AH01909: localhost:443:0 server certificate does NOT include an ID which matches the server name [Sat Jan 20 08:12:00.441919 2018] [ssl:warn] [pid 16793] AH01909: localhost:443:0 server certificate does NOT include an ID which matches the server name [Sat Jan 20 08:12:00.470337 2018] [mpm_prefork:notice] [pid 16793] AH00163: Apache/2.4.29 (Unix) OpenSSL/1.0.2n mod_wsgi/4.5.20 Python/3.6 configured -- resuming normal operations [Sat Jan 20 08:12:00.470390 2018] [core:notice] [pid 16793] AH00094: Command line: '/opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf' [Sat Jan 20 08:12:07.113691 2018] [wsgi:error] [pid 16803] /opt/bitnami/python/lib/python3.6/site-packages/pkg_resources/__init__.py:1298: … -
Django template shows only last file, instead of all uploaded
I want that for every lecture, the user to be able to upload multiple files, so I created a model that has FileField. So in my template, I want that for every lecture, the files uploaded to a particular lecture, to be shown in template. The Issue is that only the last uploaded file will show. <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.files %} <li><a href='{{ MEDIA_URL }}{{ c.files.files.url }}'>download</a></li> {% endif %} {% endfor %} </ul> {% endfor %} </ul> </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), ), default=0) lecture_title = models.CharField(max_length=100) content = models.TextField() files = models.ForeignKey('FileUpload', on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return str(self.lecture_category) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) def __str__(self): return str(self.files) def file_link(self): if self.files: return "<a href='%s'>download</a>" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' If I change to … -
How to add already built in delete permissions in Django programatically?
I have been trying to make an app which has 2 types of users : student and teacher. I have added custom permissions in both the models and they worked fine. Now I am not sure how to give the already built in delete permission to teacher so that she can delete a student? I havent been able to find anything regarding the same. -
Django {% load compress staticfiles %} image is not loading in heroku production path but works in local url
This is my heroku link : https://healthchecks-app.herokuapp.com/ I am not getting specific image.png files as it is loaded using Static compress file. Here is my Settings.py file: """ Django settings for hc project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os import warnings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HOST = "localhost" SECRET_KEY = "---" DEBUG = True ALLOWED_HOSTS = [] DEFAULT_FROM_EMAIL = 'healthchecks@example.org' USE_PAYMENTS = False REGISTRATION_OPEN = True TEMPLATE_DEBUG = False INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'compressor', 'hc.accounts', 'hc.api', 'hc.front', 'hc.payments' ) 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', 'hc.accounts.middleware.TeamAccessMiddleware', ) AUTHENTICATION_BACKENDS = ( 'hc.accounts.backends.EmailBackend', 'hc.accounts.backends.ProfileBackend' ) ROOT_URLCONF = 'hc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', 'hc.payments.context_processors.payments' ], }, }, ] WSGI_APPLICATION = 'hc.wsgi.application' TEST_RUNNER = 'hc.api.tests.CustomRunner' # Default database engine is SQLite. So one can just check out code, # install requirements.txt and do manage.py runserver and it works DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': './hc.sqlite', } } # You can switch database engine to postgres … -
Creating models and serializers for ManytoMany and foriegn key fields - django
I am new to Django and trying to create REST API for following problem : A user will add skills to his profile and other users can upvote the skill on other's profile . After learning from past 1 month I am able to create JWT session authentication for adding Skills (HTTP GET and POST). Next I am confused on how to make my serializers and views for operations like adding Skills to user profile and getting upvotes on it . I have following Model and View ready and tested : #import from django models module from django.db import models # This class will more or less map to a table in the database and defines skills at the application level class Skill (models.Model): # this defines a required name that cannot be more than 100 characters. skill_name = models.CharField(max_length=100,unique=True) class Meta: app_label = "wantedly_webapp" # This class will more or less map to a table in the database and defines the many to many relationship between user-skill, this is our intermediate model class UserSkill(models.Model): """ A Model for representing skill in user profile """ unique_together = (('user', 'skill_item'),) user = models.ForeignKey('UserProfile',on_delete=models.CASCADE,related_name='all_user_skills') skill_item = models.ForeignKey( Skill, on_delete=models.CASCADE ) def __str__(self): … -
Do I add the files in my migrations folder to my live Django server?
I'm going to push my offline Django project to Bitbucket, and then push that repo to my live Django server. My question is, do I exclude the contents in my migrations folders? And then perform makemigrations and migrate on my live server (Ubuntu/DigitalOcean) after the repo has been pushed to there? -
Django filter based on custom function
I have a table AvailableDates with a column date that stores date information. I want to filter the date after performing some operation on it which is defined by convert_date_to_type function. def convert_date_to_type(date): #perform some operation on date #return value will be a type, which will be any one item from types list below return type list of types: types = [] types.append('type1') types.append('type2') types.append('type3') Now I want to filter the table based on type. I will do this in for loop: for i in range(0,len(types)): #filter table here based on types[i], something like this AvailableDates.objects.filter(convert_date_to_type(date)=types[i]) How can I achieve this? Any other approach is much appreciated. -
How to use StringAgg aggregation functions in PostgreSQL 9.6 using DjangoORM
I am trying to join a field over a group. I could handle it in MySQL as described in one of my previous questions. However I migrated to PostgreSQL now and the proposed solutions does not work in PostgreSQL 9.6. According to Django docs, it is possible to use StringAgg as described here or here. I believe, in newer versions of PostgreSQL I cannot execute the line: from django.db.models.sql.aggregates import Aggregate as SQLAggregate Which throws the error: from django.db.models.sql.aggregates import Aggregate as SQLAggregate ModuleNotFoundError: No module named 'django.db.models.sql.aggregates' How can I create my own Aggregate Function using StringAgg? -
django best practice for navbar across multiple pages
What is the best practice way of implementing multipage navbars in webpages using Django. To be more specific (since this is the technology I am using) a Bootstrap navbar. Many tutorials motivate Django template inheritance by demonstrating an example of a page that inherits from a base page that contains the navbar. To my mind this doesn't sound optimal since the navbar would be re-downloaded and re-rendered in the browser with every request, while the server will have to re-serve it. On the other hand most Bootstrap tutorials assumes all the content in all the tabs of the navbar are in one webpage. So my question is, is there a standard Django or Bootstrap functionality that allows one to implement this scenario in a more optimal way? -
Installing MySqlDB on Python 3.6
I am unable to resolve this issue for a day now. when i try to execute my django project, pycharm throws the error "No module named 'MySQLdb'". From reference to similar questions on SO. I did try to install packages through file settings, that raises another error "Could not find a version that satisfies the requirement MySQLdb (from versions: ) No matching distribution found for MySQLdb" My project requires python 3.6 and the project doesn't seem to be working without MysqlDB. I did try to install mysqlAlchemy and mysqlconnector but it is of no use. Can some one point out how to resolve this ? I am on mac and there is no issue if i try to run the project from terminal. EDIT : I did try to install mysql from the pycharm package manager. But it throws another error No module named 'ConfigParser' -
sqlite database table is locked on tests
I am trying to migrate an application from django 1.11.1 to django 2.0.1 Tests are set up to run with sqlite in memory database. But every test is failing, because sqlite3.OperationalError: database table is locked for every table. How can I find out why is it locked? Icreasing timeout setting does not help. -
Connect Django with Oracle12C
I have successfully connected to the TESTDB using python program and JDBC and using the same credentials. Now, i want to connect to Django but getting error saying that "ORA-01017: Invalid Username/password; logon denied. python manage.py runserver error s django project settings.py oracle12c variables listener.ora file tnsnames.ora file connected using python -
How to create a pre-commit hook that will track errors from my Django code before I push to my server
I've only recently found out what a pre-commit hook is, and from what I understand it's a file (.git/hooks/pre-commit) that tracks my code for errors before the changes are committed to my server (DigitalOcean). So I want to make this file but I don't know what code to add to it. I've tried to find example files of pre-commit for Django projects but cannot find any. Advice appreciated. -
Update chart.js after form submission and page reload
I have a chart.js bar chart that pulls data via an ajax call to a Django APIView. The ajax call returns one dictionary with a stack of data inside I use to customize the chart. Here's the chart.js code: var current_year = '{% url "saveskore:api-current-year-savings" %}' $.ajax({ url: current_year, type: 'GET', cache: false, dataType: 'json', success: function(data) { var ctx = document.getElementById('current-year-chart'); var chart = new Chart(ctx, { type: 'bar', data: { labels: data['dates'], datasets: [ { label: data['income_label'], backgroundColor: "#8e5ea2", data: data['income'], }, { label: data['expense_label'], backgroundColor: 'green', data: data['expenses'], }, { label: data['savings_label'], backgroundColor: "#3e95cd", data: data['savings_goal'], }, { label: data['avail_label'], backgroundColor: "#pink", data: data['avail_to_spend'], }, ] }, options: { legend: { display: false }, title: { display: true, text: 'Savings for ' + data['year'] } } }); } }); Works great. Looks great. But! I have a django formset on a separate page that updates the table data that the chart pulls from. When I update the data in the formset and submit, redirecting to the chart page ... NO UPDATE OCCURS. If I make some code change or otherwise reload the browser, VOILA, the chart updates. I have read about either cache=false and chart.update(), but find … -
'NoneType' object is not callable on Django 2.0
I am following Obeying the Test Goat by HJWP and deploying my Django app on an Ubuntu Droplets and I come across a problem running my functional test (unit tests all clear). Details: Python 3.6, Django 2.0.1, Selenium, gecko driver 19.1, remote Unbuntu 16.04, local win10 git bash I’ve been trying to perform a function test both locally and against the server and got the results below: Local Test Result File "C:\...\.virtualenvs\superlists\lib\site- packages\django\core\handlers\base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable Against Remote Server Result: ValueError at /lists/new The view lists.views.new_list didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://midsummerseve.life:8000/lists/ I think based on the above results, there has to be something wrong with the view function which in this case is def new_list(request): list_ = List.objects.create() Item.objects.create(text=request.POST['item_text'], list=list_) return redirect(f'/lists/{list_.id}/') But I have no idea where to further and what makes it return a None object. Could it be the issue of the models of list and item? Migration steps seem quite smooth though. class List(models.Model): pass class Item(models.Model): text = models.TextField(default='') list = models.ForeignKey(List, on_delete=models.CASCADE) I am also wondering why the server would process a GET request … -
Django foreign key select field empty
I've been working on a small django website as I learn django. According to the documentation when you create a form class with a meta class that points at a model with foreign key fields, it'll render those fields as select inputs. In my application I have 3 models, client test, and record where record carries two foreign keys, each of whom point to client and test respectively Models.py class Client(models.Model): first = models.CharField(max_length=264) last = models.CharField(max_length=264) DOB = models.DateField() def __str__(self): return self.first + " " + self.last class Test(models.Model): test = models.CharField(max_length=264) fee = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.test class Record(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date) + " " + str(self.test) + " for " + str(self.client) Form.py class NewLabRecord(forms.ModelForm): client = forms.ChoiceField( label='Client ID', widget=forms.Select( attrs={'class': 'form-control'})) test = forms.ChoiceField( label='Test ID', widget=forms.Select( attrs={'class': 'form-control'})) date = forms.DateField( label='Test Date', widget=forms.DateInput( attrs={'class': 'form-control'})) class Meta: model = models.Record fields = '__all__' I render NewLabRecord at the top of my index view for records. The idea is to create a record and redirect back to the page (therefore seeing it in the list of records). Presently, I'm … -
Using existent Windows Shared Drive with Django instead of using MEDIA Files upload
I'm building a Django web application for my team. We share a drive that contains all of our documents. Is there a way for Django to mirror a shared drive instead of re-uploading everything using MEDIA FILES? Can we keep saving our files in the shared drive or do we have to upload them through Django every time? -
Is there a way to debug line by line code written in a view function of django on the website itself?
I have a view function in a django application on a webpage that a user himself writes code for (using a framework known to them). After uploading the code, they are redirected to the webpage for which they have written the code for. I want to have a way to visualize line by line the python code that is running on the view function as it gives a clear indication to the user how their code works. Is there a way to debug code on the website itself? -
Route requests with query parameters in Django without prepending with a backslash
I'm trying to process requests that have query parameters similar to the following url: http://127.0.0.1:8080/foo?bar=-capacity. I've done quite a bit of trial and error with Django's url patterns and regex but no success so far. My regex knowledge is admittedly lite. This pattern url(r'^foo(.)$', views.QueryFoo.as_view()), will process the above request but the problem is it grabs regular get requests like the following: http://127.0.0.1:8080/foo. I can add a backslash to the url pattern like this url(r'^foo/(.)$', views.QueryFoo.as_view()), which seems to be the Django norm but then I have to handle get requests from two separate urls. Any suggestions? -
Django Inline Copy Entry
I have been browsing many questions about Django inline, but can't quite find how to do this. I am using Django Nested Admin and am wanting to see how I can copy an existing row in the admin so that when I click on "Add another", it creates the new one as a copy. Here is an example: As an example...let's say I am creating a set of recipes. In these recipes, I want to create "variations" with the ingredients. So if I had "Strawberry Smoothie", I want to create a "variation" that has both the regular option, as well as a lactose-free option. So I have my main model called "Recipe": class Recipe(models.Model): name = models.CharField(max_length=128) instructions = models.TextField(blank=True) From here, I then need to add the ingredients, so in my admin.py, I have added: class RecipeAdmin(NestedModelAdmin): model = Recipe inlines = (VariationsInline,) Using the Nested Inline, I have an inline that allows me to add as many Variations, where each variation can then have as many ingredients inside of it. The issue I am running into is that sometimes these variations have 10+ ingredients (and their respective quantities) and I have to remake those for each variation I …