Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add customised choice fields in django (2.1)?
This is the model class that stores the details about an app. In this model is it possible to add a customised list fields. i,e a user should be able to define a set of choices and later it will be available for adding (as tags) to the builds of the app. class App(models.Model): bundle_number = models.CharField(max_length=255) hidden = models.BooleanField(default=False) -
Does request.session["name"] in Django creates a new list?
What does it mean when we write request.session["tasks"] and assign it to something in django views? Like in the script below in the index function request.session["tasks"] = [ ],does that mean an empty list named tasks has been created for that particular session? and if so, where exactly all these session details are stored in django? and also what does cleaned_data["task"] in the add function is exactly doing in this script? I tried looking in the documentation but couldn't find any satisfactory information about this, so I'm sorry if this sounds a little stupid but I'm new to django and sometimes the syntax really confuses me,Any help is appreciated! from django.shortcuts import render from django import forms from django.http import HttpResponseRedirect from django.urls import reverse # Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label = "New Task",min_length=8,max_length=16) priority = forms.IntegerField(label="Priority",min_value=1,max_value=5) def index(request): if "tasks" not in request.session: request.session["tasks"] = [] return render(request,"index.html", { "tasks":request.session["tasks"] }) def add(request): if request.method == "POST": vari = NewTaskForm(request.POST) if vari.is_valid(): task = vari.cleaned_data["task"] request.session["tasks"] += [task] return HttpResponseRedirect(reverse("index")) else: return render(request,"other.html", { "form":vari }) return render(request,"other.html",{ "form" : NewTaskForm() }) -
Django Rest Framework: How can I add token expiration to my API when using Django Rest Auth?
I am using "Django Rest Auth" and "Allauth" for the backend I'm creating a mobile application. Currently, the user can register and generate a new token, as well as to login and get that token from the server. The problem I'm seeing is that the token never changes, so it doesn't seem very secure to always keep the same token. I would like to implement some sort of token expiration and refresh every certain amount of time. It seems that some packages like "Django Rest Framework Simple JWT" or "Django Rest Knox" have this functionality but not the one I'm using ("Django Rest Auth") How could I integrate this workflow of token expiration into my application? -
Should my React frontend be part of my Django project?
So I'm using a REST API on Django and I was looking at tutorials and noticing that some people have their react apps as a Django app and others have it as a directory outside of the Django project. Which way do you suppose is better? I would think that if it wasn't part of the Django project, it would be harder to deploy. -
How to fix django IntegrityError?
I meet this error when I try to submit form data from front to my web server.I am confused why this happened. IntegrityError at /qa/propose-answer/7/ (1048, "Column 'created_at' cannot be null") My models.py class Answer(models.Model): uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='a_author', verbose_name='回答者') question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='回答的问题') content = MarkdownxField(verbose_name='内容') is_answer = models.BooleanField(default=False, verbose_name='回答是否被接受') votes = GenericRelation(Vote, verbose_name='投票情况') created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间') class Meta: ordering = ('-is_answer', '-created_at') verbose_name = '回答' verbose_name_plural = verbose_name My views.py class CreateAnswerView(LoginRequiredMixin, CreateView): model = Answer fields = ['content', ] template_name = 'qa/answer_form.html' message = '您的回答已提交' def form_valid(self, form): form.instance.user = self.request.user form.instance.question_id = self.kwargs['question_id'] return super(CreateAnswerView, self).form_valid(form) def get_success_url(self): messages.success(self.request, self.message) reverse_lazy('qa:question_detail', kwargs={'pk': self.kwargs['question_id']}) My template <form action="{% url 'qa:propose_answer' view.kwargs.question_id %}" id="answerForm" method="post" role="form"> {% csrf_token %} {{ form|crispy }} <div class="form-group"> <button id="answer" type="submit" class="btn btn-primary">回答</button> <a class="btn btn-light" style="float:right" href="{% url 'qa:all_q' %}">取消</a> </div> </form> -
How to apply db_constraint=True in django Composite foreignkey
I need to apply db_constraint=True in compositeFk table, because I do not want to enter data in foreign key table(table 2) if primary key(table 1) does not exist. -
Creating Django Model instance from Pandas Dataframe Vectorization
I'm still new to Pandas Dataframe in general and I've been wrestling with this for some time now where I am trying to convert a 14 MB csv into Pandas Dataframe then insert the re-adjusted column values as a new instance of Django model. I successfully managed to do it by iterating each Dataframe row using the iterrow() function on a 1 KB sample data. However, iterrow() would be way too slow to iterate a 40,000 row csv of the original 14 MB data and thus I've looked up on Pandas/NumPy Array Vectorization and how it can shorten the time complexity of a function which will be the topic of my question. The following is the snippet of the csv file to be used #Local Date, Local Time, UTC Timezone, Instance Spotted, Instance's Temperature #yyy-mm-dd, hh:mm:ss, hh:mm, integer, degrees Lcl Date, Lcl Time, Timezone, Count, Temp 2012-10-03, 22:04:36, +00:00, 82, 33 2012-10-03, 22:04:37, +00:00, 31, 34 2012-10-03, 22:04:38, +00:00, 45, 31 2012-10-03, 22:04:39, +00:00, 12, 32 2012-10-03, 22:04:40, +00:00, 63, 32 The following is the Django models in which the Dataframe would be inserted to class Parameter(models.Model): # Model representation of Parameters id = models.AutoField(primary_key=True) name = models.CharField(max_length=70) description = … -
Django How to Use {% if %} with parameterised custom tag?
I have defined a custom template tag which requires a parameter to be passed. This works ok in the template, using {% selected_tender_id user.id %}. However I want to test the value of the response in the template. To do this I try using the command below: {% if selected_tender_id user.id == 0 %}Equals Zero{% else %}Not Zero{% endif %} However I get this error: Unused 'user.id' at end of if expression. The context is that I have a user parameter saved which records the tender (think project) that the user has selected to work on. Whenever the user logs back in, this parameter is picked up and all the records they select will be filtered based on the tender id, etc. I am new to programming so may have overlooked something obvious. Can someone please advise me on two points please: Is there a way to use the {% if %} function with a parameterised custom tag? Is there a simpler way to achieve what I am trying to do? models.py class Tender(models.Model): code = models.CharField(max_length=128,null=True,blank=True ,unique=False,default='999999') description = models.TextField(blank=True) class Meta: ordering = ('code',) verbose_name = "Tender" verbose_name_plural = "Tenders" def __str__(self): return self.code class UserParms(models.Model): parm_user = … -
Come up with a simple django algorithm for booking appointments
I did not do much coding in this because I'm really stuck at actually designing the view that I'm going to work with! The problem is that i want to design a booking system for my new doctor appointment app. The idea is this: a doctor creates his or her schedule by choosing the consultation duration, the start time, and the end time for every day, and the algorithm will generate an agenda with all the booking slots. Each slot will be tied to a specific date and will have a boolean variable of 'booked?'. A user visits the doctor's agenda, and chooses the time slot he or she wants from the calendar. Slots that are booked will be grayed out, or not visible. That's it! I don't know how to approach this but this is the pseudo code I came up with so far: The doctor will create his agenda: 1- Select session duration 2- Select start time 3- Select end time 4- Select days in the week. The Django View Process: Start with the start time, create an array of durations, until the end time eg. start time is 9:00 and end time is 18:00, and the duration … -
Django REST Framework Viewset returns a 404 (GET request)
I'm seeking to understand how the ViewSet compliments URL routing when used with routers in the context of Django REST framework. When I'm requesting a collection at api/v2/people/, a 404 response is returned. I'm not clear on what else is required for the view to render in the browser and get a 200 status code as a part of the response? urls.py from django.urls import path, include from rest_framework import routers from people import views router = routers.SimpleRouter() router.register(r'people', views.PersonViewSet, basename="people") urlpatterns = [ path('admin/', admin.site.urls), path('api-path/', include('rest_framework.urls')), path('api/v2/people/', include(router.urls), name="people") ] people/views.py from rest_framework.viewsets import ViewSet from .models import Person from .serializers import PersonSerializer class PersonViewSet(ViewSet): def list(self, request): queryset = Person.objects.all() serializer = PersonSerializer(queryset, many=True) return Response(serializer.data) -
warning: python 3.6 was not found on your system…
I was installing dependencies of a project from GitHub, using pipenv install but it gave me a warning about the python version, as my current python version is 3.7.4, so I googled and using various available answers was to install pyenv module with which on running pipenv install, it installs required python version but it lead to building failed after the output of installing CPython 3.6 So can u please help me with a better way to deal with this version python version issue with Pipfile. -
getting a file from S3 with boto3, and serving it to a user with nginx
I have a Django project where users can upload documents, and later download them if they want to see them. The files are stored in AWS S3. Locally, uploading and downloading both work, however, on my production server (AWS EC2), users cannot download their files. The only difference is that the production server uses Nginx and Gunicorn to handle requests, so I think the reason that downloading files isn't working on production is because the Http response is misconfigured with nginx. This is the error when you try to download, as you can see, it doesn't really tell anything. below is some sample code as to how I download a file from S3, and return it in the Http Response s3 = boto3.resource('s3') #setup to get from AWS jdp = json.dumps(request.POST) #get request into json form jsn = json.loads(jdp) #get dictionary from json order_id = jsn['order_id'] aws_dir = 'XXXXX'+str(order_id) bucket = s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME) objs = bucket.objects.filter(Prefix=aws_dir) #get folder for obj in objs: path, filename = os.path.split(obj.key) if 'XYZ' in filename: XYZ = obj.get()['Body'].read() mimetype = filename.split(".")[1] response = HttpResponse(XYZ, "application/"+str(mimetype)) response['Content-Disposition'] = 'attachment;filename=XYZ.%s' % mimetype return response Any help is greatly appreciated :) -
ModuleNotFoundError: No module named 'django.templates'
Recently I made a django project and it was working fine. But after I added "Map"app to my project, there was an error like title of my question. So I erased all of the "Map"app and didn't touch anything. But the error still did not go away. I tried to change "templates" from "settings.py" to "template" by referring to other questions, but the error did not go away. Somebody help me.......plz........... "settings.py" """ Django settings for delibrary project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'l(gh10dpuv42dt4twx)xpvu-!d60=!6pm$geh7jc6s*#)o%p%3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'library', 'cart', 'orders', 'accounts', ] 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', ] ROOT_URLCONF = 'delibrary.urls' TEMPLATES = [ { 'BACKEND': 'django.templates.backends.django.DjangoTemplates', 'DIRS': … -
Extending Django PositiveIntegerField to automatically pad string representation?
I'm wondering if there's a best way to extend one of my model's fields to automatically pad the string representation of a PositiveIntegerField class User(AbstractUser): coupon_code = models.PositiveIntegerField(default=0, help_text='Coupon code',) Currently the field (understandably) displays as an integer would. For example, 42 is printed as '42'. However I would like if the field would pad with zeros whenever printed across the site, so 42 displayed would always be displayed as '0000000042', while keeping the underlying Integer representation in the database. Can this be done? -
error while clicking the send button 'post_detail' is not a valid view function or pattern name
while iam adding comment option to my django project i came up with these error here this comment is the comment i gave through the admin page and it get repeating again and again and also when i try to add a new comment as user when i click the send button it shows the following error and the page of form of comment is: and the views.py code is : from .forms import PostForm, CommentForm from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.http import Http404 from django.views import generic from django.contrib.auth.decorators import login_required from .forms import PostForm, CommentForm from .models import Post, Comment from django.shortcuts import render, get_object_or_404, redirect # pip install django-braces from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( … -
What is the best way to format a str range in python? "1-5,10-25,27-30" python
I'm currently working on an api where they send me a str range in this format: "1-5,10-25,27-30" and i need add or remove number conserving the format. if they send me "1-5,10-25,27-30" and I remove "15" the result must be "1-5,10-14,16-25,27-30" and if they send me "1-5,10-25,27-30" and i add "26" the result must be "1-5,10-30" how can i do this? is a library for work with this format? thanks! -
Random image selector with Wagtail and Django
I am trying to get my homepage in Wagtail to show a random image. I followed the Wagtail start guide and tried to incorporate this hack in the template, but I'm getting an error. home/models.py: from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel,InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), InlinePanel('home_images', label='HomePage Images'), ] class HomeImages(Orderable): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='home_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=64) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] home/templates/home/home_page.html: {% extends "base.html" %} {% load static %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}template-homepage{% endblock %} {% block content %} {{ page.body|richtext }} {% with page.thiswillfail|random as item %} <div> {% image item.image max-1000x1000 %} <p>{{ item.caption }}</p> </div> {% endwith %} {% endblock content %} Even after adding some images in the Wagtail admin interface, I get the same error on the homepage: object of type 'DeferringRelatedManager' has no len() I at least narrowed it down to the "with" statement in home_page.html. The wagtail image object is iterable in a for loop as in the … -
how to keep using html files from public folder in vue project in MPA (Multi-Page Application)
I use vue applications in my django templates, using webpack_loader. There are plenty of examples how to do it (this one for instance https://blog.gundammc.com/vue-js-django/), and everything works fine. The puzzling thing is that when I run yarn serve (or npm run serve), the app is shown correctly on corresponding Django pages, but I cannot access the vue apps directly via the link provided by serve command. And it would be nice to have an access to 'pure' vue app page, without having Django server running, because it would be much more convenient to develop vue app first and only later mount it to Django. So, for instance if I do npm run serve, the server is running, and it informs me that: App running at: - Local: http://localhost:8080/ - Network: http://localhost:8080/ But when I try to access the localhost:8080 (or localhost:8080/APP_NAME_PAGE.html), nothing is rendered. Although the app itself is rendered correctly in django template. The vue.config.js is very standard. It looks like this one (borrowed from here https://github.com/gundamMC/vue-django-multipage-example/blob/master/frontend/vue.config.js): const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://127.0.0.1:8080/", outputDir: './dist/', chainWebpack: config => { config.optimization .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('http://0.0.0.0:8080') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) … -
Django Calendars
I am quite new to django and the app that I am building requires me to create a calendar. I am wondering what would be the best approaches for someone with the same level of experience as me. Thanks. -
React+Django Routing
I am using python as my backend and Django as my middleware and React as front end. My index page url is mapped by django in urls.py and renders by index page and I have handled component based routing in front end. I have a hard requirement to have deeep linking in front end so I am moving evrything to react router. I am having issues when i do a refresh as it always goes to server and brings default page always. from django.urls import path, re_path from . import views from django.conf.urls import include, url urlpatterns = [ url(r'^$',views.dashboaerd, name='dashboaerd'), url(r'^(?:.*)/?$', views.dashboaerd, name='dashboaerd'), path('',views.dashboaerd, name='dashboard'), ] Is there any way I can pass URL context from django to react router? -
while clicking the comment button its shown: local variable 'form' referenced before assignment
hi im new to python and while i was adding comment option to my python django project i cam up with a UnboundLocalError my views.py code is from .forms import PostForm, CommentForm from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.http import Http404 from django.views import generic from django.contrib.auth.decorators import login_required from .forms import PostForm, CommentForm from .models import Post, Comment from django.shortcuts import render, get_object_or_404, redirect # pip install django-braces from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields = ('message','group') model = models.Post # def get_form_kwargs(self): # kwargs = super().get_form_kwargs() # kwargs.update({"user": self.request.user}) # return kwargs def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin, SelectRelatedMixin, … -
Django Admin Site File Field depending on other form fields?
I have a django model as following: class Page(Model): title = CharField(max_length=32) app = CharField(max_length=32, choices=APP_OPTIONS, default='pages') permalink = CharField(max_length=32, unique=True) update_date = DateTimeField("Last updated") filename = CharField(max_length=32) def __str__(self): return self.title and @admin.register(Page) class PageAdmin(admin.ModelAdmin): list_display = ('title', 'update_date') ordering = ('title', 'update_date') search_fields = ('title',) I would like to change the filename field to a FileField for the admin view that allows a file upload, the save location of which depends on the app field's input. For example, if the field is "pages", I'd want it to save to the corresponding templates folder and save the file's name for the column entry. -
Redirecting into another page in Django
I am working in a project in Django where someone tries to fill the info of some patients and after hitting the submit button i would like o redirect it into a page with the list of all the existing pages, i am trying using a action tag in the html but it seems not to work, i would like to know what i am doing wrong. html {%extends 'base.html'%} {%load staticfiles%} {%block body_block%} <link rel="stylesheet" href="{%static 'patients/css/patientform.css'%}"> <form action="{% url 'patients'%}" method="POST"> <div class="wrapper"> {%csrf_token%} <div class="Patient"> <h3>Informacion del Paciente</h3> {{patientinfo.as_p}} </div> <div class="Medical"> <h3>Informacion Medica</h3> {{medicalinfo.as_p}} </div> <div class="Insurance"> <h3>Informacion de Seguro</h3> {{insuranceinfo.as_p}} </div> <div class="FirstRelative"> <h3>Antecedentes Familiares</h3> <h5>Primer Caso</h5> {{first_relative.as_p}} <h5>Segundo Caso</h5> {{second_relative.as_p}} </div> </div> <input id="submit" type="submit" value="Agregar"> </form> {%endblock%} Url patterns from django.urls import path from .views import * urlpatterns = [ path('',PatientsList.as_view(),name='patients'), path('addpatient',PatientFormView,name='addpatient'), ] -
Django web app tutorial continuation for user side
So I completed the Django web app tutorial, but I wanted to forget the admin side and do something from the user side. So the user would be able to add questions, add choices, remove questions and remove choices. But I'm stuck on how to remove the question or choices. In my Index.html and detail.html I have added the delete buttons to the questions and choices but am confused on exactly how to interact that button with python to actually remove it from the database. This is the code for the delete button I added at the end of each question. [This is the code for the delete button I added at the end of each choice.2 This is the code for the function of the user to add a question. This is the code for the function of the user to add a choice. To my understanding I should have two other functions: def remove_question() and def remove_choice(), but I'm not exactly sure how I would correlate this function to the delete button to actually delete the question or choice that the user would click on. -
Search , Filter by SlugRelatedField in view
I have a problem with searching , filtering by SlugRelatedFiled which I get it in Serializers.I just want to filter , search by category names of products. Here is my serializer. class CosmeticDetailSerializer(serializers.HyperlinkedModelSerializer): category = serializers.SlugRelatedField( queryset=CosmeticCategory.objects.filter(), slug_field="name", ) class Meta: model = Cosmetic #read_only_fields = ["date_added", "date_updated"] fields = [ "image_url", "url", "pk", "name", "category", "price", "description", "color", "volume", "skin_type", "target_area" ] And view class CosmeticList(generics.ListAPIView): queryset = Cosmetic.objects.all() serializer_class = CosmeticSerializer name = "cosmetic-list" # filter_class = CosmeticFilter filter_bakcends = (SearchFilter,OrderingFilter) filter_fields = ["category","brand","name"]#----- ordering_fields = ["name", "price","volume","brand"] search_fields = ["name","brand","category"]#------ #permission_classes = [IsAdminUserOrReadOnly] Output for search: condition = self.build_lookup(lookups, col, value) File "/Desktop/SoftwareProject/Test2/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1156, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains Output for filtering: raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: iexact I think I have to set icontains or iexact value but I don't know how to do it. I found some related questions how to set these values but they are a little bit different.