Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translations not working on elastic beanstalk aws
Django translations work on my local machine but when I deploy the application to elastic beanstalk AWS the translations are not found by the server. It seems to be a path related issue but I am unable to figure out what is wrong with the path that I am using. I have the following code in my settings file. here = lambda *x: join(abspath(dirname(__file__)), *x) PROJECT_ROOT = here('..') root = lambda *x: abspath(join(abspath(PROJECT_ROOT), *x)) LOCALE_PATHS = ( root('conf', 'locale'), ) My settings file is inside the main app and the conf folder is in the main project directory which is one directory level above the settings file. -
How to choose by which fields will be filtering?
How can I can exclude(pop) email field from data object in my view in order to make filtering by the remaining data? View's logic will be based on email later. Also, It's possible that I'll need to exlude more fields from serializer... I've got simple view like this: class DataView(GenericsAPIView): serializer = TotalSerializer def post(self, request, *args, **kwargs): data = DataSerializer(data=request.data) data.is_valid(raise_exception=True) # Here I need to pop some fields from serializer queryset = self.get_queryset(**data.validate_data) ... serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) And here is my serializer, which serializes the data from the post request: class DataSerializer(serializers.Serializer): field_one = serializers.CharField(max_length=255) fields_two = serializers.CharField(max_length=255) email = serializer.EmailField() -
Does django version 1.11 work with djongo package?
When I try to run the server using django==1.11 I get this error. from djongo import models File "/usr/local/lib/python3.6/dist-packages/djongo/models/__init__.py", line 3, in <module> from .fields import ( File "/usr/local/lib/python3.6/dist-packages/djongo/models/fields.py", line 28, in <module> from django.db.models.fields.mixins import FieldCacheMixin ModuleNotFoundError: No module named 'django.db.models.fields.mixins' But when I try doing the same using django==2 everything works fine. Nothing regarding the Django version is given in the docs: https://nesdis.github.io/djongo/get-started/ Any help is appreciated. Thank You, Ayush -
How to create new cloumns from existing columns in django sqlite models.py files?
I am creating a simple result processing system using django. I made this class: class Course(models.Model): Course_Code = models.CharField(max_length=50,unique=True,primary_key = True) Course_Name = models.CharField(max_length=50) Dept = models.CharField(max_length=50) Credit_Lecture = models.IntegerField() Credit_Tutorial = models.IntegerField() Credit_Practical = models.IntegerField() Max_Marks_MidTerm = models.IntegerField() Max_Marks_Theory = models.IntegerField() Max_Marks_Pr = models.IntegerField() Now I want to make a new column that stores the total credit value of a course i.e. : Credit_Total = Credit_Lecture + Credit_Tutorial + Credit_Practical How should I do so? I found the following possibilities but failed: Total_Credit =Credit_Lec + Credit_Tut + Credit_Pr Total_credit = SELECT CAST(Credit_lec AS VARCHAR(255)) AS credit_lec FROM Course; -
How does this syntax come true in Django template?
'pics': { ';c:black;': 'xxx1.jpg', ';c:red;': 'xxx2.jpg', ';c:gary;': 'xxx3.jpg', ';c:blue;': 'xxx2.jpg', }, smarty template code : {{if pics[';' + index + ':' + sid + ';']}} // Do something.. index and sid are derived from another set of dict. How does this syntax come true in Django template? Because I'm a novice, I need an demo , Hope to help me thank you!! -
can't implement django inside html
I have a problem where I can't use my Django variables inside Html This is my code : models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) content = models.TextField(default="---") H_price = models.IntegerField(default=0) L_price = models.IntegerField(default=0) remaining = models.IntegerField(default=0) original_price = models.IntegerField(default=0) Ended = models.BooleanField(default=False) Published = models.BooleanField(default=True) class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.title def get_absolute_url(self): return reverse('Products.views.post', args=[self.slug]) Views.py from django.shortcuts import render from .models import Post # Create your views here. def index(request): posts=Post.objects.all() return render(request, 'Index.html', {"Posts": posts}) def post(request): return Index.html <h1>This is just a title </h1> {% for post in posts %} <div> <h3> {{ post.title }}</h3> <h3> {{ post.content }}</h3> </div> {% endfor %} I know this isn't the best way to do Html but the goal is just to get it to work then I will style it with css and make everything Look Clean When i run the server i only get "this is just a title" Any suggestions to help me fix it will be apreciated Note that I am a begginer in django -
Reverse for 'details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['entry\\/(?P<pk>[0-9]+)$']
I have this error: Reverse for 'details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['entry\/(?P[0-9]+)$'] On line number 7: From _calender_entry.html <div class="calender_entry col-lg-4"> <h2> {{ entry.name }} </h2> <h4> {{ entry.date }} </h4> <p> {{ entry.description }} </p> <button onclick="window.location='{% url 'details' pk=entry.id %}'" class="btn btn-primary"> View Details </button> </div> This is from my urls.py file: urlpatterns = [ path('', views.index, name='index'), path('entry/<int:pk>', views.details, name='details'), path('admin/', admin.site.urls), ] And here is method from views.py : def details(request, pk): entry = Entry.objects.get(id=pk) return render(request, 'myapp/details.html', {'entry' : entry}) Could anyone be able to tell me how could I fix this problem? -
Django with Angular 4 in Docker deployed but the error "SyntaxError: expected expression, got '<'" comes
In development it works very fine but after deployment the error comes:( Network tab Console tab -
Python 3.6 ModuleNotFoundError when trying to access class from different file
I am having a hard time understanding what I am doing wrong when attempting to import a class to another file, Python_3.6 is the version I am using. I want to mention; I am using the Django Framework to make a web scraping application. Here is the first class: Class_1 Here is the second class: Class_2 Here is the file structure of my application:File Struct When running the command the expected process is a successful web crawl. But instead I receive a error here is the stack trace. I've tried different steps such as using from . import Article -
Trying To Sort A List Of Dicts After Combining Django Query
I have a django view that I need to query from different models and combine them, and then organize by date, right now when combining the models I get a list of dicts like below. How can I sort this by date. [{'content': u'Just another another message', 'created_at': datetime.datetime(2018, 4, 22, 15, 35, 11, 577175, tzinfo=<UTC>), u'successmatch_id': 5, u'id': 8, 'reciever': u'UserA'}, {'content': u'testing blah', 'created_at': datetime.datetime(2018, 4, 22, 15, 33, 28, 84469, tzinfo=<UTC>), u'successmatch_id': 5, u'id': 7, 'reciever': u'UserB'}, {'content': u'Hi how are you', 'created_at': datetime.datetime(2018, 4, 22, 13, 29, 49, 516701, tzinfo=<UTC>), u'successmatch_id': 5, u'id': 6, 'reciever': u'UserA'}] -
Limit choices in ModelForm
Dont understand how to limit choices of field for user's groupe (standard user groupe in django admin) DOCUMENT_STATUS_OF_GROUPE = [ACTUAL, IRRELEVANT, REWORK, CHECKING] class UpdateDocumentForm(forms.ModelForm): class Meta: model = Document fields = ('name', 'status') def __init__(self, *args, **kwargs): groupe = kwargs.pop('groups') super(UpdateDocumentForm, self).__init__(*args, **kwargs) if groupe == 'Controler': self.fields['status'].choices = DOCUMENT_STATUS_OF_GROUPE This code dont limited choices - in form shows all choices of field -
Get JSON keys using Django ORM
I have a MYSQL table that consists of one attribute/field, myjson and it looks like, +----------------------------------+ | myjson | +----------------------------------+ | {"key1":22} | | {"key2":34} | | {"key2":304} | | {} | | {"key3":304} | | {"key4":164} | +----------------------------------+ How can I retrive the keys using Django ORM ? (in Python it's my_dict.keys()) Expected Output mysql version +----------------------------------+ | myjson_keys | +----------------------------------+ | key1 | | key2 | | key3 | | key4 | +----------------------------------+ NOTE: I'm using Djano 1.9.13 and MySQL Community Server 5.7.21 -
pip error on django-ftp-deploy
sudo apt-get install django-ftp-deploy has this error: requests 2.18.4 has requirement certifi>=2017.4.17, but you'll have certifi 0.0.8 which is incompatible I tried to sudo pip install --upgrade requests but this again has an error message: django-ftp-deploy 2.0.0 has requirement certifi==0.0.8, but you'll have certifi 2018.4.16 which is incompatible. When I try to upgrade the django package sudo apt-get install --upgrade django-ftp-deploy it once again has an requirement conflict. How can I solve this conflict? -
Cannot resolve keyword 'slug' into field. Choices are: body, comments, date, id, title
HI I have a problem with writing a comment on a post pls help me. Here is my urls from django.conf.urls import url from django.views.generic import ListView, DetailView from forum.models import Post from . import views from .views import createPost urlpatterns = [ url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="forum/forum.html")), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='forum/post.html')), url(r'^createPost/', createPost.as_view(), name='createPost'), url(r'^(?P<slug>[-\w]+)/comment/$', views.add_comment, name='add_comment') ] And here is my views from django.shortcuts import render, redirect from .forms import PostForm from django.views.generic import TemplateView from .forms import CommentForm from django.shortcuts import get_object_or_404 from .models import Post class createPost(TemplateView): template_name = 'forum/createPost.html' def get(self, request): form = PostForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = PostForm(request.POST) if(form.is_valid()): form.save() return redirect('/forum') def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) if(request.method == "Post"): form = CommentForm(request.Post) if(form.is_valid()): comment = form.save(commit=False) comment.post = post comment.save() return redirect('/forum/createPost', slug=post.slug) else: form = CommentForm() template = 'forum/addComment.html' context = {'form': form} return render(request, template, context) And lastly here is my models from django.db import models class Post(models.Model): title = models.CharField(max_length=140) body = models.CharField(max_length=500) date = models.DateTimeField() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=None) com_title = models.CharField(max_length=140) com_body = models.CharField(max_length=500) def __str__(self): return self.com_title I think the problem have to do … -
Returning a Django file with posted data written on it - Django Rest Framework
I want to return a PDF file whenever an user passes on some data using POST method and that PDF file should have the POSTed data written on it, I have managed to develop an api that accepts the data passed on by the user and writes the data to a PDF file but I have no idea how to return the PDF file to the user. -
Cannot resolve symbol Static
{% load staticfiles %} This is the code and I am getting error in loading static file ie in this part href="{%static 'search/style.css' %} -
Create function in database using django ORM
In my project I want to get people who have birthday between some days, I hope to find a solution which does not force any limitations to queries. I have found this solution which seems efficient and suite for my problem. But now I have a second problem to create the function in database using django ORM, because this must be portable and works with test database also. I could not find any proper way to able to define the function and the index based on it in django. In brief I want to create below function in database using django: CREATE OR REPLACE FUNCTION indexable_month_day(date) RETURNS TEXT as $BODY$ SELECT to_char($1, 'MM-DD'); $BODY$ language 'sql' IMMUTABLE STRICT; CREATE INDEX person_birthday_idx ON people (indexable_month_day(dob)); -
django doesn't see the postgis database on heroku
I deployed my geodjango website on Heroku, and it works, except: The website does not show any of the data in the database. Migrating to Heroku goes well: Running python manage.py migrate on ⬢ countrycompare... up, run.5217 (Free) Operations to perform: Apply all migrations: admin, auth, compare, contenttypes, flatpages, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying compare.0001_initial... OK Applying compare.0002_remove_worldborder_geom... OK Applying compare.0003_auto_20180422_1605... OK Applying sites.0001_initial... OK Applying flatpages.0001_initial... OK Applying sessions.0001_initial... OK Applying sites.0002_alter_domain_unique... OK And when I look into the postgis database the data is all there: heroku pg:psql --> Connecting to postgresql-clean-31400 psql (9.6.6, server 10.3 (Ubuntu 10.3-1.pgdg16.04+1)) WARNING: psql major version 9.6, server major version 10. Some psql features might not work. SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. countrycompare::DATABASE=> \dt List of relations Schema | Name | Type | Owner --------+----------------------------+-------+---------------- public | auth_group | table | wfmqwxgtkefsjo public | auth_group_permissions | table | wfmqwxgtkefsjo public | auth_permission | table | wfmqwxgtkefsjo public | … -
DJANGO get access token
When I'm running the first-time log in API using username and password will get the client id and secret. using o/token api I will get the access token, o/token params are as follows: grant_type=password username={{emailid}} password={{password}} client_id={{client id}} client_secret={{client secret}} Is it possible to get the access token without using username and password in o/token/ api? using the only client_id and client secret can I get access token and refresh token??? -
Adding error class to outer div django widget-tweaks
I am currently working on forms with django-widget-tweaks, I want to add error class to div not in input, here is my code <div class="form-group"> <label class="control-label" for="id_title">Title</label> {% render_field form.title|add_class:"form-control"%} </div> if getting error it should be <div class="form-group has-error"> <label class="control-label" for="id_title">Title</label> <input type="text" name="title" value="akjdla" id="id_title" class="form- control" required="" placeholder="Title" title="" maxlength="120"> <div class="help-block">This field is required.</div> </div> In documentation I found only adding the class in input, how can I add error class to outer div and show error down to it? -
Using related_name to call objects attributes in django templates
I have 3 models. User, Post and Proof. Posts are added by a User to the website. When other users do what the post says. They upload 2 images to say they did the task. The template will show the 2 images they uploaded. I know I am making some mistake in the template calling the images. Does anyone know the correct way to use related_name to call for the images. FYI I am new to python and Django I am sorry if this question is too trivial or has wrong logic models/posts.py User = get_user_model() class Proof(models.Model): user = models.ForeignKey(User, related_name='proofmade') post = models.ForeignKey(Post, related_name='proofmade') made_at = models.DateTimeField(auto_now=True) image_of_task= models.ImageField() proof_you_made_it = models.ImageField() suggestions = models.TextField(max_length=1000) def __str__(self): return self.post.title Templates {% for user in post.made.all %} <div class="container"> <img src="{{ user.proofmade.image_of_task.url }}" height="150px"/> <img src="{{ user.proofmade.proof_you_made_it.url }}" height="150px"/> </div> {% endfor %} -
Makemigration Keeps generating new migrations files without any changes
I am running django 1.11.11 , python3.5 I have two models in my first_app: class Component(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) code = models.CharField(max_length=15) title = models.CharField(max_length=255) slug = models.SlugField() institution = models.CharField(max_length=255) sub_components = models.ManyToManyField('SubComponent',blank=True) @property def program(self): return self.program_set.all().first() class SubComponent(models.Model): CURRENCIES = [("US","USD"),("EU","Euro"),("CAN","$ CAN"),] code = models.CharField(max_length=15) title = models.CharField(max_length=255) slug = models.SlugField() fee = models.FloatField() currency = models.CharField(choices=CURRENCIES,max_length=3,default="US") @property def component(self): return self.component_set.all().first() Those 2 models are my issue. The same app has the following models as well: Program(models.Model): components = models.ManyToManyField(Component,blank=True) Procurement(models.Model): sub_component = models.ForeignKey(SubComponent,blank=True,null=True) An other app called second_app: It has ForeignKey/ManyToManyField to those models above. Evertytime I run makemigrations, it generates new migrations files, even though I didn't make any change to those two models Component and SubComponent. Profile(models.Model): programs = models.ManyToManyField('first_app.Program',blank=True) components = models.ManyToManyField('first_app.Component',blank=True) sub_components = models.ManyToManyField('first_app.SubComponent',blank=True) I run, python manage.py makemigrations Migrations for 'second_app': second_add/migrations/0025_auto_20180422_0856.py - Alter field components on profile - Alter field sub_components on profile Migrations for 'first_app': first_app/migrations/0032_auto_20180422_0856.py - Alter field sub_components on component - Alter field sub_component on procurement - Alter field components on program The question is, how to fix this behavior? It becomes embarrassing to see each time I genereate files that contain the … -
DJANGO displaying default api's on drf docs
I want to display http://127.0.0.1/o/token/ api on DRF docs. How to do this??? -
How to make a real time notification from local server with Django Rest API to android application
I'm developing an android application using Android Studio and the server side for this application using Django and Djangorestframework. Inside the application, there's one fragment that will retrieve some data (for example, in this case, we call it "smart bin data") and it will show as listview (in a fragment), but with some conditions: Each of smart bin data has a field (let's say a flag). The default flag is 0. When this flag changed to 1, I want there's a real-time notification show up in the application and when the notification is clicked, it will open the listview as I mentioned above (that show the specific smart bin data). Listview is used because the smart bin data is more than one, each belongs to specific users. For example, if the flag of user 1 and user 2 changed at the same time, there will be 2 notification and 2 row/lists will be presented in the listview for each user. In the listview, you can delete each of the smart bin data via a button. When the button is clicked, it will delete the row/list of the data and send an order to change the flag of the data back … -
Django append objects if count less
I'm using Django 2.0 I'm writing a quiz application and I have to build 4 options for each question. options = ChapterQuestion.objects.filter( chapter__course=course_learn.course ).exclude( pk=question.pk ).order_by('?').all()[:3] This will query for other questions excluding current question to ask. But sometimes it might return less than 4 options in case total questions in the database is is less than 4. In that case I want to repeat same set of options to build 4 options. How can I repeat the same objects to build 4 options?