Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a model instance through another model
Guys I was looking at how I can add a model instance that can be added through another model. like how tags are done. If a model instance doesn't exist add it. if It does exist, don't add, just use the existing one. I wanted to do that with a Category model where if the category exists use the existing one and vice versa. #Models class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Company(models.Model): name = models.CharField(max_length=120, help_text='Name of your company', ) slug = models.SlugField(unique=True, blank=True, null=True) categories = models.ManytoManyField(Category, related_name="company", blank=True, null=True, on_delete=models.PROTECT) #Views class CompanyCreate(CreateView): model = Company form_class = CompanyForm template_name = 'company/form.html' So when one adds a company can add many categories but use the one that already exists. Thanks in Advance -
Using Django views to redirect the user to the page they took the POST action on:
A user could be at one of three pages: For this argument let's call them page1, page2 or page3. On each of those pages, they can take the same actions essentially, with subtle differences. So if the user is on page1 and they take a POST action, then after the post action is done, the redirect should just "refresh" the page so they remain on page1 and can conduct other business from there. In the view, how do I call the URL and then return redirect(that_url)? -
how to tell a django view what are the parameters when i am not using a template
I am creating a library management system where a user sends a borrow request to a librarian who will approve it. I created the requisite pages as I understood it but I am unable to make two return statements. Fairly new to django, I dont know about restful uri. my views.py @login_required def send_borrow_request(request, pk,userID, bookID): from_user=request.user to_user =User.objects.get(id=userID) book_id=BookInstance.objects.get(id=bookID) borrow_request, created= Borrow_Request.objects.get_or_create(from_user=from_user, to_user=to_user, book_id=book_id) if created: return HttpResponse('borrow request sent') else: return HttpResponse('borrow request was already sent') @login_required @permission_required('catalog.can_grant_decline_request') def process_borrow(request,pk): book_instance=get_object_or_404(BookInstance,pk=pk) if request.method == 'POST': data={'bookinstpk':book_instance.id} form = GrantRequestForm(request.POST, initial=data) if form.is_valid(): book_instance.status__exact='o' book_instance.due_back=datetime.date.today() + datetime.timedelta(days=7) book_instance.borrower=form.cleaned_data['name'] book_instance.save() return HttpResponseRedirect(reverse('all-borrowed')) else: form=GrantRequestForm() context={ 'form':form, 'book_instance':book_instance, 'borrower':book_instance.borrower, } return render(request,'catalog/process_borrow.html',context) bookinstance model class BookInstance(models.Model): id=models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID') book=models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) due_back=models.DateField(null=True, blank=True) borrower=models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) @property def is_overdue(self): if self.due_back and date.today()>self.due_back: return True return False LOAN_STATUS=( ('m','Maintenance'), ('o','on loan'), ('a', 'Available'), ('r', 'Reserved'), ) status=models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability', ) class Meta: ordering=['due_back'] permissions = (("can_mark_returned", "Set book as returned"),) def __str__(self): return f'{self.id}({self.book.title})' class Borrow_Request(models.Model): from_user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="from_user") to_user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="to_user") book_id=models.ForeignKey('BookInstance',on_delete=models.CASCADE,related_name="bookinst") class Meta: # ordering=['self.bookinst.due_back'] permissions = (("can_grant_decline_request", "Grant or decline a Request"),) def __str__(self): return f'{self.borrower.username}({self.book_id.book.title})' def get_absolute_url(self): return reverse('borrow-detail', args=[str(self.id)]) urls.py A particular bookinstance … -
What is the use of django rest framework
Please bear with me I am new in the world django. I am using django rest framework, but what is its use... Is it for fetching data directly in the template, or something else. And is it good to directly use javascript fetch method to get data? Another question, do websites like github, use there own api to render data on the template or they fetch data directly from database? Your help is appreciated! Thank you. -
Django how to remove the ForeignKey in the template
I want to remove ForeignKey in the forms and in the template and it generates it automaticallyenter code here the models and the forms are there: from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class PostProduit(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) titre = models.CharField(max_length=255) categorie = models.CharField(max_length=255) description = models.TextField(max_length=255) prix_en_FCFA = models.CharField(max_length=255) Whatsapp = models.BooleanField(max_length=255) photo_1 = models.ImageField(upload_to="image/") photo_1 = models.ImageField(upload_to="image/", null=True, blank=True) photo_1 = models.ImageField(upload_to="image/", null=True, blank=True) photo_1 = models.ImageField(upload_to="image/", null=True, blank=True) date = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user} ===> {self.titre}" class PostProduitForm(ModelForm): class Meta: model = PostProduit fields = '__all__' -
How to update a Django html element with javascript and Ajax
I am trying to update an html element on web page with javascript. When the home page loads, it works perfectly, but when I click on New Product link just the context string is displayed on the home page html <!-- product/home.html --> {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <title>Test context</title> </head> <body> <h1>Test context</h1> <div class="container"> {% block content %} Product: <span id="product-code"></span> <p><a href="{% url 'new-product' %}">New Product</a><p> {% endblock content %} <script type="text/javascript" src="{% static 'js/product.js' %}"></script> </div> </body> </html> urls.py # cardplay/urls.py from django.urls import path from .views import HomePageView, NewProduct urlpatterns = [ path('', HomePageView.as_view()), path('new-product', NewProduct.as_view(), name= 'new-product'), ] views.py # /product/views.py import random from django.views.generic import View from django.shortcuts import render from django.http import JsonResponse class HomePageView(View): template = 'product/home.html' def get(self, request): context = {} return render(request, self.template, context) class NewProduct(View): def get(self, request): code = random.choice(['A123','M456', 'X789']) context = { 'code': code, } return JsonResponse(context) product.js $(document).ready(function () { getNewProduct(); }); function getNewProduct() { $.ajax( { type: "GET", url: 'new-product', cache: false, success: function (context) { displayNewProduct(context); } } ); } function displayNewProduct(context) { var productCode = document.getElementById('product-code'); productCode.innerText = context.code; } What … -
Not able to use the collectstatic command while deploying to pythonanywhere
I am trying to collect all my static files into one folder using the python manage.py collectstatic command but it throws me this error error image notice the address '/home/vatsalp/django3-personal-portfolio/portfolio\static\portfolio' has mixture of forward and backward slash which might be the issue but do not know how to resolve it and also i am on a windows computer please help me fix this! -
Django doesn't update static files, clearing browser cache doesn't work
I stumbled into a problem with my Django & React app. I am changing the look of a component and Django doesn't update it when I refresh, I tried deleting the cache, didn't work. To be sure that it's not my browser I accessed the site from my phone and the updated content wasn't there. As a final check I used my other machine and fresh install of everything related and copied my project there and the changes finally showed. What could be the cause of the problem on my main machine? Does django itself store some cached older version and use that instead? -
How do I align fields in html from django forms?
I have a form with which I intend to capture student marks. I have an issue lke I don't know the best way to put it so that I have student name and markfield beside it for all the students. calling {{ form }} brings the form with select dropdown items(not what I want). Specifying form fields do not populae anything.i.e {% for field in form %} {{ field.student }} {{ field.marks }} {% endfor %} This is the form class AddMarksForm(forms.ModelForm): def __init__(self, school,klass,term,stream,year, *args, **kwargs): super(AddMarksForm, self).__init__(*args, **kwargs) self.fields['student'] = forms.ModelChoiceField( queryset=Students.objects.filter(school=school,klass__name__in=klass,stream__name=stream[0])) class Meta: model = Marks fields = ('student','marks') This is how I tried the html rendering <form method="post" enctype="multipart/form-data" action="{% url 'add_marks' %}"> {% csrf_token %} {% if form %} <table> <tr> <td>Student</td> <td>Marks</td> </tr> {% for field in form %} <tr> <td>{{ field.student }}</td> <td>{{ field.marks }}</td> </tr> </table> {% endfor %} <button class="btn btn-outline-primary">Save</button> </form> My view. class AddMarksView(LoginRequiredMixin,CreateView): model = Marks form_class = AddMarksForm template_name = "feed_marks.html" success_url = reverse_lazy('search_m') def get_context_data(self, *args, **kwargs): class_name = self.request.session.get('class_name')#From session storage context = super(AddMarksView,self).get_context_data(*args, **kwargs) context["student_subjects"] = Students.objects.filter(school=self.request.user.school,klass__name = class_name,stream__name='South') return context def get_form_kwargs(self): kwargs = super(AddMarksView, self).get_form_kwargs() year = self.request.session.get('year_input')#From session storage print(year) term … -
Messages Error in Django doesn't appear to the user when registering
I have a problem with my user registration function. My goal is to have the code check in the database to see if the username is already taken or not, and let the user know in case it's already taken. For now, the code is working fine for the first part, but the second doesn't work. The message "Something is wrong" appears but not the one specific to the username "This user already exists". I tried to do the following options that I found on stack, but nothing is working: first to change the form and raise a ValidationError and check for error in the front second to verify in the function "user_register" if the user is already taken and raise a message.error, this is the option in my code bellow third, try if the user exists and bring an error in the context Would someone knows what is wrong with my code? It could be something really stupid. Here is my view.py def user_register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = User.objects.create_user(username=username, password=password) group = Group.objects.get(name='Stroller') group.user_set.add(user) user.save() login(request, user) messages.success(request, "New account successfully created" ) return redirect('accounts:dashboard') else: … -
how to block direct access from staticfiles in django
Anybody can access static files in my django website by just putting the location of that particular file like css,js & img inside the url(for example:- https://example.com/static/css/style.css). I want block direct access from them so nobody can get access to any css code or any js code which makes website more vulnerable(easly hackable). I have seen in websites like EA, etc you can't have access to their static & media files as well as all their static & media files location are hidden when inspect on browsers like chrome, etc. Also I want to hide locations of these files from the inspect section in browsers like chrome, etc. -
Real time Django
I'm learning django so I'm doing Facebook clone Is there a way to make notifications by real time? I tried using ajax but it only updates for the same user not others, and for channels, i can rarely find a tutorial and even if i did it's old and they only build chat apps and for documentation it's difficult to understand Even react is only used with rest framework is there any other way to do it? I did friend request and notification system but I can't make them in real time i just need to reload to find new ones -
How can I get the profile image from Postgres DB (Django REST) to Android Studio
I try to get user's image profile from django (it's saved in postgres db as ImageField) This is my model: class User(models.Model): user_id = models.AutoField(primary_key=True) username = models.CharField(max_length=100, db_column='username') password = models.CharField(max_length=100, db_column='password') profile_image = models.ImageField(upload_to='', null=True, default=None) class Meta: db_table = 'User' This is my Serializer class ProfileImageSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('profile_image',) And this is my request method (view): @api_view(['GET']) def image(request, pk): if request.method == 'GET': user = User.objects.filter(user_id=int(pk))[0] try: dict_user = {"profile_image": user.profile_image} user_serializer = ProfileImageSerializer(data=dict_user) if user_serializer.is_valid(): return JsonResponse(user_serializer.data, status=status.HTTP_200_OK, safe=False) return JsonResponse(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST, safe=False) except Exception as e: return JsonResponse({'error': e.args[0]}, status=status.HTTP_400_BAD_REQUEST) If I try GET method above it returns the image url But if I want to see the picture in browser it doesn't work This is the settings: MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' And the urls: urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include('filmdb.urls')), url(r'^$', index, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Why didn't work? -
How to get total duration with minuts and second?
I am trying to display duration time for an particular work. For example 15:20:30 min Hence 15 is hour, 20 is minutes and 30 is second. class UserData(models.Model): uid = models.CharField(max_length=100) email = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(auto_now=True) @property def duration(self): if not (self.start_date and self.end_time): return None a,b=self.start_date, self.end_time return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60) It's giving me datetime.date' object has no attribute 'tzinfo' error. How can i get the duration from this property please? -
Process a rather large python dictionary in Heroku?
I'm upserting roughly 17000 records after doing some calculations in pandas and my dictionary is way too large to be processed. To give you an idea, one record in the dictionary looks like this: [{'ticker': '24STOR', 'stock': '24Storage AB (publ)', 'exchange__exchange_code': 'ST', 'earnings_yield': Decimal('0.0000'), 'roic': Decimal('0.0000')}] Which I have transformed from a pandas dataframe: ranked_companies = df.to_dict(orient="records") # this is the dictionary with 17000 records I'm then looping through this: stocks_to_upsert = [] for company in ranked_companies: stocks_to_upsert.append( Stock( ticker=company["ticker"], stock=company["stock"], master_id=company["master_id"], exchange=Exchange.objects.get(exchange_code=company["exchange__exchange_code"]), earnings_yield=company["earnings_yield"], roic=company["roic"], roic_rank=company["roic_rank"], ey_rank=company["ey_rank"], sum_rank=company["sum_rank"], latest_report=datetime.strptime(company["latest_report"], "%Y-%m-%d").date() ) ) And then using a django package to bulk upsert these records: Stock.objects.bulk_update_or_create( stocks_to_upsert, ["ticker", "earnings_yield", "roic", "roic_rank", "ey_rank", "sum_rank", "latest_report"], match_field="master_id" ) I'm maxing out on my heroku memory and I somehow need to optimize the ranked_companies dictionary (I assume thats where the issue is). Everything is working fine If I limit the dictionary: df.head(100).to_dict(orient="records") # this executes just fine df.to_dict(orient="records") # this makes me run out of memory in my heroku logs # error looks like this: Error R14 (Memory quota exceeded) Any idea on how to proceed? -
counting number of file downloads in django
I have a link that lets the user download a file. something like this <a href="{{x.image.url}}" download="none">Get</a> Now I want to find a way to keep track of number of downloads. I have model like this with a downloads object to keep count of them. class Photo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to="home/images") downloads = models.PositiveIntegerField(default=0) def __str__(self): return str(self.id) So, I just want to know if there is a way to update the downloads object whenever a user presses the download link. Thankyou! -
How to create and update products to a REST API from Angular
I am new to and currently working on a Django and Angular webapp and I cant seem to be able to create and update my products from the angular web app and send them to the REST API to update the server. I have written a delete function and service request that works and I can retrieve the products from the API but I don't know how to write the functions for create products and update products. Would anyone be able to help me here? Here is what I have so far: api.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http' import { Product } from './models/Product'; import { CookieService } from 'ngx-cookie-service'; import { Category } from './models/Category'; import { Shop } from './models/Shop'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { baseUrl = 'http://127.0.0.1:8000/'; baseProductUrl = `${this.baseUrl}app/products/` baseCategoryUrl = `${this.baseUrl}app/categories/` baseShopUrl = `${this.baseUrl}app/shops/` headers = new HttpHeaders({ 'Content-Type': 'application/json', }); constructor( private httpClient: HttpClient, private cookieService: CookieService, ) { } /** Product CRUD */ /** ADD: add a product to the server */ addProduct(): Observable<Product> { const productUrl = `${this.baseProductUrl}` return this.httpClient.post<Product>(productUrl, {headers: this.getAuthHeaders()}) } /** DELETE: … -
Django Summernote wont get configured on pythonanywhere
I have installed django summernote locally with a virtualenv But on the server I havent created a virtualenv I am getting the following error on pythonanywhere: ModuleNotFoundError: No module named 'django_summernote' Summernote installs fine on pythonanywhere but I still get No module named 'django_summernote' I have included the 'django_summernote' in installed apps. What is the problem? -
Couldn't connect the list view to HTML file in Django
Couldn't connect the list view to HTML file in Django. models.py class AccountList(models.Model): name=models.CharField(max_length=200) paltform=models.CharField(max_length=200) username=models.CharField(max_length=200,null=True,blank=True) password=models.CharField(max_length=200) comments=models.TextField() def get_absolute_url(self): return reverse("accdetail",kwargs={'pk':self.pk}) def __str__(self): return self.name views.py class Account_list(ListView): model=AccountList def get_queryset(self): return AccountList.objects.all() AccountList_list.html {% extends 'PasswordSafe/base.html' %} {% block content %} <div class="centerstage"> {% for acc in acc_list %} <h1><a href="{% url 'accdetail' pk=post.pk %}">{{ acc.name }}</a></h1> {% endfor %} </div> {% endblock %} urls.py from django.conf.urls import url from . import views urlpatterns=[url(r'^$',views.HomePageView.as_view(),name="hmpage"), url(r'^accountlist/',views.Account_list.as_view(),name="acc_list"), url(r'^newsafe/',views.NewSafe.as_view(),name="new_safe"), url(r'^accdetail/(?P<pk>\d+)$',views.AccDetail.as_view(),name="accdetail"), url(r'^about/',views.AboutPage.as_view(),name="about")] I Don't Know where did i go wrong. -
why this statement 'This field is required.' keep displays in my webpage
my webpage why that statement keep displays in my webpage?,i created this webpage using django my html: <form method ='post'> {% csrf_token %} {{form}} <input type="submit" value = "Search"> </form> <form method="POST", enctype="multipart/form-data"> {% csrf_token %} {{forms}} <input type="submit" value="upload"> </form> forms.py from django import forms from .models import EbookModel class SearchForm(forms.Form): pdf_title=forms.CharField(label='pdf_title',max_length=100) class UploadPdf(forms.ModelForm): class Meta: model=EbookModel fields=('title','pdf',) -
KeyError when Deploying project to google cloud
I'm trying to deploy my django+postgreSQL project to GCP by following this guide https://codeburst.io/beginners-guide-to-deploying-a-django-postgresql-project-on-google-cloud-s-flexible-app-engine-e3357b601b91 I came to the point where I was going to write this command "./manage.py collectstatic" but I get a KeyError. I think it is because I'm not using conda but instead I'm using venv(?). This is my error: File "C:\Users\xxxxxxxx\settings.py", line 12, in DEBUG = os.environ['DEBUG'] =='True' File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\lib\os.py", line 681, in getitem raise KeyError(key) from None KeyError: 'DEBUG' Is there a way to follow the guide without using conda? I'm very new to this so I'm sorry if my explaining is bad. -
How to avoid seeing sensitive user data in django admin page?
I have done a django web app in which users can input some data. I have created a super user and as the admin of the app I can see the data input by users which is fine for name and not sensitive data but I do not want to be able to see their sensitive data such as health data. I have used the encrypt module from django_cryptography.fields as follow: health_data = encrypt(models.IntegerField(default=140)) I figured out that if I am looking at the database from external script or simple DBbrowser, it works well as I cannot see the sensitive data. But I understood that this is seamless in the django admin: in django admin page it is decrypting before it is rendered. So I am ok with the encrypt data which is additional safety but this was not my first goal. I want to have the super user but I want that I am not able to see their sensitive data. Do you have any ideas ? I appreciate your time reading. -
How to properly use Django ORM Count with shopping cart
I have such models structure and I need to get information about how many pizzas was ordered. I did something like this PizzaOrder.objects.all().values('pizza').annotate(total=Count('pizza')). It works fine for orders where count in PizzaOrder equals to 1, but if count more than 1, it displays wrong count number. So I want somehow to connect Django Count with my field count in order to know how many pizzas was ordered. models.py class Pizza(models.Model): name = models.CharField(max_length=256) class Order(models.Model): order_number = models.IntegerField(primary_key=True) pizzas = models.ManyToManyField(to='Pizza', through='PizzaOrder') class PizzaOrder(models.Model): pizza = models.ForeignKey( to=Pizza, on_delete=models.PROTECT, ) order = models.ForeignKey( to=Order, on_delete=models.PROTECT, ) count = models.SmallIntegerField() -
Django Project validity
Is my Django based project valid if I don't use Django HTML and instead use simple HTML? Django would be used for the backend still. But for the frontend I am using plain HTML and bootstrap. So would it be valid? -
Django: Inline admin with 'detail'
I'm trying to build a Django App for fish farmer. Farmer(s) will access it using their smart phone. So readability will effected by phone's screen size (mostly 7") Here is my models.py from django.contrib.auth.models import User from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Pond(models.Model): name = models.CharField(max_length=20,) def __str__(self): return self.name class Food(models.Model): name = models.CharField(max_length=20,) def __str__(self): return self.name class Production(models.Model): pond = models.ForeignKey(Pond, on_delete=models.CASCADE, related_name='production',) qty= models.PositiveIntegerField(verbose_name='qty of fish', blank=True, null=True) weight = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='Avg. Weight / fish', blank=True, null=True) date_created = models.DateTimeField( verbose_name=("Start Date"), auto_now_add=True, null=True, editable=False,) def __str__(self): return '{} {}'.format(self.pond self.date_created) @property def qty_n(self): return self.mortal.last().qty_n @property def sr(self): return (self.qty_n / self.qty) * 100 class Monitoring(models.Model): production=models.ForeignKey(Production, on_delete=models.CASCADE, related_name='monitoring',) date_created = models.DateTimeField( verbose_name=("Tanggal"), auto_now_add=True, null=True, editable=False,) prevmon=models.ForeignKey('self', on_delete=models.CASCADE, related_name='nextmon', editable=False, blank=True, null=True) dead= models.PositiveIntegerField(blank=True, null=True) food= models.ForeignKey(Food, on_delete=models.CASCADE, related_name='monitoring', blank=True, null=True) foodqty=models.PositiveIntegerField(blank=True, null=True, verbose_name='Food (grams)') ph = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='Avg. Weight / fish', blank=True, null=True) @property def qty_n(self): # Current number of fishes if prevmon == None: qty_s = self.production.qty else : qty_s = self.prevmon.qty_n return qty_s-self.dead @property def t_dead(self): # Total …