Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Get list of checked elements from a select2 field
I have a select2 multiple select dropdown list and I gave it a name="specialties_kw". The <option> value has the ID of the selected object. In my Django view, I get the data from that dropdown by calling request.POST.get('specialties_kw'). What I get as data is the id of the last selected item, and not all of them. I want to get the list of all the IDs that are checked. Here are my codes: HTML: <div class="form-group"> <label class="form-label">Extra specialties</label> <select multiple="multiple" class="filter-multi" name="specialties_kw"> {% if cdoctor.specialties.all is None %} <option selected="selected" value="0">N/A</option>{% endif %} <option selected="selected" disabled="disabled">{{ cdoctor.primary_specialty }}</option> {% for s in ospecialties %} <option {% if s in cdoctor.specialties.all %} selected="selected" {% endif %} value={{ s.id }}>{{ s.title }}</option> {% endfor %} </select> </div> DJANGO VIEWS: specialties = Specialty.objects.all() ospecialties = Specialty.objects.filter().exclude(title=doctor.primary_specialty.title) ... os = request.POST.get('specialties_kw') print(os) # gives me the ID of the last checked element -
Is it necessary to explicitly indicate the WORKDIR for each command in my Dockerfile?
I have the following file structure: Dockerfile: # syntax=docker/dockerfile:1 FROM python:3.8-slim-buster WORKDIR /home/pos COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY /src /src CMD ["python", "src/manage.py", "runserver"] I expect that the content of the src/ folder will be copied to the same path in the container (home/pos/src/) but only the requirements.txt are copied to that path, the content of the /src folder is being copied to the "root" (/), so I need to change the command to: COPY /src /home/pos/src It is necessary to set the WORKDIR for each command? -
rest api flutter get method works while post doesnt
ihave this error from server response ihave this error from server response this is the models and api u can find full source code here https://github.com/alihassan75/project // To parse this JSON data, do // // final task = taskFromJson(jsonString); import 'dart:collection'; import 'dart:core'; import 'package:flutter/foundation.dart'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; //List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x))); //String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Project { Project({ this.id, required this.project_name, this.created_at, // required this.start_date, //required this.end_date, required this.user, }); int? id; final String? project_name; DateTime? created_at; // final DateTime? start_date; //final DateTime? end_date; int user; factory Project.fromJson(Map<String, dynamic> json) => Project( id: json["id"], project_name: json["project_name"], created_at: DateTime.parse(json["created_at"]), // start_date: DateTime.parse(json["start_date"]), //end_date: DateTime.parse(json["end_date"]), user: json["user"], ); Map<String, dynamic> toJson() => { "id": id, "project_name": project_name, "created_at": created_at?.toIso8601String(), // "start_date": start_date?.toIso8601String(), //"end_date": end_date?.toIso8601String(), "user": user, }; } class ProjectProvider with ChangeNotifier{ ProjectProvider(){ this.fetchProject(); } List<Project> _project = []; List<Project> get project { return [..._project]; } void addProject(Project project) async { final response = await http.post(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api'), headers: {"Content-Type": "application/json"}, body: json.encode(project)); if (response.statusCode == 201) { project.id = json.decode(response.body)['id']; _project.add(project); notifyListeners(); print('sucess'); } else { print(response.body); throw Exception('Failed to add project'); } } void deleteProject(Project project) async { final … -
update data without refreshing the page in django
I have this code in the model of project django. I used @property to calculate the timer and return it. I used it in my templates But it doesn't update unless you refresh the page. how can I update it without refreshing the page. It is possible to do this with ajax, but I don't know how to do it because I haven't learned ajax yet. @property def checking(self): self.timeend = self.timestart + timedelta(hours=self.time) if self.status == "Live": timer = self.timeend - datetime.now(timezone.utc) return timer -
Django Web interface with a upload button
You have received a text file with the company's sales data. We need to create a way for this data to be imported into a database Your task is to create a web interface that accepts file uploads, normalize the data and store it in a relational database. enter image description here -
Django DRF - Entire Other User Profile return in API call
I have a UserSerializer (I used a CustomUser model) class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['id', 'first_name', 'last_name', 'email', 'is_typeA', 'is_typeB'] read_only_fields = ['id', 'email', 'is_typeA', 'is_typeB'] I have a profile model for each user type, and a serializer as well. class TypeASerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TypeAProfile fields = ['user_id','user','course', 'ndex', 'created_at'] read_only_fields = ['id', 'created_at'] class TypeBSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TypeBProfile fields = ['user_id', 'user', 'course', 'rating', 'created_at'] read_only_fields = ['id', 'created_at', 'rating'] I have an endpoint to get the logged in users profile. class MyProfile(APIView): def get(self, request, *args, **kwargs): serializer = get_user_profile(request.user) return Response(serializer.data) def patch(self, request, *args, **kwargs): if request.user.is_typeA: typeauser = TypeAProfile.objects.get(user_id=request.user.id) user_updates = request.data.pop('user') serializer = TypeASerializer(typeauser, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() user_serializer = UserSerializer(typea.user, data=user_updates, partial=True) user_serializer.is_valid(raise_exception=True) user_serializer.save() return Response(serializer.data) elif request.user.is_typea: typebuser = TypeBProfile.objects.get(user_id=request.user.id) user_updates = request.data.pop('user') serializer = TypeBSerializer(typebuser, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() user_serializer = UserSerializer(typebuser.user, data=user_updates, partial=True) user_serializer.is_valid(raise_exception=True) user_serializer.save() return Response(serializer.data) serializer = UserSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) My endpoint is : /profile. This return: { "user_id": 1, "user": { "id": 1, "first_name": "John", "last_name": "Smith", "email": "email@email.com", "is_typeA": false, "is_typeB": true }, "course": "Udemy-123", "index": 2 "created_at": … -
How to execute cron function in linux alpine using docker
I am trying to run my django application using a docker image with a scheduled cron job. My Dockerfile is the following FROM python:3.8-alpine3.10 WORKDIR /OuterDirectory ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PORT=8000 RUN apk update && apk add --update alpine-sdk RUN apk add --no-cache tini openrc busybox-initscripts COPY requirements.txt requirements.txt RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN apk add --update npm COPY . /OuterDirectory/ RUN npm install RUN mkdir cron RUN touch cron/cronlog.log WORKDIR /OuterDirectory/Projectname EXPOSE 8000 CMD python manage.py crontab add && python manage.py runserver 0.0.0.0:8000 In django settings I have properly added it to my INSTALLED_APPS. CRONJOBS = [ ('* * * * *', 'api.cron.testfunc', '>> ../cron/cronlog.log 2>&1'), ] Everything in the docker image builds with no error. I am 99% sure the issue is something to do with alpine linux and how to configure/get cron running on it but I am unable to find any resources. If anyone has any tips, please do help me I've been trying for a while lol -
Opearator calculations insid a django template
Inside a Django template I have such a phrase: <h4>{{ webinar.name or 'Not title' }}</h4> leading to this error: Could not parse the remainder: ' or 'Not title'' from 'webinar.name or 'Not title'' This is because Django does not like to calculate operators inside a template. It seems that django-mathfilters does not have an or operator. I also do not like to use {% if ... %} either. Because this is a MWE. I have faced with other cases that I cannot get around them so easy. -
Ldap error when try to runserver, Django/Python
I can't seem to find much information about my topic online so I figured I'll ask. I'm trying to set up an app on Django and when I try to 'runserver' I get the following error. It runs with no problem when I remove the ldap configurations but when I add it back in I get this error. Anyone have an idea what can be causing this to break? I'm using Ubunut 20.04 on a windows machine. -
Inline styles working but not in style head (working on CS50 project 2)
I am working on CS50 Project 2 and have a webpage that displays active listings. I want to add some changes to the css, but it nothing happens when I add changes to the style in the head, but inline styles work. How do I make it work in the head style? {% extends "auctions/layout.html" %} <head> {% block style %} <style> .text { font-size: 10%; } </style> {% endblock %} </head> {% block body %} <h2>Active Listings</h2> {% for listing in listings %} <img src ="{{ listing.image }}" style = "height: 10%; width: 10%;"> <h4 class = "text" style = "color: aqua;">{{ listing.title }}</h4> <h6>Description: {{ listing.description }}</h6> <h6>Category: {{ listing.category }}</h6> <h6>Price: ${{ listing.bid }}</h6> {% endfor %} {% endblock %} This is the code. The font size doesn't change, but it will change colors because of the inline style. -
Database planning
I am trying to implement a Pharmacy drug database. I thought about it as follows: In the database schema, there will be a Commercial drug table called "Drug", another table for the manufacturing company called "Company" and a third one implementing the Scientific drug name and dose called "Scientific_Drug". The Drug will have a many-to-many relation with the scientific drug. In fact, multiple scientific drug entries can be included in one Commercial drug entry. I am using Python django models.Model to implement this database schema. I wounder how to implement a multiple entries of scientific drug names provided that many commercial drugs can have variable counts of scientific drug entries. Is there a way of doing this in Python django? My primary code is as follows: class Company(models.Model): name = models.CharField(max_length=70, null=False) launch_date = models.DateField('Launch Date') history = models.TextField(max_length=10000) def __str__(self): return self.name class Scientific_Drug(models.Model): name = models.CharField(max_length=70, null=False) dose = models.PositiveIntegerField(null=False) def __str__(self): return self.name class Drug(models.Model): drug_name = models.CharField(max_length=255, blank=False) drug_dose = models.DecimalField("Dose", decimal_places=2) drug_form = models.CharField(max_length=255, blank=False) drug_price = models.DecimalField("Price", decimal_places=2) release_date = models.DateField('Release Date') expiry_date = models.DateField("Expiry Date") ingredient = models.ManyToManyField(Scientific_Drug) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.drug_name Thanks in advance. -
json value in d3.js
I want to load json data from JSONField, I load the file inside js and I got an uncaught and a 404 not found error, it seems it read the value as an object but in the console I can see the data loaded as a json var jjson = {{proyecto.ifc_json|safe}}; console.log(typeof(jjson)) // = object var jsoo = JSON.stringify(jjson); console.log(typeof(jsoo)) // = string var jsonn = JSON.parse(jsoo); console.log(typeof(jsonn))// = object I got an error loading any of those in the d3.json method d3.json(jjson, function(error, flare) { if (error) throw error; root = d3.hierarchy(flare); root.x0 = 0; root.y0 = 0; update(root); }); cant figure whats the problem, thanks -
Get the count of model attribute through ListVIew
How do I get the Count of a specific attribute of an object model using ListView? I know that {{page_obj.paginator.count}} displays the total objects in the template. Is there a way to do the same for a specific attribute of the object? -
multiple times in multiple days
I want to create a model which will have multiple users and every user will have to choose multiple times in one day or multiple times in multiple days with the state of every time (available or not) and auto-update these times weekly -
How to save from html select to sql in django
I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong? sell.html <div class="form-group"> <p>Yerləşdirdiyiniz məhsul "İkinci əl məhsullar" kateqoriyasında görünəcək.</p> <select class="input search-categories" name="up_category"> <option value="0">Kateqoriya seç</option> {% for category in category %} {% if category.active %} {% if category.parent_id %} <option value="{{category.id}}">{{category.name}}</option> {% else %} <option value="{{category.id}}" style="font-weight: bold;">{{category.name}}</option> {% endif %} {% endif %} {% endfor %} </select> </div> views.py def sell(request): category = Category.objects.all() context = {'category': category} if request.POST: product_name = request.POST.get('product_name') up_category = request.POST.get('up_category') keywords = request.POST.get('keywords') descriptions = request.POST.get('descriptions') main_image = request.POST.get('main_image') price = request.POST.get('price') detail = request.POST.get('detail') image1 = request.POST.get('image1') image2 = request.POST.get('image2') image3 = request.POST.get('image3') if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '': messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!') else: newUserProduct = UserProduct(user=request.user, name=product_name, category=up_category, keywords=keywords, descriptions=descriptions, detail=detail, main_image=main_image, image1 = image1, image2 = image2, image3 =image3 ) newUserProduct.save() messages.warning(request, 'Məhsulunuz satışa çıxdı.') return render(request, 'forms/sell.html', context) return render(request, 'forms/sell.html', context) models.py class UserProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=False) name = models.CharField(max_length=100) category … -
Adding Flutterwave in to django template and view
I have created flutterwave developer account, as you can see down here i have setup everything except template and views.py file settings.py file FLUTTERWAVE_SECRET_KEY = 'my-keys' FLUTTERWAVE_PUBLIC_KEY = 'my-keys' i don't know how to write the amount to charge for each user and also don't know what to put inside my template and views.py file. is anybody who wish to help me please? -
django try block best use
I have a view that takes 2 arguments :course_slug and chapter_slug and i want to check if the given course and chapter exist in the database so what's the best way to do that : def Chapter_Detail(request,course_slug,chapter_slug): try: course = Course.objects.get(slug=course_slug) except Course.DoesNotExist: raise Http404("course does not exist") try: chapter = Chapter.objects.get(slug=chapter_slug) except Chapter.DoesNotExist: raise Http404("chapter does not exist") ''' continue view logic ''' context = { 'chapter':chapter, 'course' :course, } return render(request,'courses/chapter-detail.html',context) or: def Chapter_Detail(request,course_slug,chapter_slug): try: course = Course.objects.get(slug=course_slug) chapter = Chapter.objects.get(slug=chapter_slug) ''' continue view logic ''' except Course.DoesNotExist: raise Http404("course does not exist") except Chapter.DoesNotExist: raise Http404("chapter does not exist") context = { 'chapter':chapter, 'course' :course, } return render(request,'courses/chapter-detail.html',context) or: def Chapter_Detail(request,course_slug,chapter_slug): try: course = Course.objects.get(slug=course_slug) chapter = Chapter.objects.get(slug=chapter_slug) except Course.DoesNotExist: raise Http404("course does not exist") except Chapter.DoesNotExist: raise Http404("chapter does not exist") else : ''' continue view logic ''' context = { 'chapter':chapter, 'course' :course, } return render(request,'courses/chapter-detail.html',context) or there is a better way continue view logic means that we are going to work with the course and chapter objects -
django and telegram bot
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext import secrets def start(update: Update, context: CallbackContext) -> None: chat_id = update.effective_chat.id context.bot.send_message(chat_id=chat_id, text=f"Thank you for using our telegram bot! We will send you notifications here!") def main(): updater = Updater('53049746:27b1xn8KRQdCdFERPVw7o') updater.dispatcher.add_handler(CommandHandler('start', start)) # Start the Bot updater.start_polling( ) # timeout=300 # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle() main() This is code for my telegram bot, I run it like python3 bot.py and it works: The question is: I have django project, so I need to run this bot.py in the background what is the best way to do it? (Right now I start my django project as python3 manage.py start server, later will use docker for it) -
Better way to create background task in Django
I want to create an application that call few API at a fix frequency. So I need to create background tasks in my django app and I found two solution : Crontab or Background-task for django. But I wonder if there is a best practice or a recommandation on the best way to handle few background task to call API at least one time per minute. Or is it only a pro/cons and not really a best practice between these two methods ? Maybe is there an other method ? Thanks for your advice ! -
Building Django model form JSON file
I'm new to django and am trying to build a model from a JSON object that I'm receiving from a third party API call. At the moment, I manually created the model with my best guesses for data type as some of the fields come in null. Is there a way to create this model from the data so that there is no human error? models.py import datetime from django.db import models from django.utils import timezone from django.contrib.postgres.fields import ArrayField # Create your models here. class Address(models.Model): city = models.CharField(max_length=200) neighborhood = models.CharField(max_length=200) state = models.CharField(max_length=200) street_address = models.CharField(max_length=200) zipcode = models.CharField(max_length=10) class Phone(models.Model): prefix = models.CharField(blank=True, null=True, max_length=3) area_code = models.CharField(blank=True, null=True, max_length=3) number = models.CharField(blank=True, null=True, max_length=4) class Phone2(models.Model): prefix = models.CharField(blank=True, null=True, max_length=3) area_code = models.CharField(blank=True, null=True, max_length=3) number = models.CharField(blank=True, null=True, max_length=4) class ContactRecipients(models.Model): agent_reason = models.IntegerField(blank=True, null=True) zpro = models.CharField(blank=True, null=True, max_length=200) recent_sales = models.IntegerField(blank=True, null=True) review_count = models.IntegerField(blank=True, null=True) display_name = models.CharField(blank=True, null=True, max_length=200) zuid = models.CharField(blank=True, null=True, max_length=200) rating_average = models.IntegerField(blank=True, null=True) badge_type = models.CharField(blank=True, null=True, max_length=200) phone = models.ForeignKey(Phone, on_delete=models.CASCADE) image_url = models.CharField(blank=True, null=True, max_length=2000) class ListedBy(models.Model): agent_reason = models.IntegerField(blank=True, null=True) pro = models.BooleanField() recent_sales = models.IntegerField(blank=True, null=True) review_count = models.IntegerField(blank=True, null=True) … -
JSONField unexpected token inside javascript
im working with django 3.0.2, and I need to store a json, I installed django-jsonfield, I managed to save json data, but when I load values from this field I get unexpected tokem error, Ive tried parsing inside js the js script, |safe and |escapejs in the field tag, but still I get this error Uncaught SyntaxError: Invalid or unexpected token pointing to the first ' in the loaded json also I tried loading the jsonify tag as the domcumentation on django-jsonfield says, but I got an unrecognized tag error isnt better to store json as textfield and then parsing on javascript?? -
django rest framework serialized add an auto generated field when getting data
i want to automatically generate a field when data comes out of the database. here is an example serializer i have. class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields = '__all__' i want this serialized to have two extra fields that dynamically generate one called username which has a string username of the user obejct and the other shop name that has the name of the shop object her is the model of sale that the serializer uses. class Sale(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING) reciept = models.TextField() date_time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"reciept number {self.pk}" -
Permissions Django how do custom
I develop app in Django and have question about permissons. I have name course -> modules in course If my user click on button i want to show him certain course with all modules. How can i do this ? -
How to add comments under each post in ReactJs + Django
I want to ask; if I render specific content or post to users and they can add reply to this post, in order to allow them to add reply, they must provide the Id for the post when they submit but I have problem to deal with it; Below: first extract slug that will bring content based on user choice, and then assign => let IdPost = data.posts.id to match with comment const { slug } = useParams(); const [data, setData] = useState({ posts: [] }); useEffect(() => { axios.get(slug).then((res) => { setData({ posts: res.data }); console.log('a single post', res.data); // author, content, id, image, published, slug, title }); }, [slug]); let IdPost = data.posts.id and here for type comment and submit it: const createComment = Object.freeze({ body: '', }); const [postComment, updateComment] = useState(createComment); const handlerOnChange = (e) => { updateComment({ ...postComment,[e.target.name]: e.target.value }); }; const handlerOnSubmit = (event) => { event.preventDefault(); let formComment = new FormData(); formComment.append('body', postComment.body); axios.post(`http://localhost:8000/comment/create/`, formComment, { headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json' } }) }; this code to list comments: const [Comments, setComments] = useState([]); useEffect(() => { axios.get("http://localhost:8000/comment/list").then((res) => { const allComments = res.data; setComments(allComments); }); }, [setComments]); const filterComments = … -
how do I adjust the size of a container in the following page? (bootstrap, django)
I'm a beginner in web development and creating a simple website. I'd like to adjust the red container behind the contact form so it's not visible all over the page.. in fact I'd like it to be just a bit bigger then the form so I can use it as a background. Here is the codes that I've been working on. I'd appreciate it for any tips, advice and corrections. thank you. {% extends "pages/base.html" %} {% block header %} <header> <div class="p-4 text-black rounded-3 bg-danger"> <form> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="Email">Email address</label> <input type="email" class="form-control" id="Email" placeholder="name@example.com"> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="FirstName">first name</label> <input type="name" id="FirstName" class="form-control placeholder="first name"> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="Number">Number</label> <input type="number" class="form-control form-control-sm" id="Number" placeholder="01-2345-6789"> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="Select"> Select an inquiry</label> <select class="form-control" id="Select"> <option> 1. Do you like Ullie? </option> <option> 2. Do you hate Ullie? </option> <option> 3. Do you think Ullie is cute? </option> <option> 4. Do you think Ullie is stupid? </option> <option> 5. Ullie is een stupid hond </option> </select> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label …