Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render and bind choiceFile manually in Django
Am new to Django am trying to implement a simple select tag, the values are rendered with no problem but the value is not bound to the form during submission and I keep getting the message that the value is required Form class UploadFileForm(forms.Form): job_type = forms.ChoiceField(widget=forms.Select, choices=JOB_TYPES) HTML <div class="form-group"> <select class="browser-default custom-select"> {% for type in form.job_type %} {{ type }} {% endfor %} </select> </div> VIEW def simple_upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) return render(request, 'upload/upload.html', {'form': form}) else: form = UploadFileForm() return render(request, 'upload/upload.html', {'form': form}) I also tried to do {{ form.job_type }} and this one works fine but then I can't use the required css, But I want to freely change css and style in the HTML file without refering to the form field in forms.py -
Fill field with data from DB for validation on django-admin
I'm working with django and it's powerful administrator. It's simple. I have a field that needs to be filled with the contents of database for validation. Example: The field is Name. I want the field to make itself a deployable list with all the names contained in the DB. If the field is Name, the user should see a deployable list with "John", "Edward", "Joshua"... Because those have been stored in the db. -
django-storages giving issues with SuspiciousOperation Error from settings
I am attempting to load static files in my project through django-storages using Digital Ocean S3. I am getting this error when I attempt to load the homepage of the site and I can't seem to figure out what the issue is. SuspiciousOperation at / Attempted access to '/images/logo_white.png' denied. Here is are the settings from settings.py that are important STATIC_LOCATION = 'static' STATIC_URL = 'https://exactestate.sfo2.digitaloceanspaces.com/static/' # the issue is here STATICFILES_STORAGE = 'storage_backends.StaticStorage' Here is the StaticStorage Class, all of the settings are correct when I run collectstatic it just doesn't allow me to load the images in the template. class StaticStorage(S3Boto3Storage, ABC): bucket_name = 'exactestate' location = 'static' default_acl = 'public-read' -
How to annotate a queryset with a new field of information from a related model?
I have a model where a Vehicle fields has more Wheels fields. I am trying to display in a single field the information of the vehicle and of the first wheel in the related Wheels field. I have seen that the F function might be useful but I cannot find the correct configuration for it to work. class VehicleListView(ListView): template_name = 'vehicle.html' queryset = Vehicle.objects.all() queryset = queryset.annotate(wheel1_name = F('Wheels__wheel_name')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context I would like the line queryset = queryset.annotate(wheel1_name = F('Wheels__wheel_name')) to return a list of the first wheel name for each vehicle so I can iterate through it and show it in a table. -
I improve the admin panel with the help of django-admin-tools but I get an error
I want to add dashboard to my admin panel but I get this error. I want to do statistics of visits in the admin panel image INSTALLED_APPS = [ 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.postgres', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
How do i redirect to the same page after an action in django
Hello i have this function add_to_cart once a product is added to cart it should redirect to the same page I have done it to redirect to the product list any suggestion def add_to_cart(request, **kwargs): ------------------------ ------------------------ messages.info(request, "item added to cart") return redirect(reverse('products:product-list')) -
Is there a way to use value from one dictionary to search on another?
Im setting up a Django view where im generating some card based on how many there are on a given dictionary. Each of those cards will contain different information depending on who they are, that info is static and stored locally. The way i have the main dictionary setup allows me to loops thru all the cards but i cant figure out how to then get the card's individual data. Maybe foolishly tried to use a value from a dictionary to traverse another one. possibly my dictionary structure is my blocker but i cant come up with any other way. views.py location --> URL variable cards --> data pulled from database vlans --> data pulled from local json file def home_view(request, location): cards = Site.objects.get(sites=location.upper()).site_cards.all().values('cards') cards_dict = {c: c for c in [d['cards'] for d in list(cards)]} vlans = json.load(open('allvendors/static/json/vlans.json')) selected_site_vlans = vlans[location] home = { "site": location, "cards": cards_dict, "vlans": selected_site_vlans } return render(request, 'allvendors/home.html', {"home": home}) home.html home.vlans.card.vlan --> Foolish attempt at using key from one dict on another. See data structure being passed to the template below. {% for card in home.cards %} <div class="card mb-4 box-shadow shadow"> <div class="card-header"> <h4 id="whatfor" class="my-0 font-weight-normal">{{ card|title }}</h4> </div> … -
How to use Python dictionary data with Morris to make a line graph?
I am trying to make a line graph displaying the number of people checked in every day for a fiscal year. When I create the graph with dummy data, it works. But I am having trouble getting the graph to work when I use the actual data. I am trying to use data from the Counts dictionary as it holds the dates and corresponding counts of who checked in. I've tried using a for statement to grab an item in counts but the graph ends up blank. I've also tried a for statement to grab each day in count.dates to iterate over the different days and grab the data for that particular day but that also resulted in a blank graph. index_graph.html {% extends "admin/base_site.html" %} {% load static %} {% load i18n %} {% load in_group %} {% block extrastyle %} <link type='text/css' rel='stylesheet' href="{% static 'index.css' %}"> {% endblock %} {% block content %} <div class="row-fluid"> <div class="span12 text-center" id="pdfRenderer" style="width: 80%; align: left;"> <script src="{% static 'js/raphael-min.js' %}"></script> <script src="{% static 'js/morris-0.4.3.min.js' %}"></script> <link rel="stylesheet" href="{% static 'css/morris-0.4.3.min.css' %}"> <h5>Swipe Data from {{fiscal_start_date}} to {{fiscal_end_date}}</h5> <div id="line-graph"> <script> var count = {{counts}} new Morris.Line({ element: 'line-graph', data: … -
How to get the posts of a user (who is currently logged in) in django?
When a user logged in and went to his/her account they must see there old posts, what they have uploaded in past. If tried if statement in template by comparing current logged in user (request.user) and the users available in database. If, if condition is true than all the posts which are related to that user must be visible in my account page. But this if condition is not working. When i remove this condition it shows all of the posts whether these posts are related or uploaded by the user or not. And when i apply this condition it shows nothing, no error, it shows my navbar only which means rest of the code is fine the problem is with if statement. Template : {% for i in userstweet %} {% if request.user==i.user %} Username : {{i.user}} <br /> {{i.datetime}} <br /> <img src="{{i.image.url}}" width=400 height=400 /> <br /> <br /> {{i.tweet}} {% endif %} {% endfor %} View : def myaccount(request): return render(request,'tweets/myaccount.html',{'userstweet':Tweets.objects.all}) url : path('myaccount',views.myaccount,name='account') i expect the posts uploaded by the current logged in user will be shown on my account page but it gives nothing. -
How to change Django admin panel login-form requirement
I want to set up multiple Admin panels for different groups. Like user from "Management" group can only login into Management-Panel not to administration panel or any other.. -
Why not the page is displayed after migration?
OperationalError at /admin/newapp/effectivenessfield/ no such table: newapp_effectivenessfield On admin page is displayed, but not inside the class models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from completeness.models import Project class ConclusionName(models.Model): user = models.ForeignKey(User) conclusion_name = models.CharField(max_length=250) def __unicode__(self): return self.name class RetrospectiveField(models.Model): user = models.ForeignKey(User) baseText = models.TextField(max_length=255) comments = models.TextField(max_length=255) project = models.ForeignKey(Project) class ValidityField(models.Model): user = models.ForeignKey(User) baseText = models.TextField(max_length=255) comments = models.TextField(max_length=255) project = models.ForeignKey(Project) class EffectivenessField(models.Model): user = models.ForeignKey(User) baseText = models.TextField(max_length=255) comments = models.TextField(max_length=255) project = models.ForeignKey(Project) admin.py from django.contrib import admin from .models import ConclusionName, RetrospectiveField, ValidityField, EffectivenessField admin.site.register(ConclusionName) admin.site.register(RetrospectiveField) admin.site.register(ValidityField) admin.site.register(EffectivenessField) -
When a am trying to use 'git push heroku master' it returns me 'error: src refspec master does not match any'
I am a beginner in web dewelopment and Django. I apologize in advance for my english, but hope you will understand me. I am reading 'Django for beginners: build websites with python and django' and do all just like in the book. I will describe everything that i did. Everything is working in local server and i want to deploy it into production with Heroku. I signed up and went to git cmd and entered to my folder. Order of actions: 1. $ pipenv shell 2. $ pipenv lock 3. $ touch Procfile 4. write 'web: gunicorn pages_project.wsgi --log-file -' in Procfile 5. $ pipenv install gunicorn==19.9.0 6. in settings.py update ALLOWED_HOSTS=[] to ALLOWED_HOSTS['*'] 7. $ heroku create 8. $ heroku git:remote -a NAME #example: heroku git:remote -a morning-brook-95121 $ heroku config:set DISABLE_COLLECTSTATIC=1 To this place all was pretty good. Without errors. But next command is: $ git push heroku master error: src refspec master does not match any error: failed to push some refs to 'https://git.heroku.com/morning-brook-95121.git' I can't explain what i am doing and if it's not enough to you: https://www.pdfdrive.com/django-for-beginners-build-websites-with-python-and-django-updated-for-version-21-e176333886.html Page 57. I very need your help, i can't do anything. Don't forget: the good is returns, today … -
Django - how to define a MySQL CHAR data type in models?
I use MySQL as the db backend in django, I want to define a MySQL CHAR data type. When i use CharField, it will be a VARCHAR data type. c0 = models.CharField(max_length=1) How to define a MySQL CHAR data type in django models. -
Django How to redirect AJAX Loaded form to previous state on unsuccessful submission
I have got a template A.html which contains a link that processes an AJAX request, goes to a view, loads a form in B.html that is returned in AJAX success to a div specified in A.html. Now I have a view that on form submission goes to forms.py and gets that form cleaned and a validation error is raised. Where should I redirect my view if I want the previous state of A.html to be preserved? -
Django Form is rendered continuously
I have created a model from in django.After rendering the form. the output is continuously displayed. how can i make it in proper way.Like after every field is bellow previous field. <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>User Form Page</title> </head> <body> <h1>USER REGISTRATION FORM</h1> <Form action=" " method="post"> {{Templateform}} {% csrf_token %} <input type="submit" name="" value="submit"> <input type="reset" name="" value="Reset"> </Form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> </body> </html> -
Chat functionality in django Helpdesk web application
I'm trying to develope a Helpdesk application with django. It is a basic app that allows users to authenticate and submit support tickets. Everything works fine upto submitting the tickets, but now I want to add the chat functionality where the support staff can reply to user's queries and they can communicate back and forth. I'm relatively new to development and coding, so can't think like a pro, but I'm hoping that some of you experts out there can give me a general idea how to approach this? I've spent so much time to get to this point but now I'm kind of stuck. Any help would be much appreciated. This is my TicketUpdateView where users with staff status can update the tickets. It's not fully functional but I'm just putting it out for you guys to have some idea. File \helpdesk\tickets\views.py class TicketUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Ticket fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): user =self.request.user if user.is_staff: return True return False -
Django split sitemaps and static files
my first question; how can i add static pages in sitemaps for example; sitename.com/blabla I want like this; sitename.com/post-sitemap.xml sitename.com/categorry-sitemap.xml... sitemaps.xml class PostSitemap(Sitemap): def items(self): return Post.objects.published() class CategorySitemap(Sitemap): def items(self): return Category.objects.all() class TagSitemap(Sitemap): def items(self): return Tag.objects.all() -
How to integrate Angular8 with Django 2.2?
I am trying to integrate my Angular8 frontend app with my Django 2.2 backend. I have only run the following command for setting up Django: django-admin startproject project_name Following this I moved my Angular app within the folder created. I followed this tutorial: https://www.techiediaries.com/django-angular-cli/ and set up my settings.py file as shown on the site. Here is my settings.py file. """ Django settings for photorest project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/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/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 't1w0%3@l7!dnx_sm&xho3hdyyg4)$_p(%pz0h*^#a%9m$v2pr$' # 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', ] 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 = 'photorest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
how to make messages showed up in the template
i have a login django app where i am trying to inform user in if they have wrong credentials or if they are successfully login. the problem is that i used the message framework in django but it did not showed up in the template. views.py from django.contrib import messages def login_request(request): if request.method == "POST": username = request.POST['lognName'] password = request.POST['lognCode'] user = authenticate(username = username,password = password) if user is not None: login(request,user) messages.info(request,f"You are now logged in as {username}") return redirect("main") else: messages.error(request,"invalid username or password") return render(request,'login.html') login.html {% if messages %} {% for message in messages %} <script>M.toast({html:"{{message}}",classes:'blue rounded',displaylength:2000});</script> {% endfor %} {% endif %} even if i tried to used outside the if statement the toast doesn't work -
How to get app name in Django within its api file?
Without any hard coding, I want to derive my django app name within its apis. for eg: mysite_apiV1_someapi.py or mysite.apiV1.someapi.py. Here mysite is my app name in the django project. It is not the django project name. apiV1 is the folder, made by me, containing all apis like ApiOne.py,ApiTwo.py, someapi.py and so on. someapi.py is my api file which contains logic and I have to get here my django app name,api folder name and api file name in the above mentioned format. -
Django annotate returns result in memory
I've the following call in Django: Activity.objects.values('user_field__username').annotate(Sum('reward')) Given below is the schema of my "Activity" table: User (foreign key to user model) Reward Each user can have around dozen entries in this table. There can be 10 million users. I want to get the total reward of each user and send notification to all such users at one time. The above query satisfied my requirement but i was told that its suboptimal and would have huge space complexity. What's the right thing to do in principle. -
Why QuesrySet return TypeError
When I makemigration/migate/get from shell - except in my API queryset: models.py class NewsManager(models.Manager): def get_queryset(self): locale = get_language() return super().get_queryset().annotate(title=F('title_' + locale), body=F('body_' + locale), short_description=F('short_description_' + locale), seo_title=F('seo_title_' + locale)) class News (models.Model): class Meta: verbose_name = _('Новини') ordering = ("-created_at",) title_uk = models.CharField(max_length=255, blank=False) title_en = models.CharField(max_length=255, blank=True) seo_title_uk = models.CharField(max_length=255, blank=True) seo_title_en = models.CharField(max_length=255, blank=True) short_description_uk = RichTextField(blank=False) short_description_en = RichTextField(blank=True) body_uk = RichTextField(blank=False) body_en = RichTextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) published = models.BooleanField(default=False) objects = NewsManager() api/views.py class NewsAPIView(generics.ListAPIView): """ list: Return a list of all news """ serializer_class = NewsPreviewSerializer def get_queryset(self): return News.objects.all().exclude(published=False) class NewsDetailAPIView(generics.RetrieveAPIView): """ get: Return one News obj by id """ serializer_class = NewsSerializer queryset = News.objects.all() lookup_field = 'id' TypeError: must be str, not NoneType return super().get_queryset().annotate(title=F('title_' + locale), body=F('body_' + locale), -
Django AES Encryption : how to decrypt files when they are sent to the user?
I want to decrypt files in django when sending them, but keep only the encrypted version on the server. How can I decrypt the files when sending them ? I currently use pyAesCrypt to decrypt files but it replaces the file or create a new one that I have to delete after, and as I think I have to send the response with the file I don t see when I can delete de decrypted version of the file on the server (except deleting it at a later time) This is what I do for a request for the file : import pyAesCrypt from os import stat with open("*FilePath*", "rb") as InputFile: with open("*OutputFilePath*", "wb+") as OutputFile: pyAesCrypt.decryptStream(InputFile, OutputFile, Password, BufferSize, stat(InputFile).st_size) response = HttpResponse(Model.File, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
Django & React: How to censor columns when user is not logged in
I am using Django as my CMS and React for my Frontend. For the API I am using Django REST framework. In Django I have a model like this: class person(models.Model): number = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) I would like to censor some columns depending on if the user sent me the correct Authentification Token or not. So in result I would like to have something like { "number": 1, "name": "johnny", "last_name": "miagi"} when the user is authentificated, and { "number": 1, "name": "johnny", "last_name": "########"} when not. Is this possible? I am, unfortunately, a beginner in Django. I know about the user privileges system, but as far as I know this is meant to be used on complete tables, not columns. -
How to find nearby machines from a given coordinate while all the machine coordinates are in the database?
I am creating a website where a specific machine owner can upload the machine for renting or selling. In the process I am also saving his shop's coordinates in the database. Now if any costumer wants to by the machine, I want to take his coordinates and classify the nearest shops with the machine available. Also please tell me the resources I need to use. Currently I am using Django for backend development.