Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django: how to give multiple categories to an item
i want to have one Post have multiple Categories kind of like Tags here's what i have already models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class Post(models.Model): title = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default="Non Categorized") Thumbnail = models.ImageField(null=True, blank=True, upload_to="images/") Text = RichTextField(blank=False, null=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) Overview = models.CharField(max_length=400) Date = models.DateTimeField(auto_now_add=True) main_story = models.BooleanField(default=False) def __str__(self): return str(self.title) def get_absolute_url(self): # return reverse('about', args=(str(self.id))) return reverse('home') -
Django Courses Lock and Unlock
I am developing E-Learning Site where I have courses..In the courses I have Sections and within specific section I have video Lectures e.g:if I have django-bootcamp course and within this course I have three sections 1.HTML,2.CSS,3.DjangoBackend ..I want when student click on specific section of course I have created Section in card-component where two buttons already added one for watch and other for Skip..I want when user click on skip button or watch button of specific course section videos next section of Course Lock until user attempt quiz or watch every lectures that are in the selected section of course..For example if user click HTML Section and click watch or takeQuiz next CSS Section lock until anyone of these task perform...I have already add courses,Sections and within sections added video lectures also just Lock next section functionality I want until previous or current Course Section Complete watch or Attempt quiz of this Section and I am developing this site in Django Framework..Plzz help me.Thanks -
How to display legend in toolbox in Google Charts?
I created a scatter chart by using Google Charts in my Django project. It is working clearly but in the toolbox, the legends name does not show just number is displaying. How can I display it? I want to display it as: Argentina(44015314.68,28) my code: var bubbleChart = document.getElementById('mybubbleChart').getContext('2d') var myBubbleChart = new Chart(bubbleChart,{ type: 'scatter', data: { datasets:[{ label: name_1, data:[{x:x_1,y:y_1}], backgroundColor:"#716aca" },{ label: name_2, data:[{x:x_2,y:y_2}], backgroundColor:"#d643ad" },{ label: name_3, data:[{x:x_3,y:y_3}], backgroundColor:"#2ec3be" },{ label: name_4, data:[{x:x_4,y:y_4}], backgroundColor:"#2ec34e" }, { label: name_5, data:[{x:x_5,y:y_5}], backgroundColor:"#decb3e" }, ], }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', }, tooltip: { isHtml: false }, elements: { point: { radius: 10, hoverRadius: 15, } }, scales: { yAxes: [{ ticks: { beginAtZero:true }, }], xAxes: [{ ticks: { beginAtZero:true }, }] }, } }); -
Django: utils.py - name 'short_url' is not defined
I'm seeing the error while querying 'short_url' field from UrlModels NameError at /admin/shortner/urlmodels/5/change/ name 'short_url' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/admin/shortner/urlmodels/5/change/ Django Version: 3.1.6 Exception Type: NameError Exception Value: name 'short_url' is not defined utils.py def code_generator(size=6, chars=string.ascii_lowercase + string.digits ): return ''.join(random.choice(chars) for i in range(size)) def create_shortcut(instance, size=6): new_code = code_generator(size=size) urlmodel = instance.__class__ print(instance) print(instance.__class__) query_exists = urlmodel.objects.filter(short_url==new_code).exists() if query_exists: return create_shortcut(size=size) return new_codefrom models.py class UrlModels(models.Model): url = models.CharField(max_length=1000) short_url = models.CharField(max_length=50, unique=True, blank=True) def save(self, *args, **kwargs): if self.short_url is None or self.short_url == '': self.short_url = create_shortcut(self) super().save(*args, **kwargs) def __str__(self): return self.url -
how to only accept requests with users over the age of a certain age in Django rest framework
the title probably seems very confusing but I will explain it. I am trying to make a feature in my Django rest framework project of which when you sign up it calculates your age then if you are old enough your account is made but if you are not it gives an error of you are not old enough. so my 2 questions are: how would you calculate a users age using their date of birth how would you only create account which have users over the age(in my case I would like to make the threshold 13) I have seen another question on stack overflow here. I added the calculation on the top answer to my models.py but It gives an error in self.birthday(which in the answer would be date_of_birth) saying Unexpected field type(s): (DateField) Possible type(s): (timedelta) (date) -
How to debug Django using daphne
I recently switched from gunicorn to daphne for my Django application, and I am finding it impossible to debug now. When using gunicorn, if I made a mistake the Django debug page would appear, and I could find the issue. With Daphne, I am just getting the nginx error page until I can manually track down the error... Is there a way to make this behave like gunicorn and show the django debug page? -
Django: How do I exclude related fields when using `._meta.get_fields()`?
I'm trying to write a view in Django to export my model data in a csv file. The problem is that I can't figure out how to exclude related fields. Currently, when I run model._meta.get_fields(), the function returns the model's fields and the related model's field, so my view throws an error when I use getattr() using the related field's name. I tried using .is_related() to exclude related fields, but that also excludes the model fields (like ForeignKey). When I call the field name, I can see the class name is ManyToOneRel, but I can't figure out how to access that attribute. Does anyone know how to exclude related fields or figure out if a field is a related model's field? My view is below. Thanks to anyone that can help! class CSVExportView(View): template_name = 'medrec_v2/csv_export.html' def get(self, request, *args, **kwargs): model_list = [m for m in apps.app_configs['medrec_v2'].models if '_' not in m ] # print(model_list) context = {'model_list':model_list} return render(request, self.template_name, context) def post(self, request, *args, ): model_name = request.POST.get("model-sel") model = apps.get_model(app_label='medrec_v2',model_name=model_name) content_type = 'text/csv' datecode = datetime.today().strftime('%y%m%d') file_name = f'{datecode}_medrecv2_{model_name}.csv' response = HttpResponse(content_type = content_type) response['Content-Disposition'] = f'attachment; filename="{file_name}"' header = [f.name.split('.')[-1] for f in model._meta.get_fields() if …