Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Base template for Node.js and Express similar to Django
In Django there is a really useful tool i.e, using base template for stuff like navbar which makes it really fast for development and also avoids a lot of redundant code since we can neglect including stuff like navbar each time in different pages of a web-app. Also if there is any change to make in navbar, I need not have to change it everywhere but base template. I want to know if there is a similar functionality for Node.js + Express. -
Ajax sending empty list via POST request Django
I am sending array of user's answers in my test app and i'm getting two arrays (one of them filled in correctly , but another is empty). Also in console i noticed that i'm getting to requests (POST and GET). How should i send the array via ajax POST so that been sended only one time? Sripts.js: $.ajax({ type: "POST", url: 'result', data: { res_list: resultList() }, success: function () { } }) Views.py: def result(request): user_answers_list = request.POST.getlist('res_list[]') context = {'res_lst': user_answers_list } return render(request, 'main/result.html', context) result.html: <div class="alert alert-warning mt-2" id="mainArea"> {% for question in testing %} <div class="alert alert-secondary mt-2" id="questionArea{{ forloop.counter0 }}"> <form method="post" id='testForm' data-url="{% url 'test' %}"> {% csrf_token %} <table> <thead> <tr> <th>{{ forloop.counter }}. {{ question.1 }}</th> </tr> </thead> </table> {% if question.4 %} {% for images in img %} {% if images.picture == question.4 %} <img src="{{ images.picture.url }}" class="mainImg" alt=""><br> {% endif %} {% endfor %} {% endif %} {% if question.0 == '1' %} {% for el in question.2 %} <label> <input type="checkbox" class="checkbox" onclick="getCheckedCheckBoxes()" name="{{ question.1 }}" value="{{ el }}" id="{{ question.1 }}"/> {{ el }} </label><br> {% endfor %} {% else %} <label> {% for num … -
How do I modify the ManyToMany submission form from "hold ctrl to select multiple"
I'm making a medication tracking site in Django and am having trouble assigning multiple times to a medication. Currently I have a model for the Medication: class Medication(models.Model): UNDEFINED = '' MILIGRAMS = 'mg' MILIEQUIVILENT = 'MEQ' MILILITERS = 'ml' MEASUREMENT_CHOICES = [ (UNDEFINED, ' '), (MILIGRAMS, 'mg'), (MILIEQUIVILENT, 'MEQ'), (MILILITERS, 'ml'), ] ORAL = 'orally' OPTICALLY = 'optically' NASALLY = 'nasally' OTTICALLY = 'per ear' SUBLINGUAL = 'sublingual' SUBCUTANEOUS = 'subcutaneous' PER_RECTUM = 'per rectum' TOPICAL = 'topical' INHALATION = 'inhalation' ROUTE_CHOICES = [ (ORAL, 'orally'), (OPTICALLY, 'optically'), (NASALLY, 'nasally'), (OTTICALLY, 'per ear'), (SUBLINGUAL, 'sublingual'), (SUBCUTANEOUS, 'subcutaneous'), (PER_RECTUM, 'per rectum'), (TOPICAL, 'topical'), (INHALATION, 'inhalation'), ] AS_NEEDED = "PRN" EVERY = "every" EVERY_TWO = "every two" EVERY_THREE = "every three" EVERY_FOUR = "every four" EVERY_FIVE = "every five" EVERY_SIX = "six" EVERY_SEVEN = "seven" EVERY_EIGHT = "eight" EVERY_NINE = "nine" FREQUENCY_NUM = [ (AS_NEEDED, "PRN"), (EVERY, "every"), (EVERY_TWO, "every two"), (EVERY_THREE, "every three"), (EVERY_FOUR, "every four"), (EVERY_FIVE, "every five"), (EVERY_SIX, "six"), (EVERY_SEVEN, "seven"), (EVERY_EIGHT, "eight"), (EVERY_NINE, "nine"), ] MINUTE = 'minute' HOUR = "hour" DAY = "day" WEEK = 'week' MONTH = "month" FREQUENCY_MEASUREMENT = [ (MINUTE, 'minute'), (HOUR, "hour"), (DAY, "day"), (WEEK, 'week'), (MONTH, "month"), ] ONE_TAB = 'tab' … -
I'm trying to launch a project in a web server [closed]
I'm trying to launch a project in a web server but it doesn't work git clone project >>> -su: git: command not found -
Django: How do I create a Custom User based on AbstractBaseUser not resulting to a pointer
I created a custom user model from AbstractBaseUser so that I would remove the dependency on username, and just use email as the USERNAME_FIELD. I created it in this manner: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) # rest of the code I then also added this: class CustomUser(User): profile_picture = models.ImageField(null=True, blank=True, upload_to=user_directory_path, height_field=None, width_field=None, max_length=254) However, when I ran the migrations, in the database, it created a pointer(foreign key, 1-1) to the user table i.e. it created two database tables (user, and customuser). How do I make it have only the customuser table, with all the fields(including the user fields)? I do not want to put all the fields in the user table. -
jsPDF isn't working with Django - Render HTML page to PDF
I was using this function below to generate and download the pdf version of such a page. <script> function getPDF() { var HTML_Width = $(".canvas_div_pdf").width(); var HTML_Height = $(".canvas_div_pdf").height(); var top_left_margin = 15; var PDF_Width = HTML_Width + (top_left_margin * 2); var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2); var canvas_image_width = HTML_Width; var canvas_image_height = HTML_Height; var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1; html2canvas($(".canvas_div_pdf")[0], { allowTaint: true }).then(function(canvas) { canvas.getContext('2d'); console.log(canvas.height + " " + canvas.width); var imgData = canvas.toDataURL("image/jpeg", 1.0); var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]); pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height); for (var i = 1; i <= totalPDFPages; i++) { pdf.addPage(PDF_Width, PDF_Height); pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height); } pdf.save("HTML-Document.pdf"); }); }; </script> Here is an example when the function worked: <button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button> <div class="canvas_div_pdf" style="margin-left:100px;"> <p> Something to render.</p> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script> <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script> But when I try to use Django variables, like below, it doesn't work, I click on the button and nothing happened: <button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button> <div class="canvas_div_pdf" style="margin-left:100px;"> <p> {{ Something from Django }}</p> … -
django - class based views to post from user
I am creating a user post blog. I want the author name to be generated from the login but instead it is displaying the admin user name this is my Models.py I have used class based views to create post this is my views.py I am accessing author name in html as request.user.username articledetail.html -
Login and Logout Endpoints Django Rest
I want to create the login and logout endpoints for my api, when I try to go to my login endpoint, I don't find the fields in order to login, instead I find an empty page. I am using TokenAuthentication. Here is my code for Login and Logout What is wrong with my code? Login: serializers.py: UserModel = get_user_model() class UserLoginSerializer(serializers.Serializer): class Meta: model = UserModel fields = ('email', 'password',) extra_kwargs = {'password': {'write_only': True}} def validate(self, data): email = data.get('email', None) password = data.get('password', None) user = UserModel.objects.get(email= email) if(user): if(not user.check_password(data['password'])): raise serializers.ValidationError("Incorrect Password!") return data else: return Response("User Not Found!", status= status.HTTP_404_NOT_FOUND) views.py class UserLoginView(APIView): permission_classes = [AllowAny,] serializer_class = UserLoginSerializer def post(self, request): serializer = UserLoginSerializer(data= request.data) data = {} if(serializer.is_valid()): return Response(serializer.data, status= status.HTTP_200_OK) return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST) Logout: views.py: class UserLogoutView(APIView): authentication_classes = [IsAuthenticated, ] permission_classes= [IsAuthenticated,] def get(self, request): #deleting the token in order to logout request.user.auth_token.delete() return Response("Successfully Logged Out!", status= status.HTTP_200_OK) Thanks. -
Django form - update boolean field to true
I'm trying to up update a boolean field but I got this issue: save() got an unexpected keyword argument 'update_fields'. I got different issue: at the beginning when seller complete the form it was creating a new channel. I just want to update the current channel. Logic= consumer create a channel with a seller (channel is not active) -> if seller wants to launch it. he has a form to make it true and launch it. models: class Sugargroup(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sugargroup_consumer", blank=True, null=True) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sugargroup_seller") is_active = models.BooleanField('Make it happen', default=False) slug = models.SlugField(editable=False, unique=True) views: @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class CheckoutDetail(generic.DetailView, FormMixin): model = Sugargroup context_object_name = 'sugargroup' template_name = 'checkout_detail.html' form_class = CreateSugarChatForm validation_form_class = LaunchSugargroupForm def get_context_data(self, **kwargs): context = super(CheckoutDetail, self).get_context_data(**kwargs) context['form'] = self.get_form() context['validation_form'] = self.get_form(self.validation_form_class) #self.validation_form_class() return context def form_valid(self, form): if form.is_valid(): form.instance.sugargroup = self.object form.instance.user = self.request.user form.save() return super(CheckoutDetail, self).form_valid(form) else: return super(CheckoutDetail, self).form_invalid(form) def form_valide(self, validation_form): if validation_form.is_valid(): validation_form.instance.sugargroup = self.object #validation_form.instance.seller = self.request.user validation_form.save(update_fields=["is_active"]) return super(CheckoutDetail, self).form_valid(validation_form) else: return super(CheckoutDetail, self).form_invalid(validation_form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() validation_form = self.validation_form_class(request.POST) #validation_form = self.get_form(self.validation_form_class) if form.is_valid(): return self.form_valid(form) elif validation_form.is_valid(): return self.form_valide(validation_form) else: return self.form_valid(form) … -
Django: If visiting any page of the site, check if session key is created if not create it
I'm building an Ecommerce site following a tutorial that uses JavaScript to add cart functionality (mostly though, just a counter) and to store a product ID. I want to use the Django Sessions framework to replace this functionality. What I'm not sure how to do is how do you make it to where when the user visits the site (no matter what page), you set the session cart value to 0? Here's how I do it on my current class-based view only on the home page (currently): # shop/views.py from django.views.generic import TemplateView from .models import * # Create your views here. class Home(TemplateView): """Home page with products list""" template_name = 'shop/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['products'] = Product.objects.all() # Initialize cart if cart doesn't exist if not 'cart' in self.request.session: # Maybe there's a better method to put this in self.request.session['cart'] = 0 return context If it were a function based view I'd write it like this, but I prefer class based: def home(request): products = Product.objects.all() if not 'cart' in request.session: request.session['cart'] = 0 return render(request, 'shop/home.html', {'products': products}) Of course I can right the same code on every single view, but that's not dry. Is … -
Update Foreignkey values using Signals in Django
I have two models Label and AlternateLabel. Each Label can have multiple AlternateLabel associated with it, that is there is ForeignKey relation between them. class Label(models.Model): name = models.CharField(max_length=55, blank=True, unique=True) lower_range = models.FloatField(null=True, blank=True) upper_range = models.FloatField(null=True, blank=True) def __str__(self) -> str: return f"{self.name}" class AlternateLabel(models.Model): name = models.CharField(max_length=55, blank=False) label = models.ForeignKey(to=Label, on_delete=models.CASCADE) class Meta: unique_together =('name', 'label') def __str__(self) -> str: return f"{self.name}" def __repr__(self) -> str: return f"{self.name}" When a Label is created one AlternateLabel is also created using post_save signal. @receiver(post_save, sender=Label) def create_alternatelabel(sender, instance, created, **kwargs): """ when label is created an alternate label with name as label is also created """ if created: AlternateLabel.objects.get_or_create( name = instance.name, label = instance ) I also want AlternateLabel to be updated when Label name is updated For which I tried this @receiver(post_save, sender=Label) def save_alternatelabel(sender, instance, created, **kwargs): """ when label is saved an alternate label with name as label is also saved """ Label.alternatelabel_set.filter( name=instance.name, label = instance ).first().save() But, on updating the Label I am getting error None type object has not method save(), I understand this is due to the fact that, this approach is trying to find the AlternateLable with new Label … -
'<' not supported between instances of 'Tech' and 'Mobile'
hello i'm trying to make two model inside one view (def) to show data in one html page i did this in views.py but it say '<' not supported between instances of 'Tech' and 'Mobile' i don't know what is the problem Views.py : def home(request): mobileforhome = Mobile.objects.all() techforhome = Tech.objects.all() results = list(sorted(chain(mobileforhome,techforhome))) paginator = Paginator(results,6) page = request.GET.get('page') results = paginator.get_page(page) context = {'results':results} return render(request,'website_primary_html_pages/home.html',context=context) -
django rest framework nested relationship view
Following is my model representation class A(models.Model) ....__annotations__ name_a = models.CharField(max_length=100) class B(models.Model): a = models.ForeignKey(A) name_b = models.CharField(max_length=100) ....__annotations__ class C(models.Model): b = models.ForeignKey(B) Following is the serializer for model C class CSerializer(serializers.ModelSerializer): class Meta: model = C fields = '__all__' In the serializer I would like to display the name of A and B. How to achieve the same? -
Execute code when Django starts (BEFORE APP REGISTRATION)
AppConfig.ready() is the proper way to execute code when Django starts, for a given app. As the docs mention: It is called as soon as the registry is fully populated. How about initialization code that is not tied to any app and should run even before populating the registry? One example is monkeypatching a third-party module (or even Django itself!). -
Building object models around external data
I want to integrate external data into a Django app. Lets say, for example, I want to work with GitHub issues as if they were formulated as normal models within Django. So underneath these object, I use the GitHub API to retrieve and store data. In particular, I also want to be able to reference the GitHub issues from models - but not the other way around. I.e., I don't intend to modify or extend the external data directly. Are there any examples on how to achieve this in an idiomatic way? Ideally this would be would also be split in a general part that describes the API in general, and a descriptive part of the classes similar to how normal ORM classes are described. -
How to do a Model inside another Model to save a information
I am developing something and I have difficulty with a part of the Model, I registered a client and within this client, I would like to register his credit and debit information. He will borrow money and I need to register it, inside the client, so I need to enter the information of how much money he acquired with us and register manually, and every time he makes a payment, I need to register inside him too to see how much remains to be paid. I have no idea how to do this, I need to save an information inside another information and go to feed it manually. -
Run Django background task on heroku
So, I have a Django Project which has a background task for a method to run. I made following adjustments to procfile Initially web: python manage.py collectstatic --no-input; gunicorn project.wsgi --log-file - --log-level debug Now web: python manage.py collectstatic --no-input; gunicorn project.wsgi --log-file - --log-level debug worker: python manage.py process_tasks Inspite of adding worker, when I deploy my project on heroku it does not run the background task. The background task gets created and can be seen registered in django admin but does not run. I hoped after reading various articles (one of them being https://medium.com/@201651034/background-tasks-in-django-and-heroku-58ac91bc881c) adding worker: python mnanage.py process_tasks would do the job but it didn't. If I execute in my heroku cli: heroku run python manage.py process_tasks it only runs on the data which was initially present in database and not on any new data that I add after deployment. Note: python manage.py process_tasks is what I use to get the background task to run on my local server. So, if anyone could help me in running the background task after deployment on heroku. -
Access the json file with list inside. Access the dictionaries inside the list Countries
{'Message': '', 'Global': {'NewConfirmed': 314750, 'TotalConfirmed': 30073966, 'NewDeaths': 5413, 'TotalDeaths': 944827, 'NewRecovered': 214422, 'TotalRecovered': 20436752}, 'Countries': [{'Country': 'Afghanistan', 'CountryCode': 'AF', 'Slug': 'afghanistan', 'NewConfirmed': 17, 'TotalConfirmed': 38872, 'NewDeaths': 0, 'TotalDeaths': 1436, 'NewRecovered': 2, 'TotalRecovered': 32505, 'Date': '2020-09-18T09:31:06Z', 'Premium': {}}, {'Country': 'Albania', 'CountryCode': 'AL', 'Slug': 'albania', 'NewConfirmed': 132, 'TotalConfirmed': 11948, 'NewDeaths': 4, 'TotalDeaths': 347, 'NewRecovered': 55, 'TotalRecovered': 6788, 'Date': '2020-09-18T09:31:06Z', 'Premium': {}}, {'Country': 'Algeria', 'CountryCode': 'DZ', 'Slug': 'algeria', 'NewConfirmed': 228, 'TotalConfirmed': 49194, 'NewDeaths': 9, 'TotalDeaths': 1654, 'NewRecovered': 158, 'TotalRecovered': 34675, 'Date': '2020-09-18T09:31:06Z', 'Premium': {}}, {'Country': 'Andorra', 'CountryCode': 'AD', 'Slug': 'andorra', 'NewConfirmed': 0, 'TotalConfirmed': 1483, 'NewDeaths': 0, 'TotalDeaths': 53, 'NewRecovered': 0, 'TotalRecovered': 1054, 'Date': '2020-09-18T09:31:06Z', 'Premium': {}}] -
Create multiple instances of the model in one query
There is a form with several fields and a view that processes it views.py class VehiclesBlacklistAddView(ObjectAddView): model = Vehicle form_class = VehicleForm ..... def process_valid_form(self, request, form): form.instance.save() It's OK, it works. But now I want to be able to add several values to one of the item_id fields of the form by comma and create several instances instead of one views.py def process_valid_form(self, request, form): # print(form.instance.__dict__) items = [id.strip() for id in form.instance.item_id.split(',')] for i in items: form.instance(item_id=i).save() But got an error 'Vehicle' object is not callable models.py class Vehicle(models.Model): item_type = models.CharField() item_id = models.CharField() desc = models.CharField() -
How to Fetch Data Form Many to Many relation table in Djnago?
I Have Many to Many Relationship tables. One user can take Multiple Courses this is what i want to do.My Models are class CourseModel(models.Model): course_name = models.CharField(max_length=255,blank=False) class UserModel(models.Model): username = models.CharField(max_length=255) usercourses=models.ManyToManyField(CourseModel) #this code is creating saperate table in my database my new created table's data looks like below: id : 1 usermodel_id : 7 # (any user_id can come here) coursemodel_id : 10 #(any course id can come here) id : 2 usermodel_id : 7 coursemodel_id : 11 As we can see in Above Data, user(7) taken multiple courses such as 10,11. i Want to fetch all Courses of user(7) form above data.How to do that? -
derive dataframe column in django views with pandas
I'm retrieving some data from a database But before sending them to frontend, I'd like to do some basics data manipulations. def mypage(request) #database request here # [...] #now I'm pushing it into a dataframe - this works! myresults=pd.DataFrame(mydata.data()) #now I'm selecting a subset of the retrieved data - this works! myresults=myresults[["VAR1","VAR2","VAR3"]] #now I'm trying to derive VAR4, setting it equal to VAR3 #the basic pandas syntax seems correct, but in Django for some reasons it fails myresults["VAR4"]=myresults["VAR3"] What am I doing wrong here? I tried to achieve the same using numpy - but failed again. Thanks. -
loading image as input to keras-theano models
I am using following code to load images for input in to keras-theano models. def load_to_img(path_to_img): image=k.preprocessing.image.load_img(path_to_img) image = img_to_array(image) # this is a Numpy array with shape (3, 150, 150) image= image.reshape((1,) + image.shape) image=image/260 return image and when I am trying to input it to a keras model i get following error. ValueError: Layer sequential_13 was called with an input that isn't a symbolic tensor. Received type: <class 'numpy.ndarray'>. -
Uvicorn running with Unicorn, how?
While reading the docs of running Uvicorn: Gunicorn is a mature, fully featured server and process manager. Uvicorn includes a Gunicorn worker class allowing you to run ASGI applications, with all of Uvicorn's performance benefits, while also giving you Gunicorn's fully-featured process management. Is doc wrong or i didn't understand correctly? from my understanding, Gunicorn has a master slave structure to allow Uvicon class(async sever) to run in separate worker classes using command: gunicorn example:app -w 4 -k uvicorn.workers.UvicornWorker why the doc says: Uvicorn includes a G unicorn worker class allowing you to run ASGI applications Someone could explain? thanks in advance! -
django raised 'function' object is not subscriptable but local python doesn't
I got a strange thing I can't handle and understand. I'm really intrigue Let me explain, I coded some stuff locally on my computer with python3 (which run like a charm !! ), I used to transfer this script to my django . And magic happen it's raised an error , I don't have when I run locally ... here is the script part which seems to create the error : from c***.utils import calculate_distance from operator import itemgetter import geopy solution = [] def is_in_radius(elem1, elem2): dict_coord = { 'pa' : (elem1[3][0],elem1[3][1]), 'pb' : (elem2[3][0],elem2[3][1]), } distance = calculate_distance(dict_coord.get('pa'), dict_coord.get('pb')) # print("distance : " + str(distance) + " m - entre : "+ str(elem1[0]) + " et " + str(elem2[0])) if (distance <= 1200): return(True) else: return(False) def last_rad(data_info, elem1, am_act): global solution if(len(solution) + 1 == am_act): if(is_in_radius(elem1, data_info[1]) == True): return(True) else: return(False) else: return(True) def first_rad(data_info, elem1): global solution if(len(solution) == 0): if(is_in_radius(data_info[0], elem1) == True): return(True) else: return(False) else: return(True) Error raised is : 'function' object is not subscriptable Request Method: POST Request URL: http://****.io/new_search Django Version: 3.1 Exception Type: TypeError Exception Value: 'function' object is not subscriptable Exception Location: /home/debian/***/mysite/**/backtrack.py, line 33, in first_rad … -
How to query multiple models in views and pass them to one template?
I am trying to make a path lab database system, Where I have models as follows: Client model: to store client name CBC test model: child to client model. Liver test model: child to client model. kidney function test model: child to client model. my purpose is that if we enter client id and date to form it goes to result page and shows all the test performed to that particular client on that date. I made a client model and models for each tests. from django.shortcuts import render from .models import client, cbc, lft, kft from django.db.models import Q # Create your views here. def index(request): return render(request, 'vmr/index.html') def result(request): client = request.POST['client'] date = request.POST['date'] r = cbc.objects.filter(Q(id = client ) & Q(Date__iexact = date)) l = lft.objects.filter(Q(id = client ) & Q(Date__iexact = date)) k = kft.objects.filter(Q(id = client ) & Q(Date__iexact = date)) context = { "results": r, "liver": l, "kidney":k} return render(request, 'vmr/result.html', context=context ) ``` My Result template for results is: {% if results %} {% for result in results%} <h3 style="padding-left: 10%;"> DATE:{{result.Date}} </h3> <table style="width:70%"> <tr> <th>PARAMETER</th> <th>UNIT</th> <th>VALUE</th> <th>RANGE</th> <th>INFERENCE</th> </tr> <tr> <td> RBC </td> <td> million/mm3 </td> <td> {{result.RBC}} …