Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Switch django cache backend according to URL
How to use django per-view cache which for the same view uses memcached for some URLs and filesystem cache for others ? -
Read password, django model
I know that django saves passwords like a single-way hash, but for reasons of my app I need to encode an object and I want to use the user's same password, but when I want to use that object I have to decrypt using the same password but the value that returns is hash and it couldn't be possible -
Filtering Django data by dictionary and regular expression?
I was trying to combine filtering Django data through a combination of dictionary and regular expression. So my dictionary looks like this: dict = {'city': '.*?Philadelph.*?$'} And I want to filter the data such that all the rows I retrieve have its city index contains the string "Philadelph". table.objects.all().filter(**dict) However, this does not give me the rows I desire; in fact, it gives me no row at all while all the rows with index "city" have values "Philadephia". I'd appreciate any insights into what might have gone wrong here and how I can begin fixing it. Thank you! -
django edit profile in views if filefield is empty
i am tryng to ignore filefield if its empty but dont works and everytime clears img path in database how can i fix? @login_required def EditProfile(request): user = request.user.id profile = Profile.objects.get(user__id=user) BASE_WIDTH = 400 if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES) if form.is_valid(): if not profile.picture: pass else: profile.picture = form.cleaned_data.get('picture') profile.name = form.cleaned_data.get('name') profile.profile_info = form.cleaned_data.get('profile_info') profile.save() return redirect('index') else: form = EditProfileForm() context = { 'form':form, } return render(request, 'edit_profile.html', context) -
Django-Baton Configuration
I am trying to install and configure the Django-baton to my django project, I followed the steps in the official documentation : Here is my Installed_apps in settings.py : INSTALLED_APPS = [ 'baton', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'crispy_forms', 'baton.autodiscover', ] and at the end of the file BATON = { 'SITE_HEADER': 'Coficab Administration', 'SITE_TITLE': 'Coficab Admin', 'INDEX_TITLE': 'Site administration', 'CONFIRM_UNSAVED_CHANGES': True, 'SHOW_MULTIPART_UPLOADING': True, 'ENABLE_IMAGES_PREVIEW': True, 'CHANGELIST_FILTERS_IN_MODAL': True, 'CHANGELIST_FILTERS_ALWAYS_OPEN': False, 'CHANGELIST_FILTERS_FORM': True, } Also changed my admin url in the urls.py but the display is showing as follows : -
Is "sessions" empty by default in Django? And if, how is the automated login managed?
I'm trying to view all the (keys,values) pair of the sessions-attribute, since I'm writing our cookie-policy thus I need to know exactly what Django sets as default. I have the following view: def MySessions(request): keys =[] values = [] for key, value in request.session.items(): values.append(value) keys.append(key) context = {"keys":keys,"values":values} return render(request,"my_app/my_sessions.html",context = context) and the template {% extends "my_app/base.html" %} {% block content %} {% load static %} <p> {{keys}} </p> <p> {{values}} </p> {% endblock %} In at my page I just have (please let me know, if there's a more easy way to accomplish this) [] [] Unless I have made a mistake, is "session" then empty by default e.g no session is set by Django by default? And if it is, how does Django then log me in automatically? -
Django: problem of displaying uploaded images
I'm building a photo blog via Django, it has a very basic structure: 1)a list page: each post has a cover picture 2)severals detail pages correspondant: each page contains multiple pictures. At the list page, things are all good, the cover picture displayed correctely, but for the detail web page, the pictures that I uploaded from django admin won't show up, though they can be found in the local folder \media. I checked the page in Chrome, I got this: <img src(unknown) alt>. I'm confused. Thanks a lot for your time and help. structure : lyv_dev #project name --settings.py --urls.py media --upload1.jpg --upload2.jpg --upload3.jpg -- ... project #app name -- templates --projects -- base.html -- list.html -- detail.html -- urls.py -- admin.py -- views.py static -- css -- style.css db.sqlite3 manage.py models.py from django.db import models from django.urls import reverse # models project class Project(models.Model): title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, unique_for_date = 'publish') text = models.TextField() year = models.IntegerField(default = 2020) # couv: this is a cover picture couv = models.FileField(blank=True) height = models.IntegerField(default=0) weidth = models.IntegerField(default=0) class Meta: ordering = ('-publish', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('projects:project_detail', args=[self.slug]) # Images related … -
Get 403 (Forbidden) React + Django
when I try to delete or edit a task(todo), I get DELETE http://127.0.0.1:8000/api/tasks/4/ 403 (Forbidden). Maybe the problem in CORS. I have 'corsheaders' in INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('pk', 'title', 'created_at', 'is_done') settings.py CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:8000", ] App.js function removeTodo(id){ axios.delete(`http://127.0.0.1:8000/api/tasks/${id}`) } -
How can I count the characters from a textarea?
I am trying to implement a character counter to my `textarea` tag, but something definitely isn't working. I tried several approaches, but unsuccessfully. I know there are lots of implementation on web, but I couldn't find something that is working to my code. I am quite beginner in this field, and I simply can't get how this works. Code: ............... <div id='id_text' class="control-group"> <label for="id_text" class="control-label"> Text </label> <div class="controls"> <label for="field"></label> <textarea id="field" onkeydown="countChar(this)" maxlength="800"></textarea> </div> <span>Char Left:</span> <span id="charNum"> </span> </div> .................................... script: <script src="http://code.jquery.com/jquery-1.5.js"></script> <script> function countChar(val) { var len = val.value.length; $('#charNum').text(800 - len); } </script> NOTE: The script is positioned on the bottom of the HTML page (I tried to place it on top, but in vain). The script is simple: I just want to take the number of characters from the textarea and then to display the remaining characters to the user. I looked for other answers here, I looked for answers on other websites, but I think there is a problem with my code and I don't get it. NOTE2: The textarea is part of a <form>. And I am using django framework. Thank you so much for your help and attention! -
Highcharts failing to get parsed with json into django templates
Hello im trying to embed highcharts into my django code but with no success. i tried the usual hardcoding of the data into the templates and it worked. Then i tried parsing the data from the django views and it failed to work. Next was using json to parse the data and that one as well doesnt work yet everywhere its taken to be the best option Below is my views.py file def totals_mapper(request): template_name = "stats/totals_barchart.html" cats = ["A", "B", "C", "D", "E", "F", "G", "H"] the_totals = [12, 45, 88, 70, 43, 31, 19, 99] context = {"cats": cats, "the_totals": the_totals} # THE JSON EXAMPLE CHARTS dataset = ['cats', 'the_totals'] return render(request, template_name, {"dataset": dataset}) Below is the html file... <div id="container" class="container-fluid"></div> <script language="javascript"> Highcharts.chart('container', { chart: { type: 'bar' }, title: { text: 'Variation of regions and different total submissions from there' }, xAxis: { categories: [ {% for entry in dataset %}'{{entry.cats}}'{% if not forloop.last %},{%endif %} {%endfor %} ], title: { text: 'Regions in the country', } }, yAxis: { min: 0, title: { text: 'Number of total submissions', }, labels: { overflow: 'justify' } }, tooltip: { valueSuffix: ' millions' }, plotOptions: { … -
Uploading Image to Azure Blob converting Octet Stream to Jpeg in Django
I am trying to upload an images and files using a FORM in React which is passing the data to my Django APIthe data is being stored perfectly on my local machine. The issue I am facing is in uploading this data to the Azure Blob storage as when I send the data it shows up as octet-stream and not as an image. Here is the react code import React, { Component } from "react"; import axios from "axios"; class App extends Component { state = { file_name: "", upload: null, }; handleChange = (e) => { this.setState({ [e.target.id]: e.target.value, }); }; handleFileChange = (e) => { this.setState({ upload: e.target.files[0], }); }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); form_data.append("upload", this.state.upload, this.state.upload.name); form_data.append("name", this.state.file_name); let url = "http://localhost:8000/api/files/"; axios .post(url, form_data, { headers: { "content-type": "multipart/form-data", }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); }; render() { return ( <div className="App"> <form onSubmit={this.handleSubmit}> <p> <input type="text" placeholder="FileName" id="file_name" value={this.state.name} onChange={this.handleChange} required /> </p> <p> <input type="file" id="upload" accept="image/png, image/jpeg" onChange={this.handleFileChange} required /> </p> <input type="submit" /> </form> </div> ); } } export default App; views.py class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, … -
How to redirect to a template page in Django after a Celery task ran successfully?
I am making an application where a celery task processes a video and needs to redirect to a page after processing is completed. How can I redirect to a processed page after the video processing is completed by the celery worker? -
Accessing individual field error message in Django
Consider this in my views.py: if not form_data.is_valid(): messages.error(request, form_data.errors) Now, in my template, I do the following: {% for message in messages %} <div class="alert alert-warning" role="alert"> {{ message.message }} </div> {% endfor %} I end up getting all the form error message into one list: Is there a way I can just display the error messages and not the field names? I.e. can I replace or just get rid of password2 and email in the above error message? I have read the documentation, but to no avail- I just want to get the error message and not the corresponding field. I also tried writing a filter, but didn't succeed there either (I couldn't handle the ErrorDict field and values that messages is). Edit: I just realized that I can easily hide the field names with CSS. But it would still be nice if I can do that without relying on CSS. -
How to use pagination in SerializerMethodField
I would like to return the data of pagination in get_vidoes. I could not find a way to return the pagination data in the serializer. The following serializer returns only the number of data for the first page, and Should I use the following serializer to return only the number of data for the first page, and after that, access the pagination endpoint to receive the data for the After that, should I access the pagination endpoint and receive the pagination data? class TagDetailSerializer(serializers.ModelSerializer): videos = serializers.SerializerMethodField() class Meta: model = MyCustomTag fields = ('pk', 'name', 'videos') def get_videos(self, obj): queryset = Video.objects.filter(tags=obj).order_by('-created_at') if queryset.exists(): videos = VideoSerializer( queryset, context=self.context, many=True ).data return videos else: return None -
Inserting data into a Django ManyToMany field with intermediate table
I have an issue that I am unable to solve. Here is the scenario: there is a retail business which sells cigarettes. This business can have many sites, but each site does not necessarily sell the same types of cigarettes. For this reason, each store owner can browse to a web portal and select the cigarette types that their site sells – these selections will act as columns for a future table. The trouble I am having is writing the data to a database because it is a ManyToMany field. From the data entry perspective, everything appears to be working. The user is able to select what they need and, as a test, I have a HttpResponse message that returns the correct value to the POST method of the view. The problem that I’m running into is that I don’t know how to save this data in a table because the underlying table is part of a many-to-many relationship. When I try to save the data coming from the form, I get an error: " Cannot assign "'6565'": "CigCountColumnsMappings.site_id" must be a "Sites" instance." I have tried many things and I just can’t seem to get this to insert. My … -
Why does a redirected POST request is transformed to a GET and how can we keep it as a POST? [duplicate]
I have a function to login in Django and it works well: def loginuser(request): if request.method == 'GET': return render(request, 'todo/loginuser.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request, 'todo/loginuser.html', {'form': AuthenticationForm(), 'error': 'username and password did not match'}) else: print("request.method: ", request.method) print("user: ", user) login(request, user) return redirect('recommend') And it returns: request.method: POST user: antoi [16/Apr/2021 16:48:14] "POST /login/ HTTP/1.1" 302 0 So it redirects to the function linked to recommend in urls.py: path('recommend/', views.recommend, name='recommend'), However when I go to the function recommend it is now a GET request, so I can't provide the data I want to the html page I want to render: @login_required() def recommend(request): print("request.method: ", request.method) if request.method=='POST': print("in POST") recommendations= None return render(request, 'todo/table.html', {'liked': None, 'recommendations': None}) Indeed it returns: request.method: GET Internal Server Error: /recommend/ Traceback (most recent call last): File "C:\Users\antoi\Documents\Programming\Projects\todowoo\tod_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\antoi\Documents\Programming\Projects\todowoo\tod_env\lib\site-packages\django\core\handlers\base.py", line 188, in _get_response self.check_response(response, callback) File "C:\Users\antoi\Documents\Programming\Projects\todowoo\tod_env\lib\site-packages\django\core\handlers\base.py", line 309, in check_response raise ValueError( ValueError: The view todo.views.recommend didn't return an HttpResponse object. It returned None instead. [16/Apr/2021 16:48:14] "GET /recommend/ HTTP/1.1" 500 64508 -
How to show scraped updated data on a table on website page?
I typed this code to scrape an updated data (numbers). I have no idea how to show them on a table on a website. I know I should use (Django or flask) but I don't know how to use them both :). I just wanna show these updated numbers on a table. I am using HTML and python on Vs Code. here is my scraping code: import requests from bs4 import BeautifulSoup getpage= requests.get('https://www.worldometers.info/coronavirus/country/austria/') getpage_soup= BeautifulSoup(getpage.text, 'html.parser') Get_Total_Deaths_Recoverd_Cases= getpage_soup.findAll('div', {'class':'maincounter-number'}) for para in Get_Total_Deaths_Recoverd_Cases: print (para.text) and here is the updated (day by day ) data result: 589,299 9,843 550,470 thanks :) -
Can display an image in HTML but not in Django? Setting Static Files to be a Windows Directory?
I'm a beginner in Django, and still trying to understand how static files work. We have a shared folder with images in it. In Pure HTML, I can get the image to display like this <img src="file://///Server/Folder1/Folder2/Folder3/img.png"> But it doesn't load at all in Django. Although I know how to display images from the static folders, but not sure how to set it to be the shared folder we have. in settings.py, I tried this: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '/static/', PureWindowsPath('\\Server\Folder1\Folder2\')) would this mean my html code would be <img src="{% static 'Folder3\img.png' %}"> This also didn't work, is there anything else I can try? -
Getting keyerror for key present in python dictionary
I created a dict by filtering a model like this: article_map = {article.name: article for article in Article.objects.all()} It gives a dict as expected, something like this: >>> article_map {'Article name': <Article: Article name>, ....} But when I try following command, it returns key error: >>> article_map['Article name'] KeyError: 'Article name' >>> 'Article name' in article_map False I verified that both data types are same. But still I am unable to find the issue. Extra test: I also checked by using Ctrl + F and searching 'Article name', and both are included in the search results. P.S. There are around 200+ items in article_map dict, but this key error is only for 8 items. I can't skip these items that are not found, so how can I retrieve them from dict? -
Why am I getting ModuleNotFoundError after installing Negbio?
Building a docker image, I've installed Negbio in my Dockerfile using: RUN git clone https://github.com/ncbi-nlp/NegBio.git xyz && \ python xyz/setup.py install When I try to run my Django application at localhost:1227 I get: No module named 'negbio' ModuleNotFoundError exception When I run pip list I can see negbio. What am I missing? -
creating an if statement to look for specific button press
first time poster! I'm still fairly new to coding and Django... I'm looking to create a django if statement to see if a certain button is pressed. I have a toast set up to show an error warning if a search returns no results, but it also pops up if the user clears the search. Here's the button(s) <div class="input-group-append"> <button class="form-control rounded-circle btn form-button ml-2" type="submit"> <span> <i class="fas fa-search"></i> </span> </button> <button class="form-control rounded-circle btn form-button ml-2 closebutton" type="clear" name="clear"> <span> <i class="fas fa-times"></i> </span> </button> </div> I'd like it to spot if the button with the name/type "clear" is clicked, then it won't run the toast. Toast is below: {% if button == 'clear' %} <div class="toast custom-toast rounded-0 border-top-0" data-autohide="false"> <div class="arrow-up arrow-danger"></div> <div class="w-100 toast-capper bg-danger"></div> <div class="toast-header bg-white text-dark"> <strong class="mr-auto">Error!</strong> <button type="button" class="ml-2 mb-1 close text-dark" data-dismiss="toast" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="toast-body bg-white"> {{ message }} </div> </div> {% endif %} -
Logic to create Django web app for adding quiz questions
I have an existing web app using django for creating following type of questions MCQs Single answer questions I want to add a new type of question which takes a long text paragraph (like a case study, or a passage for reading comprehension) followed by 5-6 questions that are based on this paragraph. These questions can be MCQs or Single answer questions. I have exiting code for mcqs and saqs ( single answer questions) which implements three models one model for mcqs Second model for saqs Third model for type of question ( saqs are further of following three types - very short answer, short answer and long answer). For implementing this mew question type, I would prefer to use same mcq or saq models. I am not able to figure out what should be a goo and efficient logic. -
Django DB index is present or not
Suppose I have a model and db_index=True, so 1 migration file is created. Due to some reason I have Deleted the index directly in DB with PgAdmin. And also removed the db_index=True from model. Again it will create a migration with operations = [ migrations.RemoveIndex( model_name='Person', name='name_idx', ), So if i run this on my machine(where i have deleted the index) will raise error ValueError("No index named %s on model %s" % (name, self.name)). Is there any way that I can do Delete index only if it is present. -
What is the correct way to implement Internationalization in your software?
I'm doing a project in which have an Api in Django and to consume that Api I use flutter. I want to implement an Internationalization, but I see that for both flutter and Django there are ways to Internationalize, Which one is a good practice? -
Django - gitlab-ci - sqlite3 - django.db.utils.OperationalError: unable to open database file
Gitlab CI/CD results in the following Error: django.db.utils.OperationalError: unable to open database file .gitlab-ci.yml: stages: - test pytest: stage: test image: docker/compose:latest tags: - test services: - docker:dind before_script: - docker-compose build - docker-compose run --rm django python manage.py migrate - docker-compose up -d script: - docker-compose run django python manage.py test Django Engine settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I do not push db.sqlite3 to my gitlab project.