Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-CMS plugin second page
I am developing a Django-CMS plugin for my site. It should give the user the oportunity to choose between social networks on the first page(for now it's Instagram, Facebook, Twitter and Other). And after that, it should have a 'next' button, instead of a 'save' button which will lead to the second page. For example, in the second screenshot you could see how second page should look if 'Other' is choosen on the first page. First page Second page How can I implement that? -
Can you help me with my Django application, how it should start?
I need to connect to api on another server, download data (e.g. once a day) to my own server, process it and save it in another table in the database using the django rest framework. What should I do at the beginning. do you have any advice or tools that i can use? I am a beginner in this. Thank you in advance for your answer -
Django form with redirect that is callable on each page
I have a search box that can redirect the user to several pages, based on the input. When i m put the searchbox on 1 specific page called "zoek", it works fine: def zoek(request): if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): q = form.cleaned_data["SearchQuery"] for result in util.list_entries(): if q.capitalize() == result: return HttpResponseRedirect(reverse("entry", args=[result])) return HttpResponseRedirect(reverse("searchresults", args=[q])) return render(request, "encyclopedia/zoek.html", { "form": SearchForm(), }) However, I want to put this searchform in a sidebar that is included on every page. The sidebar is constructed in a base called layout.html: {% load static %} <form action="{% url 'index' %}" method="post"> {% csrf_token %} {{ searchform }} <input type="submit" value="search"> </form> But I cannot return redirects on the layout. I tried using a custom context processor, but found out those are not suited for this. How could I make sure this form functions on every page that extends layout.html? -
What can slow down an ajax call?
I know I might get slammed for this because I cannot give a case that others might duplicate. However I have a problem and being fairly new to ajax I don't know where to turn I am using ajax to fire a django GET and the django response is almost instantaneous, the ajax function takes about 2 seconds to fire views.py class NewBoard(View): @staticmethod def get(request, board_selector): context={} print('NewBoard') return JsonResponse(context, safe=False) script.js function getNewBoard(board_selector) { setWaitCursor('wait') $.ajax( { type: "GET", url: 'new-board/'+board_selector, cache: false, success: function () { console.log('x') displayBoard(); } } ); console.log('a') setWaitCursor('default') } function displayBoard() { console.log('c') } When this runs, 'NewBoard' and 'a' appear in some fast sub-second time, but 'x' and 'c' do not appear until about 2.5 seconds later. I have other similar functions that work perfectly. Maybe I am doing something fundamentally wrong, but if not where can I start to look for a way to speed this up? -
About tensorflow installation
I am working in django and tf so I have installed different libraries for my project and also now I need to install tensorflow into the same environment but when i tried doing so it raised some ereo after some search i found solution to downgrade the python to 3.7 from 3.8 but while doing so I ran into frozen problem any solution. ? -
DRF: SQL server unmanaged model with period columns
In Django, I have an unmanaged model named Client like this class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=40) sys_start_time = models.DateTimeField(db_column="SysStartTime") sys_end_time = models.DateTimeField(db_column="SysEndTime") class Meta: managed = False db_table = "client" and I would like to have some basic APIs to CURD, currently using RetrieveUpdateDestroyAPIView form DRF's generic views. class GetUpdateDeleteClient(RetrieveUpdateDestroyAPIView): authentication_classes = [...] # omitted permission_classes = [...] # omitted serializer_class = ClientSerializer lookup_url_kwarg = "client_id" lookup_field = "id" I can get a client object without any problem but when I make PUT or PATCH calls to update values, an error is raised: django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot update GENERATED ALWAYS columns in table 'dbo.client'. (13537) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") Problem is that, sys_start_time & sys_end_time are period columns, and as described in MS sql doc: However, you cannot update a PERIOD column and you cannot update the history table. But I cannot figure out if there is a way to let django not send all columns when performing create and update. Goal: I would like to send GET calls to retrieve all information including these period columns, but I don't … -
Couldn't import Django
I am trying to run django from virtualenv but i am getting this error: Error Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django.core' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 17, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtu? ( when i imported django from python shell,i got this: ModuleNotFoundError: No module named 'django.core' i checked if django is installed. (welpieenv) root@li2180-35:~/welpie# source welpieenv/bin/activate (welpieenv) root@li2180-35:~/welpie# pip install django Requirement already satisfied: django in ./welpieenv/lib/python3.7/site-packages (3.1.6) Requirement already satisfied: sqlparse>=0.2.2 in ./welpieenv/lib/python3.7/site-packages (from django) (0.4.1) Requirement already satisfied: asgiref<4,>=3.2.10 in ./welpieenv/lib/python3.7/site-packages (from django) (3.3.1) Requirement already satisfied: pytz in ./welpieenv/lib/python3.7/site-packages (from django) (2021.1) (welpieenv) root@li2180-35:~/welpie# pip3 install django Requirement already satisfied: django in ./welpieenv/lib/python3.7/site-packages (3.1.6) Requirement already satisfied: sqlparse>=0.2.2 in ./welpieenv/lib/python3.7/site-packages (from django) (0.4.1) Requirement already satisfied: pytz in ./welpieenv/lib/python3.7/site-packages (from django) (2021.1) Requirement already satisfied: asgiref<4,>=3.2.10 in ./welpieenv/lib/python3.7/site-packages (from django) (3.3.1) As you guys can see virtualenv is … -
Custom filter not working in django rest framework
I made a custom filter named Productfilter and imported it to my views. It was working until a few days ago but now has stopped working totally. I tried to pass the query parameters included in the filter, but all the objects are shown as if no query parameters are included in the API endpoint. My view: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductSerializer # filter_backends = [DjangoFilterBackend] filterset_class = ProductFilter My filter: from django_filters import rest_framework as filters from ..models import * class ProductFilter(filters.FilterSet): price = filters.RangeFilter() class Meta: model = Product fields = ['price','availability', 'warranty', 'services', 'brand__id','category__id','collection__id'] My urls: path('api/products', views.ProductAPIView.as_view(), name='api-products'), My serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'category','brand','collection','featured', 'best_seller','top_rated','name', 'description','picture','price','size', 'color','quantity','availability','warranty', 'services', ] # lookup_field = "slug" depth = 1 -
Prefetch queryset when related_name="+"
Is it possible without related name (related_name="+") to prefetch objects on the target instance? Sure I know it's not a problem with the related name, but I'm not really sure if it's possible without it. Here is the example code: from django.db import models class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): parent = models.ForeignKey(to=Parent, related_name="+", on_delete=models.CASCADE) Parent.objects.all().prefetch_related('child_set') Maybe it's possible using the Prefetch(lookup, queryset=None, to_attr=None) object, because it takes the queryset in the argument list? -
Django type error: excepted string or byte types like object?
When I tried to publish blog an exception occurs "excepted string or bytes type object".I tried a lot but I don't know how to fix this . What I understand is that it is occuring because DateTimeField(default=timezone.now). I'm correct? This is the error I m getting on writing py maname.py runserver: File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python parsed = parse_datetime(value) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object [] "GET / HTTP/1.1" 500 139276 Not Found: /favicon.ico [] "GET /favicon.ico HTTP/1.1" 404 4283 Here is models.py:- from django.db import models from django.utils import timezone from django.urls import reverse class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title=models.CharField(max_length=200) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) published_date=models.DateTimeField(blank=True,null=True) def publish(self): self.published_date=timezone.now self.save() def approve_comments(self): return self.comments.filter(approve_comments=True) def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post=models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author=models.CharField(max_length=200) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) approve_comment=models.BooleanField(default=False) def approve(self): self.approved_comment=True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text Here is views.py:- from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.forms import PostForm,CommentForm from blog.models import Post,Comment from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView,DetailView, CreateView,UpdateView,DeleteView) class AboutView(TemplateView): template_name='about.html' class PostListView(ListView): model=Post #generating a query to db (so this means that grab all … -
uwsgi static files loading error form django (react and webpack)
My app consists of django and react, which at the end is bundled to static (.js) file. My goal is to setup a nginx for it, but for now I just want to run in uwsgi to see if it works. Aaaaand it does not work at all. I belive there is a issue with loading this bundle file which webpack is compiling. Connection to uwsgi works, server is up and running, but when connecting to 127.0.0.1:8080 I get (in Mozilla): The resource from “http://127.0.0.1:8080/static/frontend/main.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). # and another GET http://127.0.0.1:8080/static/frontend/main.js HTTP/1.1 404 Not Found Content-Type: text/html X-Frame-Options: DENY Content-Length: 3277 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Vary: Origin Similar topic I found: Difference between static STATIC_URL and STATIC_ROOT on Django and this: Django + React The resource was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) But messing with python manage.py collectstatic resolved nothing. I have this lines of code to manage static files: STATIC_URL = '/static/' STATIC_ROOT = os.path.join('/app/label_it/front/static/frontend/') And this is how I start my uwsgi connection: python manage.py collectstatic --no-input uwsgi --http 0.0.0.0:8080 --master --enable-threads --module label_it.wsgi Beside collectstatic I've tried messing with <script src"static_file_path"></script> this static path … -
Django - Submit data from a HTML table into database
I am creating a restaurant application and I am currently trying to implement 'confirm order' functionality. I have rendered objects from my database onto a template, as each item is rendered, I assign a "Add to Basket" button that will do exactly that. The add to basket functionality works perfectly. Now, I am wondering how I can pass the data within my 'basket' (html table) to my database. I have found that I need to assign unique 'names' to each object that is being rendered in order to get them in views.py. I have done so. But how can I know which unique values that user has selected within the table? Is it possible to get the quantity and price fields as well? I believe forms will have to be used, but I am not sure how to go about it. takeaway.js function addToBasket(selected) { const itemDiv = selected.parentElement.parentElement; const itemName = itemDiv.getElementsByClassName("food-item-name")[0].innerText; const itemPrice = itemDiv.getElementsByClassName("food-item-price")[0].innerText; // check if item already in basket if (check(itemName)) { updateQuantity(itemName); updateItemPrice(itemName); } else { const basketTable = document.getElementById("basket"); const rowCount = basketTable.rows.length; const row = basketTable.insertRow(rowCount); const basketRowName = row.insertCell(0); const basketRowQuantity = row.insertCell(1); const basketRowPrice = row.insertCell(2) const basketRowTotalPrice = row.insertCell(3); … -
Can I change to a CustomUser model after the initial migration? Or I should've done it at the start of the project?
I'm trying to add custom user model mid project, and I might remember reading somewhere that you can't do that or that it isn't easy to do so, is that true? What can I do now? -
Can someone explain how to deploy django application on linux server inside my organization?
Can someone help me with the step by step process to be followed using nginx and gunicorn / or some other easier method,or some usefull links so that i can follow. Thanks in advance ! -
Django: Iterate on inlineformset_factory - update existing model's fields
I have a project that includes several "list" models, and multiple "list item" models for each list. Here are my models: class List(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class ListItem(models.Model): team_list = models.ForeignKey(List, on_delete=models.CASCADE) content = models.TextField() list_index = models.IntegerField() def __str__(self): return f"{self.team_list} [{self.index}]" the "list index" field is for use in another feature of my project. Essentially, each item in the list will have an index number 1 - whatever the total number of items in the list are. This list index number is where I'm running into trouble. I am working on a list edit view where the user can add additional items to the list. Here is my urls: urlpatterns = [ path('edit_list/list<int:list_pk>/', views.edit_list, name='edit_list'), ] and here is the corresponding view: def edit_list(request, list_pk): theList = List.objects.get(pk=list_pk) listForm = EditListForm(instance=theList) listItemForm = inlineformset_factory(List, ListItem, fields=('content',)) context = { 'title': 'Edit List', 'list_form': listForm, 'list_item_form': listItemForm(instance=theList), } if request.method == 'POST': listForm = EditListForm(request.POST) listItemForm = listItemForm(request.POST, instance=theList) if listForm.is_valid and listItemForm.is_valid: listItemInstance = listItemForm.save(commit=False) index = 1 for form in listItemInstance: form.list_index = index index += 1 listItemForm.save() listForm.save() messages.success(request, "List has been updated!") return redirect('home') else: messages.error(request, 'Something went wrong...') return render(request, … -
javascript and django views not updating shipping cart if user not logged in
Following a YouTube tutorial on making an ecom app and everything seems ok except that when I sign out it won't add items to cart although the logic is there for anonymous users. Once user is logged in everything works great. when I call the url on chrome it gives me this error: JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0) here is the javascript snippet: for(var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action', action ) console.log('USER:', user) if(user == 'AnonymousUser'){ console.log('Not logged in') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json(); }) .then((data) =>{ console.log('data:', data) location.reload() }) } I get this on firefox console when I try to add items to cart manually (user not logged in): productId: 1 action add cart.js:8:17 USER: AnonymousUser cart.js:10:17 Not logged in The django view responsible for this part: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('action:', action) print('productId:', productId) customer = request.user.customer … -
SyntaxError in Python3.9 datetime.py
I have Python 3.9 (/usr/bin/python3.9) with Django 3.1.6 and with Apache2 want to run my application. But on the browser is error 500 Internal Server Error and in log of Apache I'm getting SyntaxError in datetime.py: mod_wsgi (pid=25852): Target WSGI script '/path/to/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=25852): Exception occurred processing WSGI script '/path/to/wsgi.py'. Traceback (most recent call last): File "/path/to/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/usr/lib/python3.9/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/usr/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module> import datetime File "/usr/lib/python3.9/datetime.py", line 889 raise ValueError(f'Invalid isoformat string: {date_string!r}') ^ SyntaxError: invalid syntax I'm already desperate. -
PageNotAnInteger at /products/ That page number is not an integer
So I'm trying to use pagination in django, When I click on previous it takes me to localhost:8000/thatpage/?page= when it is supposed to take me to the previous page, It also gives me error on that page. I have tried handling it in my views.py but it doesn't work. I have also tried using books_obj.previous_page_number but that doesn't work too. I'm using Django 3.1 views.py def showproducts(request): oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) category = Category.objects.all() haha = Paginator(Book.objects.all(), 2) page = request.GET.get('page') if page is None or "": page = 1 fianlprice = 0 for item in hehe: fianlprice += item.book.price # books = Book.objects.all() books = haha.page(page) return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category}) products.html <h1>Products</h1> <h1>{{ error }}</h1> {% if user.is_authenticated %} <h1>Your cart currently costs ${{ price }}</h1> {% else %} <h1>Please login to view your cart</h1> {% endif %} <form method="GET" action="/search/"> <label>Choose a category</label> <select name="category" id="category"> <option value="All" selected>All</option> {% for name in category %} <option value="{{ name.name }}">{{ name.name }}</option> {% endfor %} </select> <input type="text" placeholder="Search here" name="search" id="search"> <button type="submit">Search</button> </form> {% for book in books %} <a href="{% url 'detailview' book.id %}"><h3>{{ book.name … -
Get a django instance that is selected with the mouse
I define in django a class called Scenario. The view of Scenario is this: If you want to use the button called "Check Issues", you have to click with your mouse on one scenario, in this case you only can click on "s1" or "s2". The button call a python function called gen_issues, here is the code: def get_urls(self): urls = super().get_urls() my_urls = [ django.urls.path('issue/', self.gen_issues), django.urls.path('duplicate/', self.gen_duplicate), ] return my_urls + urls def gen_issues(self, request): if len(request.user.username) > 0: queryset=super().get_queryset(request) #scenarios = Scenario.objects.filter(user=request.user.username) if len(queryset) == 1: sv = ScenarioVerifier(queryset[0]) sv.verify() return HttpResponseRedirect("../") else: self.message_user(request,len(queryset) ,level=messages.ERROR) return HttpResponseRedirect("../") But It doesn't work because I don't know how to get the clicked scenario, so the queryset in the function "gen_issues" is wrong beacuse it has two elements, i.e, all the scenarios, not the selected with the mouse. So my question is how can get the selected scenario with the mouse in order to can use it inside my function. -
In Django, what is the difference between Trunc and Extract Django database functions?
In Django what is the difference between using Trunc and Extract functions on datetime fields in queries? For example, is there a difference between TruncYear() and ExtractYear()? Are the edge cases handled the same? When should one be preferred over the other? -
csrf_exempt set but CSRF Failed: Referer checking failed - no Referer
I have a backend API, it's in django and deployed on Google Endpoint. I have a post request that insert data to my DB. I created a script to use this endpoint but I got this error: {"detail":"CSRF Failed: Referer checking failed - no Referer."} Regarding over posts I added the crsf_exempt decorator to my class but it did not change. I try to add the decorator two ways: class AddUser(APIView): """ Create user and company from csv """ @method_decorator(csrf_exempt) def post(self, request): @method_decorator(csrf_exempt, name='dispatch') class AddUser(APIView): """ Create user and company from csv """ def post(self, request): But both failed. This is how I contact my endpoint: resp = requests.request( method, url, headers={'Authorization': 'Bearer {}'.format( open_id_connect_token)}, **kwargs) Any ideas ? Thanks -
How to store password of user id (from user model) in another separate table and maintain one to one relation between those table based on userid
How to store password of user id (from user model) in another separate table(say password_table) and maintain one to one relation between those table based on userid # -
get django variable by javascript variable
I want to get variable stored in Django admin by using JavaScript variable for ex: var x = 2; console.log("{{product.0}}") //by this I get data from admin console.log( "{{product." + x + "}}" ) //but by this it shows couldn't parse reminder +x+ I want that I get my data by using that x variable -
how to get user based on username?
How can i get the user profile based on his username not id , i tried with only slug_filed it shows me that there is no username choice , and i made this get object method but it didn't work views.py class ProfileDetail(DetailView): model = Profile template_name = 'profile.html' slug_field = "username" def get_object(self): username = self.kwargs.get('username') return get_object_or_404(User, username=User.username) models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() picture = models.ImageField(upload_to='profile_pics') def __str__(self): return str(self.user) def save(self, *args, **kwargs): super().save(*args, **kwargs) urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from users.views import register, UpdateUserView, ProfileDetail from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('register', register, name="register"), path('accounts/', include('allauth.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('settings', UpdateUserView.as_view(), name='settings'), path('profile/<slug>', ProfileDetail.as_view(), name='profile'),] -
How to set a string value to django model Id?
I am new to web development. I want to manually define the identifiers of a model. So I add "id = models.AutoField (primary_key = True)" in my model class: mymodel class (models.Model): id = models.AutoField (primary_key = True) When trying to set a string id I got the following error: The "id" field was expecting a number but got "Activity_0m91i8s". Activity_0m91i8s is the string id Is there a way to define the id string? Thank you