Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remote deployment with pyCharm + Django + Raspberry pi
I'm developing web application on raspberry pi using Django. I set up django, virtual enviroment and server on raspberry pi. Now I want to write code in pyCharm and deploy it on remote machine(raspi). I've copied all folders (virtualenviroment also) to my pc. I'm wondering- how can I 'take' this virtual enviroment from raspberry to have also working on pyCharm? I've tired: C:\MyPath\AquaControl>activate AquaControlEnv Could not find conda environment: AquaControlEnv and by using conda info --envs C:\MyPath\AquaControl>conda info --envs # conda environments: # base * C:\Users\Me\Anaconda3 Only this one from PC is discoverable. Or I can create local virtual enviroment and this will not cause any problems with deployment on remote? -
Django choicefield using pictures instead of text not displaying
I'm trying to do something which should be straightforward, but I cannot have it work properly. I would like to display images in a grid, with let's say 4-6 images per column and be able to select one and then hit a submit button. My model looks like: class MyPicture(models.Model): name = models.CharField(max_length=60, blank=False, unique=True) logo = models.ImageField(upload_to='logos') def __str__(self): return self.name My form looks like: class MyPictureForm(forms.Form): def __init__(self, data, *args, **kwargs): super(MyPictureForm, self).__init__(data, *args, **kwargs) self.fields['pictures'] = forms.ModelChoiceField(queryset=MyPicture.objects.all()) My view looks like: def mypicture(request): form = MyPictureForm(request.POST or None) if form.is_valid(): #TODO return render(request, 'myproj/picture.html', {'form': form}) and finally, my hmtl (where I assume the issue lies): <form action="{% url 'mypicture' %}" method="post"> {% csrf_token %} {% for s in form.pictures %} <option value="{{ s.id }}"><img src="{{ MEDIA_URL }}{{ s.logo.url }}"/></option> {% endfor %} <input type="submit" value="Submit" class="btn btn-primary"/> </form> The pictures just don't show up. When I put a breakpoint, in the form I was able to double check that the adresses of the pictures were properly selected. I'm convinced the error is in the html, but I could not figure out where despite my many attempts. Maybe with a fresh eye, you'll spot it in seconds... … -
How can you add a name by clicking the button to Django?
I want to know that the theme of making the website in Django is the project site but clicking the button, you know the name of the user enters and participate, what should I do? Tell me how! -
Django-ORM: Check whether multiple items are in DB while minimizing calls
Assume that from an external API call, we get the following response: resp = ['123', '67283', '99829', '786232'] These are external_id fields for our objects, defined in our Article model. Some of which may already exist in database, while others don't. Before returning a response, we need to check whether each external_id corresponds to a record in our database, and if not, we need to create it and fetch additional info from another, third, source. What is the most efficient way to do this? Right now I can't think of something better than: for external_id in resp: if not Article.objects.filter(external_id=external_id).exists(): # item doesn't exist, go fetch more data and create object else: # already exists, do something else But there must be a better way..? -
Access URL Parameter Variables in Custom ScopedRateThrottle
I'm using Django Framework and Django REST Framework. I have an endpoint that needs to be throttled using the (user, token) pair, with user being the user making the request and token being the URL variable specified in the urls.py url(r'^api/v2/(?P<token>\w+)/action$', ActionEndpoint.as_view()) I have created a custom ScopedRateThrottle to accomplish this: class CustomThrottle(ScopedRateThrottle): rate = '2/day' def get_cache_key(self, request, view): user_id = request.user.pk token = (?????????) identity = "%s_%s" % (user_id, token) cache_key = self.cache_format % { 'scope': self.scope, 'ident': identity } return cache_key Question: How should I retrieve the token variable from the request object in this scenario? -
AttributeError at /cart/add/2/ 'Cart' object has no attribute 'add'
enter image description here Here in line 16 has an errorenter image description here urls.py of app cart -
AttributeError: module 'django.db.models' has no attribute 'PositiveSmallIntgerField'
I am a beginner in django I started facing this issue while running the manage.py runserver this is my models.py file from django.db import models # Create your models her class Product(models.Model): Product_ID = models.IntegerField(primary_key = True) Name = models.CharField(max_length=264) Price = models.DecimalField(decimal_places=2, max_digits=5) Quantity = models.PositiveSmallIntgerField(default=1) Reviews = models.TextField() def _str_(self): return self.Name class Buyer(models.Model): Buyer_ID = models.IntegerField(unique=True) Name = models.CharField(max_length=264) DOB = models.DateField(auto_now=False, auto_now_add=False) Address = models.CharField(max_length=264) Sex = models.CharField(max_length=6) Reviews = models.TextField() Product_ID = models.ForeignKey(Product) def _str_(self): return self.Name class Seller(models.Model): Seller_ID = models.IntegerField(unique=True) Name = models.CharField(max_legth=264) Contact = model.IntegerField() Product_ID = models.ForeignKey(Product) def _str_(self): return self.Name class Order(models.Model): Order_ID = models.IntegerField(unique=True) DateOfDelivery = models.DateField(auto_now=False, auto_now_add=False) Buyer_ID = models.ForeignKey(Buyer) Product_ID = models.ForeignKey(Product) def _str_(self): return self.Product.Name class Admin(models.Model): Admin_ID = models.IntegerField(unique=True) Name = models.CharField(max_length=264) Contact = models.IntegerField() Product_ID = models.ForeignKey(Product) Seller_ID = models.ForeignKey(Seller) Buyer_ID = models.ForeignKey(Buyer) def _str_(self): return self.Name The error i get is: module 'django.db.models' has no attribute 'CharField'. I have already crossed check any other settings or files to be imported but everything is in place -
Using google map api(javascript) with django queryset, I can't access queries well of the queryset
I can't access queries of queryset. Only, I can have the first query of queryset, if I do like this. views.py def restaurant(request, pk): restaurants = Restaurant.objects.all() ctx = { 'comments': comments, } return render(request, 'base_app/restaurant.html', ctx) base.html var markers =[]; // new map var map = new google.maps.Map(document.getElementById('map'), options); {% for restaurant in restaurants %} var marker = new google.maps.Marker({ position: {{ restaurant.locate }}, map: map, }); var restaurant_introduction = '<div class="restaurant_set">\n' + ' <div class="restaurant_image"></div>\n' + ' <div class="restaurant_content">\n' + ' <div class="restaurant_name">**{{ restaurant }}**</div>\n' + ' </div>\n' + ' <a href="**{% url "base_app:restaurant" pk=restaurant.pk %}**"><div class="comments">more</div></a>\n' + '</div>'; markers.push(marker); {% endfor %} } Do I have to use Json?? OR what should I do to use other queries(I mean other restaurants, not only first one). -
No HttpResponse object is returned when calling a view from another view?
I have a webpage where user chooses one object from a model. Based on the button clicked, certain actions are executed. One of the actions is by calling one of the views, and dislaying another webpage. So, when user visits http://127.0.0.1:8000/clinic/manage, he sees the below form: Code: @login_required def manage_clinics(request): msg = '' if request.method == 'POST': clid = int(request.POST.get('clinics')) print("POST details", request.POST) if request.POST.get('createdoctor')=='Create Doctor': clinicobj = Clinic.objects.get(clinicid=clid) print("Creating Doctor for clinic:", clinicobj) createdoctor(request, clinicobj.label) else: form = ChooseClinicMetaForm() return render(request, 'clinic/manageclinics.html', {'form': form, 'msg': msg}) If he clicks on 'Create Doctor', the following view function is to be executed: @login_required def createdoctor(request, cliniclabel): msg ='' cliniclink = '/clinic/'+cliniclabel+'/createdoctor' cl = Clinic.objects.get(label=cliniclabel) if request.method == 'POST': print("POST details", request.POST) form = DoctorMetaForm(request.POST) if form.is_valid(): print("Form is valid.") # form.save() username = request.POST.get('username') name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') msg = SaveDoctortoSQLNew(request) print(msg) if 'Error:' not in msg: doctorobj = doctor.objects.get(name=name, email=email, phone=phone, username=username) clinicobj = Clinic.objects.get(label=cliniclabel) permobj = ClinicPermissions(clinicid=clinicobj, doctorid=doctorobj, viewperms =1) permobj.save() msg = "Successfully created a doctor and assigned permissions" else: msg = "Invalid details." print(msg) else: # cl = Clinic.objects.get(label=cliniclabel) form = DoctorMetaForm() return render(request, 'clinic/doctorprofile.html', {'form': form, 'rnd_num': randomnumber(), 'cliniclink': cliniclink, 'msg': … -
Django models for school timetable?
I am building a school timetable app for each room? There are my models. Is there anything i am missing? class Building(models.Model): bid = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=255, unique=True) class Meta: ordering = ['bid'] def __str__(self): return f'{self.bid}' class Room(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE, related_name='rooms') number = models.PositiveIntegerField() availability = models.BooleanField(default=False) power = models.BooleanField(default=False) class Meta: ordering = ['building', 'number'] unique_together = ['building', 'number'] def __str__(self): return f'{self.building.bid}/{self.number}' class Occurrence(models.Model): date = models.DateField('Date') start_period = models.ForeignKey(Period, on_delete=models.CASCADE, related_name='start_at') end_period = models.ForeignKey(Period, on_delete=models.CASCADE, related_name='end_at') class Meta: abstract = True class Period(models.Model): start = models.TimeField() end = models.TimeField() objects = PeriodManager() class Meta: ordering = ['start'] def __str__(self): return f'{self.start}-{self.end}' def check_time(self): return True if self.start < self.end else False def check_overlap(self): pass class TimetableModel(models.Model): class Meta: abstract =True There will be a model name Booking which extends from Occurrence to allow students register to use a room in periods.Any advises? -
How to change the ui of django-oscar ?
iam buiding an ecommerce website and new to python.How can i change the ui of django-oscar ui and also the admin dashboard ui -
Deploy Django 2.1 with Apache and mod_wsgi gives Timeout
I´m really stuck trying to get my Django-App working with Apache2 and mod_wsgi. Maybe some good people here can help me out? I had to put my VHost for 80 and 443 into one file, since certbot is only doing Copy & Paste with the VHost and that leads to an error due to the requirement of the unique WSGI Process naming etc. So here is my VHost (apache2 configtest all good): WSGIDaemonProcess my.domain.co processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/site/project/venv/lib/python3.6 WSGIProcessGroup my.domain.co WSGIScriptAlias / /var/www/site/project/wsgi.py <VirtualHost *:80> ServerName my.domain.co DocumentRoot /var/www/site <directory /var/www/site> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /var/www/site/static/ <Directory /var/www/site/static> Require all granted </Directory> RewriteEngine on RewriteCond %{SERVER_NAME} =my.domain.co RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost *:443> ServerName my.domain.co DocumentRoot /var/www/site <directory /var/www/site> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /var/www/site/project/ <Directory /var/www/site/static> Require all granted </Directory> SSLCertificateFile ... SSLCertificateKeyFile ... Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> Where my projectstructure is obviously: /var/www/site as the main directory in which the venv lives and django-project was created. The project dir contains the wsgi.py and the settings.py. So when I´m trying to open my site I´m running into a timeout error. When I´m doing: python3 manage.py runserver 127.0.0.1:8080 and … -
adding queryset month and year dropdown list filter in django view page
I am working on queryset django. In my view page i am able to get data from database for month and year by typing manually. instead i need drop down list for year and month. and also date picker for selecting data between two dates. For example, Display data From Sep 24 2018 To Sep 28 2018 models.py from django.db import models class Track(models.Model): EndDate = models.DateField(blank=True, null=True) STATUS_CHOICES = [('Progress', 'Progress'),('Completed', 'Completed')] filters.py from django.contrib.auth.models import User import django_filters from .models import Track class UserFilter(django_filters.FilterSet): class Meta: model = Track fields = { 'EndDate': ['year','month', ], } views.py from django.shortcuts import render from django.http import HttpRequest, HttpResponse from .filters import UserFilter def search(request): status_list = Track.objects.filter(Status__startswith='Completed') status_filter = UserFilter(request.GET, queryset=status_list) return render(request, 'hai/data.html', {'filter': status_filter}) HTML page <div> {% block content %} <form method="get"> {{ filter.form.as_table }} </select> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </form> <ul> <table style="margin-top: 20px" class="table table-bordered" > <span style="display:none"></span> <thead> <tr> <th>EndDate</th> </tr> </thead> <tbody> {% for Track in filter.qs %} <tr> <td>{{ Track.EndDate }}</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> </table> {% endblock %} HTML Page Screenshot -
Referencing css and js files in django templates?
I am working on an eCommerce site. I have bootstrapped a template that is in plain html,css and js. Now, I am trying to migrate it to django template. So, here is the issue. The index.html file which is the landing page has over 67 css + js references and then there are close to 80 img references. Now, referencing them one by one to django way is tiresome and tedious. Is there a better way if i am faced with such a situation ? -
Bad redirect for a part of my first app for Django
Hi I'm newbie into the Django world and for learn the bases I've decided to develop my new blog. On my blog I've two categories: gis and sustainable mobility. I've created two view for each one for the list of posts and the single post using ListView and DetailView. This is views.py: class SuMoSinglePost(DetailView): model = Post template_name = "single_sustainablemobility.html" class SuMoListPosts(ListView): model = Post template_name = "list_sustainablemobility.html" queryset = Post.objects.filter(categories_id=2) class GisSinglePost(DetailView): model = Post template_name = "single_gis.html" class GisListPosts(ListView): model = Post template_name = "list_gis.html" queryset = Post.objects.filter(categories_id=1) This is urls.py: path("gis/", GisListPosts.as_view(), name="list_gis"), path("gis/<slug:slug>/", GisSinglePost.as_view(), name="single_gis"), path("sustainable-mobility/", SuMoListPosts.as_view(), name="list_sustainablemobility"), path("sustainable-mobility/<slug:slug>/", SuMoSinglePost.as_view(), name="single_sustainablemobility"), This is models.py: class Category(models.Model): type = models.CharField(max_length=20, verbose_name="Categoria", help_text="Every argument must be not longer then 20 characters", unique=True) created = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name="Data di creazione") def __str__(self): return self.type def get_absolute_url(self): return reverse("single_category", kwargs={"pk": self.pk}) class Meta: verbose_name = "Categoria" verbose_name_plural = "Categorie" class KeyConcept(models.Model): """definizione delle caratteristiche di una concetto chiave""" concept = models.CharField(max_length=50, verbose_name="Concetti chiave", help_text="Every key concept must be not longer then 50 characters", unique=True) created = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name="Data di creazione") def __str__(self): return self.concept def get_absolute_url(self): return reverse("single_keyconcept", kwargs={"pk": self.pk}) class Meta: ordering = ['concept'] verbose_name = "Concetto chiave" … -
django adding a column on a queryset
Hi i got a question lets say i got this models: class Site(): site_name = charfield class Sample(): site = foregeinkey state = decimalfield sample_date = datefield and i need to assembly a table like this: | site_name | latest_sample | | site1 | 150 | searching in the documentation an the internet link1 link2 i found annotate for when i need to adding some other characteristics to a query set and my new query is something like: class ApiGetListOfSites(View): def get(self, request, format=None): objList = Site.objects.annotate( date_sample=Max('sample__sample_date'), valor_estado=F('sample__state') ) json = serializers.serialize('json', objList) return HttpResponse(json, content_type='application/json') i got the problem that i retrieve repeated objects and no new columns in the json. some one con help me with some suggestions on how i can do this. Ps i think if i write the query in raw SQL i can used with the raw property of django models. -
Django- MultiValueDictKeyError while requesting GET object from html page
I am having a problem while fetching the data from HTML. In views.py def PrimeNumber(request): number = request.GET['number'] return render(request , 'PrimeNumber.html',{'number':number}) In html file <form action = "{% url 'PrimeNumber' %}"> <label for="number"><b>Enter the number : </b></label> <input type="text" placeholder="Enter Number" name= "number" required> </form> Error I am facing Exception Type: MultiValueDictKeyError Exception Value:"'number'" I dont what is happening over here. Since I am beginner in python I have gone through many answers on stackoverflow but did not understand how to implement that on my own code. Please inform if any information is missing. -
Django: web app with session authentication and android app with JWT authentication: How to manage DRF views
I am developing an application for web and android: I have decided to use session authentication for web application and JWT based authentication for android app I found that for both applications i will have to create api endpoints for using data. I am using DRF to create api endpoints: Will DRF views indentify the request and check the user based on session authentication or JWT token Or i have to write different views for session authentication and JWT authentication seprately. -
How to return table name in django model
My Model.py class Banana(models.Model): nohdt = models.IntegerField() isi_indonesia = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'Banana' def __str__(self): return self.isi_indonesia class Mango(models.Model): nohdt = models.IntegerField() isi_indonesia = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'Mango' def __str__(self): return self.isi_indonesia My View.py list = [] data = [] banana = Banana.object.all() mango = Mango.object.all() list.append(banana) list.append(mango) for x in list: #looping django-models for i in x: #looping list in models tmp = {'no':x.nohdt, 'indo':x.isi_indonesia, 'table_name':???} data.append(tmp) return render(request, 'index.html', {'data':data}) i have two models in model.py, in my view 'view.py' i use LIST to store data. Before i store, i loop list models, and loop value of models. And than i use tmp variable to keep information of 'nohdt', 'isi_indonesia', and 'name of model'. How do i return name of model? -
Change django admin site url dynamiclly
I have django project. I want to use django admin site and have an url in django admin site to redirect user to certian url, so I used this code: admin.py: from django.contrib import admin admin.site.site_url = 'http://localhost:8000/some-api-url/' This code change VIEW SITE link in django admin. Problem is this url is static and I want to get server url dynamically, is there any approach to do that? -
Make a Django Form Field Time Zone Aware
I have a form field where the user enters a date. I want to have the user enter the date in their timezone and then save the date in the database in UTC time. I can't find any resources on how to do this. Does anyone have any ideas? -
Django 2.1: Base template for all apps does not recognize static files in project root
Following this structure: gallito (Django project folder) |_gallito |_main_app |_static |_main_app |_style.css |_static |_style2.css |_templates (new) |_registration |_login.html |_base.html I need/want to have a base template in project root template folder, that extends to my html files inside my main_app (and other apps there will be in the future). 'base.html' extends correclty but it has problems reading the css file inside the static folder in project root: 'style2.css' In my base.html file inside project root directory static templates folder, I've: Using this and calling the style sheet from main_app I get my site working: <link href="{% static 'main_app/style.css' %}" rel="stylesheet"> But if I want to call the style sheet from project root static folder, It wont work: <link href="{% static 'style2.css' %}" rel="stylesheet"> Why? I've this in my project settings: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' I've read that I also need a STATICFILES_DIRS variable to point to my static files dirs. Any pointer on this? STATICFILES_DIRS base.html from root: {% load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../../../favicon.ico"> <title>Jumbotron Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link … -
In Django, how to get child object that is connected by foreign key?
In Django, the following code works fine - event has a foreign key to group. group = Group.objects.get(slug=cult_slug) event = Event.objects.get(slug=event_slug) The event that is returned above is what I need - it allows me to get field values from the event object. I am trying to work out how to do effectively the same thing, but instead get the event object with a given slug via the cult object. I have tried this, but it does not seem to return the same event object as in the top example: event1 = cult.event_set.filter(slug=event_slug) I also tried this but it also does not give me a working event object that I can get fields from: event2 = Cult.objects.get(slug=cult_slug).event_set.filter(slug=event_slug) Can anyone please suggest how I can get a child object via its parent, filtering on a specific field such as "slug"? thanks! -
Django models not allowing one to many relationship
Having a really tough time wrapping my head around creating this model set for Django. Currently I am creating a site where a user can click the article to decide that he or she likes the article. I have set up the models to include article, favorite articles, and user. However, currently the way I have it set up is for it to only allow the user to have one favorite article, not two. I am using the ForeignKey field and that is not working. Here they are from django.db import models # users/models.py from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver import uuid class Article(models.Model): title = models.CharField(max_length=120, primary_key=True) content = models.TextField() url=models.CharField(max_length=200, null=True) category = models.CharField(max_length=250, null =True) def __str__(self): return self.title class CustomUser(AbstractUser): username = models.CharField(max_length=50, unique=True, primary_key=True) git = models.CharField(max_length=200, null=True) homepage = models.CharField(max_length=250, null=True) def __str__(self): return str(self.username) class FavoriteArticles(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user', null=True) fav_title = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='fav_title', null=True) reasons = models.CharField(max_length=120, null=True) favcategory = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='favcategory', max_length=250, null =True) # def __str__(self): # return self.user -
How to store a JWT and how to use it in cookies
I have a Django REST backend and React frontend. My submit function is the following: handleSubmit = async event => { event.preventDefault(); const { username, password } = this.state; const response = await login(username, password); console.log(response.data.token); }; response.data.token is successfully returning a token but my question is: How do I store it to use in another HTTP requests? (Using the cookie solution)