Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AssertionError: The field 'links' was declared on serializer SprintSerializer, but has not been included in the 'fields' option
I am having problems with reproducing example from Julia Elman's book models.py class Sprint(models.Model): name = models.CharField(max_length=100, blank=True, default='') description = models.TextField(blank=True, default='') end = models.DateField(unique=True) def __str__(self): return self.name or _('Sprint ending %s') % self.end serializer.py from rest_framework import serializers from django.contrib.auth import get_user_model from rest_framework.reverse import reverse from .models import Sprint, Task User = get_user_model() class SprintSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField('get_links') class Meta: model = Sprint fields = ('id', 'name', 'description', 'end', 'links',) def get_links(self, obj): request = self.context['request'] return {'self': reverse('sprint-detail',kwargs={'pk': obj.pk},request=request),} views.py from django.contrib.auth import get_user_model from rest_framework import authentication, permissions, viewsets from .models import Sprint,Task from .serializers import SprintSerializer,TaskSerializer, UserSerializer User = get_user_model() class DefaultsMixin(object): authentication_classes = (authentication.BasicAuthentication,authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) paginate_by = 25 paginate_by_param = 'page_size' max_paginate_by = 100 class SprintViewSet(DefaultsMixin, viewsets.ModelViewSet): queryset = Sprint.objects.order_by('end') serializer_class = SprintSerializer I try to see repr from shell from board.serializers import SprintSerializer >>> s = SprintSerializer() >>> print (repr(s)) But I have problem AssertionError: The field 'links' was declared on serializer SprintSerializer, but has not been included in the 'fields' option. How to debug this issue? -
Django 1.11 + Amazon S3 for collectstatic
I just tried serving my static files in production using Amazon S3 on eu-west-1. I'm using Elastic Beanstalk and Django 1.11. Furthermore I use boto3 and the package Django Storages for it. My problem is that even though collectstatic worked and the files are now in the S3 bucket, the Django Admin still doesn't use static files. For context, let me give you the settings I used: import os from django.core.exceptions import ImproperlyConfigured # Static files (CSS, JavaScript, Images) STATICFILES_DIRS = [BASE_DIR.parent / 'myproject' / 'static'] INSTALLED_APPS += ['storages', ] def get_env_variable(var_name): """Get the environment variable or return exception.""" try: return os.environ[var_name] except KeyError: error_msg = 'Set the {} environment variable'.format(var_name) raise ImproperlyConfigured(error_msg) AWS_ACCESS_KEY_ID = get_env_variable("ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = get_env_variable("SECRET_ACCESS_KEY") AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_STORAGE_BUCKET_NAME = get_env_variable("BUCKET_NAME") AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'config.settings.aws.utils.StaticRootS3BotoStorage' DEFAULT_FILE_STORAGE = 'config.settings.aws.utils.MediaRootS3BotoStorage' MEDIA_URL = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' S3_USE_SIGV4 = True Does anyone have an idea what went wrong? Why did collectstatic work, but Django Admin doesn't apply the css and the javascript? -
Update multiple object attributes at once
I have such a data model with topic and entry: class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic) title = models.CharField(max_length=200) text = models.TextField() tags = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return string representation of the model""" return self.text[:50] + "..." I intend to retrieve the entries whose topic is questions and title starts with numerals, then change the unqualified titles to the qualified title which I set is the first line retrieved from entry's text. entries = (Entry.objects .filter(topic__text="Questions") .filter(title__regex=r"^\d+")) In[63]: [entry.title for entry in entries] Out[63]: ['1', '1', '1', '1', '1'] Replace the integer with the first line of entry's text as the title: def first_line(text): return re.search(r".+", text).group() for entry in entries: new_title = first_line(entry.text) setattr(entry, 'title', new_title) entry.save() I am novice of Django, and wondering: If "regex" is a best solution to filter titles startswith a numerical? entry.save() is implemented multiple times, could all the changes be saved in one go? Could such operations be handle on database … -
how to declare flag like variable in django template
I'm using for loop inside that i just check condition if match then flag=1 else flag=0. but i'm not able to do that. can any one help me please ? -
Update details in the Detail view
I have a client detail view which has various information of the client i want to give an edit option to the use , so that they can edit the client. urls.py url(r'edit/(?P<pk>[0- 9]+)/$',views.ClientInfoUpdate.as_view(),name='clientinfo'), views.py class ClientInfoUpdate(UpdateView): model = ClientInfo fields = '__all__' form_class = ClinetInfoForm forms.py class ClinetInfoForm(ModelForm): class Meta: model = ClientInfo fields = '__all__' -
psycopg2.DataError: integer out of range
Thanks in advance for the help. I am new to Django, and trying to use postgres for my database. When I try to migrate my Django models, the following error shows up: psycopg2.DataError on line 85 of django/db/backends/utils.py django.db.utils.DataError I originally was using MariaDB and there were no problems. Also, my models.py file currently has the models that I wish to use commented out. Thanks -
set django form initial value to blank when the filed is required
In Django forms how do I specify default value of a field to blank and force users to select one of choices. class JobForm(forms.ModelForm): notification_email = forms.ChoiceField(choices=[("a","a"),("b","b")],initial="--",required=True) Im using this, but it sets "a" as initial value. -
Open Sqlite database file directly inside django
Is there any way to open SQLite DB directly in Django. I am working on an application for which a back end script creates a database for every execution. The database consists of multiple tables and I have to show those tables on the web site made in django. Is there any other way around for this? -
Django DRF / Nginx - 404 when URI parameters include hyphens?
In other words this works : GET https://api.example.com/resource/De48Ie_38 But this gives a 404 from nginx "not found" : GET https://api.example.com/resource/De48Ie-38 (of course the resource does exist) I have no idea why, and how I could address this. Please share your advice. Thanks -
how to add dynamic variables in data target for django
{% for key,value in config.items %} <button type="button" class="btn btn-info btn-xs" data-toggle="modal" **data-target='#'{{key}}**><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button> <div class="modal fade" **id={{ key}}** role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">{{key}}</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endfor %} //I want to call each element by {{key}} so that I can display all the values based on the loop value.Please anyone suggest me how to fix this issue -
ValueError: "<Task: Task object>" needs to have a value for field "id" before this many-to-many relationship can be used
Problem Description I have 2 models that have a many to one relationship (There can be 1-many Tasks per Event), so I have set up a reverse ForeignKey relationship with a related name as you'll see below. I want to be able to create one or more of those tasks on POST of an Event, so I am using nested serializers as shown in the documentation for writable nested serializers for Django Rest Framework (I've used this method with great success in the past). I can create a Task without any difficulty and I can create an Event without problems (with tasks=[]). The problem is that this time, for whatever reason, if I nest the exact same payload I am using to create a Task into the tasks array, I get the following error: ValueError: "<Task: Task object>" needs to have a value for field "id" before this many-to-many relationship can be used.. This is confusing for several reasons: The TaskSerializer accepts the payload on its own to create a new Task. The Event actually gets created, but with tasks=[] Events and Tasks is not a many-to-many relationship, so it must be erroring on assignees, but I'm just giving it … -
What is the best way to store comments in database?
I am working on small community site using django, python, mysql. In this community users can create a comment to an article, and also they can create a comment to comment that created by other users. The first models I was thinking about is like this. comment -
Collect value from textfield in HTML and insert to database
I have a simple form in HTML with 2 input textfield, : name & age , and a submit button I want after user click submit button name & age will be insert to table 'User' of models class Can you teach me how to do that ? thanks alot -
What does 'u' mean in the output of an object in djnago?? for example: >>> data {'cal_id': u'2', 'username': u'tester'} [duplicate]
This question already has an answer here: What does the 'u' symbol mean in front of string values? [duplicate] 2 answers I'm not able to find anywhere what does 'u' here stands for.. please help me out >>> data {'cal_id': u'2', 'username': u'tester'} -
I want to pass dynamic id to a anchor tag for that I tried so many ways but its not working
<script> <!-- json format call --> $(document).ready(function(){ $('#college').dataTable({ "processing": true, "ajax": { "processing": true, "url": "{% url 'collegeview' %}", "dataSrc": "" }, "columns": [ { "data": "pk" }, { "data": "fields.college_name" }, { "data": "fields.college_email" }, { "data": "fields.college_number_1" }, { "data": "fields.college_address" }, { "data": "fields.college_category" }, { "data": "fields.university_name" }, { className: "center", defaultContent: '<a href="{% url 'collegeprofile' %}" class="btn btn-block btn-primary">View</a>', data: null } ], }); }); </script> -
Alternate methods to use context processors in Django with templating Jinja2?
I am using Jinja2 templating in Django. Jinja2 doest support context processors. Is there any alternate ways to achieve the same functionality that context processors provide, while using Jinja2 with Django ? One solution that I found was django-jinja. But, I don't know how to use this with Jinja2 (Documentations are not really good). If anyone used django-jinja, pleaese explain how to use this properly or if you know any other methods/suggestions, please contribute. -
Hosting a local website to the public using a VPN?
Is it possible to host a local website to a select number of people who have access to my VPN address? My thought process is this. I get a windows computer to host a VPN network, with the same computer I would host a mysql server and a Django (or whatever framework of my choice) application on 127.0.0.1. Then provide my VPN ip address to my users who can use something like cisco anyconnect to connect to my VPN and view my localhost site on something like 127.0.0.1:8000. Is this feasible? Am I missing anything? -
How to get just one field from a reverse reference in Django Rest Framework
I have two models, Roundtrip and Tour, and another model called RoundtripTour where I can link those two models in a many-to-many fashion. I have made a rest service that returns a Tour instance and a list of all RoundtripTour instances through a reverse reference, and it works perfectly, but the service returns all fields from the RoundtripTour model, and I want to return only the field that references the Roundtrip model instance. These are my models: class Roundtrip(models.Model): name = models.CharField(max_length=70, verbose_name=_('Name')) code = models.CharField(max_length=8, verbose_name=_('Code')) duration = models.IntegerField(verbose_name=_('Duration')) description = models.TextField(verbose_name=_('Description')) class Tour(models.Model): name = models.CharField(max_length=70, verbose_name=_('Name')) description = models.TextField(verbose_name=_('Description')) is_own = models.BooleanField(default=True, verbose_name=_('Is own tour?')) code = models.CharField(max_length=10, verbose_name=_('Code')) class RoundtripTour(models.Model): roundtrip = models.ForeignKey(Roundtrip, on_delete=models.PROTECT, related_name='tours', verbose_name=_('Roundtrip')) tour = models.ForeignKey(Tour, on_delete=models.PROTECT, related_name='roundtrips', verbose_name=_('Tour')) day = models.IntegerField(verbose_name=_('Day')) This is my serializer: class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Tour fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips') depth = 1 This is my view: class TourRoundtripsViewSet(viewsets.ModelViewSet): queryset = models.Tour.objects.all() serializer_class = serializers.TourRoundtripsSerializer I would like the roundtrips reverser reference to return only the field roundtrip from the RoundtripTour model (roundtrip field of RoundtripTour model). Is that possible? -
`pk` and `id` are not identical when coping instances with inheritance
I am aware that pk is preferable because id is builtins.They are identical. However, reference to copy instances which use inheritance, it's not complicated to distinguish them: In the official tutorial doc #Due to how inheritance works, you have to set both pk and id to None: django_blog.pk = None django_blog.id = None django_blog.save() # django_blog.pk == 4 There, pk is definitely not identical to id How to understand it? -
Django/Python convert string to Model filter with '=' in result
I'm working on writing test_templates so that I can very quickly write my tests, as I realized I was duplicating the same code with different variables. But I've run into a problem: # path of view # '/app/view/path/' view_name = 'service:create_employee_profile' # valid field values to test form success. valid_values = { 'first_name': 'First', 'last_name': 'Last', } # Search criteria for Model 'get' and 'filter' # Model.objects.get(field=value) # Model.objects.get(eval(model_criteria)) model_criteria = 'first_name="First"' """ TESTS: Submitting forms """ # TEST: View saves valid object. def test_view_saves_valid_object(self): response = self.client.post( reverse(view_name), valid_values) self.assertTrue(Model.objects.filter(eval(model_criteria)).exists()) I thought I was set with eval(), until I quickly discovered that it doesn't like =. I tried using 2 different variables for 'first_name="First"', but a Model will never find a field out of a variable='field_name'. These templates help me test multiple views with adding just a little information to them, and since more than 1 test in the template requires retrieving an instance of the model I am trying to set a variable at the top that will run all associated tests. -
Django channels installation failed : Command "python setup.py egg_info" failed with error code 1
I got this error and referred to this link. Then I did the following sudo pip install pathlib then I did this pip install channels This is the output that I got. Collecting twisted>=17.5 (from daphne~=2.1->channels) Using cached https://files.pythonhosted.org/packages/12/2a/e9e4fb2e6b2f7a75577e0614926819a472934b0b85f205ba5d5d2add54d0/Twisted-18.4.0.tar.bz2 Complete output from command python setup.py egg_info: Download error on https://pypi.python.org/simple/incremental/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) -- Some packages may not be found! Couldn't find index page for 'incremental' (maybe misspelled?) Download error on https://pypi.python.org/simple/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) -- Some packages may not be found! No local packages or download links found for incremental>=16.10.1 Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/8z/kyzmz7xd4yv6fpz5lssfyf540000gn/T/pip-install-yi0d4y1s/twisted/setup.py", line 21, in <module> setuptools.setup(**_setup["getSetupArgs"]()) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/setuptools/dist.py", line 268, in __init__ self.fetch_build_eggs(attrs['setup_requires']) File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/setuptools/dist.py", line 313, in fetch_build_eggs replace_conflicting=True, File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/pkg_resources/__init__.py", line 836, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1081, in best_match return self.obtain(req, installer) File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1093, in obtain return installer(requirement) File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/setuptools/dist.py", line 380, in fetch_build_egg return cmd.easy_install(req) File "/Users/admin/Development/DjangoWebSockets/multichat/lib/python3.5/site-packages/setuptools/command/easy_install.py", line 623, in easy_install raise DistutilsError(msg) distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('incremental>=16.10.1') ---------------------------------------- Command "python setup.py … -
django how to render same template twice
I am new to using django and am unfamiliar as to how my question should be worded. I have been working on a new web app but noticed that the initial loading of the website is slow. My current view code is here. from jinja2 import Environment, FileSystemLoader from django.http import HttpResponse from tools import fetcher import requests import json def index(request): env = Environment(loader=FileSystemLoader('templates')) template = env.get_template('index.html') template_values = {'popular_stocks': []} popular = fetcher.get_tops() for instrument in popular: r = requests.get('https://api.iextrading.com/1.0/stock/%s/quote' % (instrument['symbol'])) quote = json.loads(r.content.decode('utf-8')) template_values['popular_stocks'].append(quote) return HttpResponse(template.render(template_values)) Is there anyway to speed up the loading of my site by loading the initial index.html first WITHOUT any popularstocks and then submitting the fetcher.get_tops() to the template values? I know of AJAX but I am unsure how to implement it or if that is even what I need. Any step towards the right direction would be appreciated. -
Custom social sing up form
I have a custom Form already working for normal sign in (with email), now i have the problem with the social one. Following the official documentation from allauth.socialaccount.forms import SignupForm class MyCustomSocialSignupForm(SignupForm): def save(self): # Ensure you call the parent classes save. # .save() returns a User object. user = super(MyCustomSocialSignupForm, self).save() # Add your own processing here. # You must return the original result. return user And my code is the following : settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'accounts.forms.SignupFormEmail' SOCIALACCOUNT_FORMS = {'signup': 'accounts.forms.SignupFormSocial'} forms.py class SignupFormEmail(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['localizacion'].label = 'Categorias' localidades = Alcance.objects.exclude(pk=1).filter(zona_afectada=Alcance.CONCEJO) localizacion = forms.ModelChoiceField(queryset=localidades, label='Concejo',empty_label="Selecciona tu concejo") def signup(self, request, user: User): self.user=user user.residencia.add(self.cleaned_data['localizacion']) user.save() class SignupFormSocial(SignupForm): localidades = Alcance.objects.exclude(pk=1).filter(zona_afectada=Alcance.CONCEJO) localizacion = forms.ModelChoiceField(queryset=localidades, label='Concejo', empty_label="Selecciona tu concejo") def __init__(self, sociallogin=None, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['localizacion'].label = 'Categorias' def save(self,request): # Ensure you call the parent classes save. # .save() returns a User object. user = super(SignupFormSocial, self).save() # Add your own processing here. user.residencia.add(self.cleaned_data['localizacion']) user.save() # You must return the original result. return user The problem is that i get the following exception django.core.exceptions.ImproperlyConfigured: Error importing form class accounts.forms: "cannot import name 'BaseSignupForm'" I also try , inheriting from form.Form and from SignupFormEmail , … -
Django REST: Processing lists within a request
I'm making an endpoint for purchases that takes in a list of items to be purchased and updates the database accordingly. The parameters are: { items: [ { product_id: <product_id>, quantity: <product_quantity> }, …. ] } Each product_id corresponds to a product to be purchased. How do I process all of them? -
Django: my css static path does not exist
My link looks like this: <link rel="stylesheet" type="text/css" href="{% static 'css/background.css' %}"> This is fine because it gets that path I want which is href="/static/background.css". I use {% load static}. I have django.contrib.staticfiles in my INSTALLED_APPS. This is some more relevant info on my settings.py: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] But I'm pretty sure this is right too. My problem is that static/css/background.css cannot be found by my local server. I know this because http://localhost:8000/static/background.css gives me a 404 error. I don't know why this is the case because this is my project file path: Project Project src static css background.css