Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add an extra dictionary to ModelViewset response?
using the model class Sim(modesl.Model): iccid = models.CharField(max_length=64) carrier = models.CharField(max_length=50) status = models.CharField(max_length=100) class Meta(object): app_label = "app" verbose_name = "Sim" class JSONAPIMeta: resource_name = "sim" external_field = "id" using the view : class SimView(viewsets.ModelViewSet): queryset = Sim.objects.all() serializer_class = SimSerializer using serializer: class SimSerializer(serializers.ModelSerializer): class Meta: model = Sim fields = "__all__" for /get/ { "links": { "first": "some link", "last": "some link" "next": null, "prev": null }, "data": [ { "type": "sim", "id": "1", "attributes": { "carrier": "Vodaphone", "iccid": "12345678912345678912", "status": "UnManaged", } } ], "meta": { "pagination": { "count": 1, "limit": 20, "offset": 0 } } } Now I want a dictionary "license_info" to be sent in the response which should appear only once in response, so the response may look like: { "links": { "first": "some link", "last": "some link" "next": null, "prev": null }, "data": [ { "type": "sim", "id": "1", "attributes": { "carrier": "Vodaphone", "iccid": "12345678912345678912", "status": "UnManaged", } } #Either add here { "license_info":"some value" } ], "meta": { "pagination": { "count": 1, "limit": 20, "offset": 0 } } #Or Add here "license_info":{ "some key value pairs" } } I tried to make license_info as property but this was getting repeated for … -
Bootstrap - How to center the contents of a navbar with a collapse button?
Currently have this navbar <!--Ignore--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> <a class="navbar-brand text-center" href="{% url 'Home' %}"><img class="center" src="{% static '/images/PawPrint.png'%}" alt="" width=30px></a> </div> </nav> <!--Main navbar--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> <a href="">Home</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% comment %} <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> </ul> </div> {% endcomment %} </div> </nav> Which centers Home the way I want it to But then when I want to properly add my things under the collapse button it shifts to the left despite the justify-content-center on the container <!--Logo "Navbar"--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> <a class="navbar-brand text-center" href="{% url 'Home' %}"><img class="center" src="{% static '/images/PawPrint.png'%}" alt="" width=30px></a> </div> </nav> <!--Main navbar--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> {% comment %} <a href="">Home</a> {% endcomment %} <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> </ul> </div> </div> </nav> How do I properly center the contents of a navbar? -
How to upload an image withouth form.is_valid in django
I need to know is there a specific way to upload an image without form.is_valid in django . Can someone please help me to solve this. Thanks -
Can't use Django website on subdomain with WordPress on main domain, GoDaddy
I have build a booking system using django and I have successfully hosted the website on my subdomain(appointment.xyz.com). Next I build a Website for the same organisation using WordPress and hosted on the main Domain (www.xyz.com). When I again loaded my booking website hosted on sub domain,the website won't load and shows this error: Forbidden You don't have permission to access this resource. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. What am I missing here? The problem started when I install WordPress on my Main domain.All I did was just install WordPress from cPanel. Please help! -
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??