Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use Swagger in production for free?
I would like to deploy my Django backend on Heroku with Swagger documentation. I wonder whether is it legal to make my Swagger documentation of API available to the whole world? -
Python - `\n` in json
I'm using POSTMAN to send the POST data. After posting the data, I body I receive in request.body is { "title": "Kill Bill: Vol. 2","content": "http://netflixroulette.net/api/posters/60032563.jpg\n\nabcdefrefbqwejf\n\nq efjqwefqwrf aksks" } I want to json.loads the body. However, I've new line character in my json. So, I first replace \n with \\n and then do json.loads. But after replacing \n with \\n, the string I receive is :- {\n "title": "Kill Bill: Vol. 2","content":\n "http://netflixroulette.net/api/posters/60032563.jpg\n\nabcdefrefbqwejf\n\nq efjqwefqwrf aksks"\n} And then when I do json.loads, it results in error. This is because of new line character at the start of string and at various other locations as well. Any idea how can I treat this? -
Django Row Update in Table
I'm trying to update a database row based on the table row's info. I've attached a screenshot of the UI here: Table Form As you can see from the image each table row has an individual form that should update the database for the related database row. Is there a way to iterate over all the instances in the queryset when rendering the form? Or possible to set each rendered form's id/action uniquely and have that passed to the post request on submission. Views.py class CreateRequestListView(ListView, ModelFormMixin): model = StoreRequest form_class = StoreRequestForm second_form_class = StoreConfirmForm template_name = 'create-request.html' def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) record_request_id = StoreRequest.objects.get(id=3) self.form2 = StoreConfirmForm(request.POST, instance=record_request_id) return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) record_request_id = StoreRequest.objects.get(id=3) self.form2 = StoreConfirmForm(request.POST, instance=record_request_id) if self.form.is_valid(): self.object = self.form.save(commit=False) self.object.request_created_by = request.user self.object.request_date = timezone.now() self.object.save() self.form = self.get_form(self.form_class) return HttpResponseRedirect('/tracker/requests') elif self.form2.is_valid(): self.object = self.form2.save(commit=False) self.object.request_confirmed_by = request.user self.object.request_fulfilled_date = timezone.now() self.object.save() return HttpResponseRedirect('/tracker/requests') return self.get(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(CreateRequestListView, self).get_context_data(*args, **kwargs) context['storerequests'] = StoreRequest.objects.exclude(request_invoice_no__isnull=False) context['form'] = self.form context['form2'] = self.form2 context['errorlist'] = self.form.errors return context -
add fields to model from another one related with OneToOneField or ForeignKey relation
i am new to django and i am using the 1.11 version i have several models some related with foreign keys and some with oneToOne relation. for instance the user and profile models, i would like to add in the profile form fields from the user form how? -
override password_validation messages
I use UserCreationForm to create new users. from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'is_active'] UserCreationForm automatically adds two fields (Password1 and Password2). If the password is too short then it raises an error, telling that. Or if it is too simple or common. It is done via django.contrib.auth.password_validation. I wonder if I can override the messages of these errors. right now the source code for password validation is: def validate(self, password, user=None): if len(password) < self.min_length: raise ValidationError( ungettext( "This password is too short. It must contain at least %(min_length)d character.", "This password is too short. It must contain at least %(min_length)d characters.", self.min_length ), code='password_too_short', params={'min_length': self.min_length}, ) but when I try to use this code in form definition to override this error message the label changes, but error_messages remain the same: password1 = forms.CharField(label='New Label', error_messages={'password_too_short': 'My error message for too short passwords'}) What am I doing wrong? -
Database Model for Parking App API
I had this this question given to me during an onsite interview and i had to walk out of the interview as I had no clue how could I tackle this question. I studied Django Rest Framework, Django for last month. I was thinking maybe I would be able to tackle this problem by now. However I am getting stumped even to think about the app/Database model. Parking App API: Assume that we are building a parking app for SF city and we need two API's. Build the following REST APIs. (choose Django or Flask framework. DB is of your choice.) 1. REST API to list all **available** parking spots. - Input params: {lat, lng, radius} response: returns an array of elements each containing an id, lat and lng. 2. REST API to reserve an available parking spot. input params: { parking_spot, time-range } Note: You can store a dummy lat, lng locations in your table. Optional: - test cases for the API's - view existing reservations - cancel existing reservations - extend existing reservations. Deliverables: * Please host the code in a git repo and share the link with me. * Commit every logical step. I have an idea … -
Django mniddleware and rest api integration
I am planning create REST api at django and front with angular 4. I am wondering how to integrate django middleware with rest framework, because for example DEFAULT_AUTHENTICATION_CLASSES set by default are very similar to AuthenticationMiddleware from django and it is processed after middleware so what is the point of exists it? For now i think it can be useful for huge applications by adding next abstraction layer BUT for small application or with custom user management flow it is necessary to have it? For example I have my own user model and auth middleware or I use just django builtin auth middleware so can I safety just delete some of rest framework's classes, methods etc if I am handling it in middleware? -
type error django include url... thing that should not be django1.11 python2.7
I am using djangos include feature in my main urls file, from my app urls file. main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/', include('posts.urls')), ] posts.urls.py from django.conf.urls import url from . import views #relative import to post views urlpatterns = [ url(r'$',"views.posts_list" ), #list all posts url(r'create/$',"views.posts_create" ), url(r'detail/$',"views.posts_detail" ), url(r'update/$',"views.posts_update" ), url(r'delete/$',"views.posts_delete" ), ] I have looked at the docs on this issue: https://docs.djangoproject.com/en/1.11/ref/urls/#include and the source code: https://docs.djangoproject.com/en/1.11/_modules/django/conf/urls/#include and I have no idea what I am doing wrong. Please help. Hugs kisses, and high fives -
Page not found 404 on Django site
I've started with the online tutorial on Django(1.9) from thenewboston channel on YouTube which is building a simple music app. However I am getting the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, music, didn't match any of these. Here are my files: website/website/settings.py ... INSTALLED_APPS = [ 'music', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... ROOT_URLCONF = 'website.urls' ... website/website/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^music/', include('music.urls')), url(r'^admin/', admin.site.urls), ] website/music/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] website/music/views.py from django.http import HttpResponse def index(request): return HttpResponse("<h1>This is the Music app homepage</h1>") P.S: I've made sure that I am editing the correct urls.py file and it is placed in the correct directory also I guess, unlike the other similar questions asked about this problem -
URL was not found on this server - nginx django
I'm having trouble getting a new Django app to render when I go to the url. I just get a 'Not Found The requested URL /spacegame/ was not found on this server.' error. I 'installed' the app in settings.py,setup the url patterns in mains urls.py and app urls.py correctly, and app views.py, but still not working. It is working on my Django development server, but not on production server. I think it could also be the nginx settings, but not sure. Any help would be greatly appreciated. The app name is 'spacegame'. main urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^', include('homepageapp.urls')), url(r'^spacegame/', include('spacegame.urls')), url(r'^admin/', admin.site.urls) ] spacegame.urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ] spacegame.views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the spacegame index.") nginx conf server { listen 80; server_name ::removed:: ; return 301 https://$server_name$request_uri; root /home/projects/aar/aarcom; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/home/projects/aar/aarcom/aarcom.sock; } location /static { allow all; autoindex on; alias /home/projects/aar/aarcom/static; } location ~ /.well-known { allow all; } } -
how do I access a django form value in the __init__ method for a query
I have a model that includes a foreign key: class Part(models.Model): partType = models.ForeignKey(PartType, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) part_name = models.CharField(max_length=60) class QuotePart(models.Model): quote = models.ForeignKey(Quote, on_delete=models.CASCADE) line = models.PositiveSmallIntegerField(default=1) partType = models.ForeignKey(PartType, on_delete=models.CASCADE) # part can be None if the part has not been selected part = models.ForeignKey(Part, on_delete=models.CASCADE,blank=True,null=True) I have a form that allows parts to be added to a quote and want to want to limit the choices on the form to just the Parts that are the right PartType but my code is not working: class QuoteBikePartForm(ModelForm): def __init__(self, *args, **kwargs): super(QuoteBikePartForm, self).__init__(*args, **kwargs) self.fields['partType'].widget.attrs['disabled'] = True self.fields['frame_part'].widget.attrs['disabled'] = True partType = kwargs.pop('partType') self.fields['part'].queryset = Part.objects.filter(partType=partType.pk) class Meta: model = QuotePart fields = ['quote','line','partType','frame_part', 'part', 'quantity','cost_price', 'sell_price'] QuoteBikePartFormSet = inlineformset_factory(Quote, QuotePart, form=QuoteBikePartForm) I have tried a number of different things and so far no luck. -
Django: How structure/use project with multiple apps
I've already read the official Django tutorial and many other questions here on stackoverflow.com, but it seems like there is no real answer to my question or I just don't get it. Unfortunately, I could not find an appropriate tutorial with more than one app. My problem: A Django project usually consists of multiple apps. What I don't get is how those apps can work together. Example: Let's say we build a news website and this news website has blog posts, polls and a comments area etc. So I think it would make sense to create an app called polls, another app called blog and the app comments. So, when you browse to url.com/news/5 for example, you'll see the blog post with the id 5. Or when you browse to url.com/polls/2 you'll see the poll with the id 2. Everything ok. Now, however, I don't want it to be separated. What I don't get is when I want to have those parts of a website on a single webpage (like in most of the websites). That means if I browse to url.com/news/5 it should not only display the news but also the poll (because the poll belongs to this news … -
Secret Key environment variable not working on Ubuntu. Django, Postgres, Gunicorn, Nginx, Virtualenv
This is the following error I get when I try to run the makemigrations command while my virtualenv is active: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/tony/vp/vpenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/tony/vp/vp/config/settings/production.py", line 1, in <module> from .base import * File "/home/tony/vp/vp/config/settings/base.py", line 22, in <module> SECRET_KEY = os.environ["VP_SECRET_KEY"] File "/home/tony/vp/vpenv/lib/python3.5/os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'VP_SECRET_KEY' I have set my environment variables inside three locations: in my virtual environments bin/activate script: Environment=VP_SECRET_KEY="****" Environment=VP_DB_PASS="****" in the .bashrc file: VP_SECRET_KEY="****" VP_DB_PASS="****" and in my gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=tony Environment=VP_SECRET_KEY="****" Environment=VP_DB_PASS="****" Group=www-data WorkingDirectory=/home/tony/vp/vp/ ExecStart=/home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application [Install] WantedBy=multi-user.target … -
Django: How to have multiple "add another field" buttons in a form.
I'm new to django and I'm having a lot of trouble with forms. I'm making a calculation-based tool and I need to be able to have an arbitrary number of inputs. As a really basic example, let's say I want to make a calculator that will sum and subtract any number of inputs. Each number to be added or subtracted is in its own number field. Both the list of "adding" fields and the list of "subtracting" fields has its own "add another field" button. For starters, here's something that adds two inputs (since I can't figure out how to implement even 1 "add another field button" or understand the answer to it). views.py from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from .forms import AddForm def _from_str(s): try: s = int(s) except ValueError: try: s = float(s) except ValueError: pass return s @csrf_exempt def web_adder(request): if request.method == 'POST': form = AddForm(request.POST) # form = MyForm(request.POST, extra=request.POST.get('extra_field_count')) if form.is_valid(): return web_adder_out(request, _from_str(form.cleaned_data['addend0']), _from_str(form.cleaned_data['addend1'])) else: form = AddForm() # form = MyForm() return render(request, 'addercontent.html', {'form': form}) def web_adder_out(request, a, b): return render(request, 'addercontentout.html', {'content':[a + b]}) forms.py from django import … -
How to add a link to a website and space in API_DESCRIPTION in Django Rest Documentation?
I use Django Rest Framework Documentation and I would like to add a link to another website. Unfortunately they way shown below on the screenshot is not working. Anyone have an idea? Furthemore, I would like to know how can I add space in description. Thanks in advance. -
Django - Create a custom id
I know Django auto generates a ID for my model with a primary_key And I also know that if I want to generate a custom id I should do: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) But how can I change this so the id would look like this YYYYMMDDXXXXXX ? Where: YYYY = year MM = month DD = day XXXXXX = random number -
What is Django's migration?
I've been wrapping my head around this concept for a while, when I start a new django project, it urges me to apply migrations: # python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. why do I need to do it? could anybody give a concise explanation and a simple use case of migration? -
Django form fields not loading in template
I can't seem to get a model form to load in my template. models.py from django.db import models class Event(models.Model): name = models.CharField(max_length=60) start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() description = models.TextField() forms.py from django import forms from .models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = ['name'] views.py from django.shortcuts import render from .forms import EventForm def index(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() else: form = EventForm() return render(request, 'index.html', {'events': events}) index.html <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} </form> <button type="submit">Save</button> I can get the form to print to the console on load when adding print(form) in views.py on the GET request, but it doesn't load in the template. -
Is there a way that can give me easy friend importing AND invite from Facebook, and (or) Gmail to my website?
Is there a way that let me send to my gmail contacts a request to invite them to my django website. -
Django generic view - clarification on extra_context property - github vs installed source
So i was digging in Django's source codes and came across these two: views.generic.list.py and views.generic.base.py so this is line 26 in base.py in ContextMixin's get_context_data method if self.extra_context is not None: kwargs.update(self.extra_context) return kwargs MultipleObjectMixin (line 9 in list.py) inherits ContextMixin and calls the parent class's method in the overwritten get_context_data method (line 136 in list.py) So the extra_context variable should work and add extra context to the dictionary passed to template engine in classes that use the MultipleObjectMixin. But the questions i looked up stated that extra_context isn't supported anymore, and i ran a code that didn't work and i had to overwrite get_context_data to get what i wanted, does anyone have any explanations about this? P.S. I checked the installed sources on my system, and it was different than the github code, so my question now is why is the repository behind from latest released versions? -
Why request body in JSON is not mentioned as acceptable in Django Rest Documentation?
I have written backend using Django Rest Framework. I am sure that json is working properly, however in the documentation I have only mentioned in create methods Request Body - The request body should be a "application/x-www-form-urlencoded" encoded object, containing the following items. Does anyone have an idea why there is no information about json format? It seems to me that it should be something like this Body - The request body should be a "application/x-www-form-urlencoded" or "application/json" -
How to override a single item on a model form django
How does one correctly override the styling of a single item in Django's model form {{form}} call. I cant seem to just overide the defualt behaviour and add my necessary style. Specifically, I would like to add a simple slider that passes through some text to the view. I have added an extra field to my form as follows: class CreateTestForm(forms.ModelForm): difficulty = forms.CharField() class Meta: model = Test And the following in my html directly: <form method="POST" action=""> {% csrf_token %} {{ form|crispy }} <strong>Difficulty</strong> <input id="difficulty" type="text" value="" class="slider form-control" data-slider-min="0" data-slider-max="10" data-slider-step="1" data-slider-value="[0,10]" data-slider-orientation="horizontal" data-slider-selection="before" data-slider-tooltip="show" data-slider-id="blue"> </br> <input type='submit' value='Create' class='btn'> </form> However, when I render the view, I get two difficulties inputs (one slider and one box). I understand that Django is creating the text box for me, but I assumed, giving my slider the same id would simply override it? From my belief, I would also have to have the slider defined in the forms.py class for this form, else it is not accessible in cleaned_data in the view. Any ideas? -
Django: Is APPEND_SLASH set to True even if not in settings.py?
Here is my urls.py: urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] If I type 127.0.0.1:8000/polls in my browser (Firefox) I get redirected to 127.0.0.1:8000/polls/ (with slash at the end). To be honest, I am confused why that is. Because in my settings.pythere is no APPEND_SLASH = True However, the Django docs say: APPEND_SLASH Default: True When set to True, if the request URL does not match any of the patterns in the URLconf and it doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended. Note that the redirect may cause any data submitted in a POST request to be lost. Source: https://docs.djangoproject.com/en/1.11/ref/settings/#append-slash Is it that APPEND_SLASH is True by default even if it's not in settings.py? And that you should only put it in this file if you want to set it to False? Or what's the reason for that behaviour? -
How to access/create a proper Request object for DRF Serializer?
I have created a REST API using DRF, and that works well enough. The frontend is a simple page that allows data to be viewed and updated. Now I am trying to add more interactivity to the site using WebSockets with django-channels. The Channels system is fairly simple to use and also works nicely. However the issue I am now facing is trying to combine all of the moving pieces to work together. My idea is that the initial page refresh comes through the REST API, and any subsequent updates would automagically come through a WebSocket after every update (post_save). I have nice DRF Serializers for all my models, but alas those do not work without a Request (HyperLinkedIdentityField for instance). So my question is, how do I somehow create the Request object that the Serializers want? -
Django admin shows Post object in lieu of title
Really new to Django so bear with me :) I am running into an issue to display the posts titles in the Django admin. I have tried both in Python 3 class Post(models.Model): title = models.TextField(max_length=100) text = models.TextField(max_length=10000) tags = models.TextField(max_length=300) comments = models.TextField(max_length=400) def __str__(self): return self.title and Python 2 class Post(models.Model): title = models.TextField(max_length=100) text = models.TextField(max_length=10000) tags = models.TextField(max_length=300) comments = models.TextField(max_length=400) def __unicode__(self): return self.title but unfortunately in the Django admin I see "Post object "in the list of posts Thanks in advance for your help.