Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django only show first POST element in loop
I have simple library page that user can register, add and edit\delete records from library. Template.html {% extends "book/base.html" %} {% block content %} <div class="row justify-content-center mt-5"> </div> {% if books %} {% for book in books %} <div class="table-users"> <div class="header"> {{ book.title }} </a> </div> <table cellspacing="0"> <tr><center> <th>Name</th> <th>Author</th> <th>Delete</th> </center> </tr> <td> {{ book.name }} </td> <td> {{ book.author }} </td> <td> <form class="delete" method="POST" action="{% url 'deletebook' book.id %}"> {% csrf_token %} <button class="delete" type="submit" class="btn btn-warning">Delete</button></td> views.py: def deletebook (request, book_pk): book = get_object_or_404(Book, pk=book_pk, user=request.user) if request.method == 'POST': book.delete() return redirect('currentbooks') With this loop only first element of POST method is active and working. Actually I'd debuggging html after rendered and i've seen that theres a only first element has a POST method. I searched on google and on stackoverflow and found something about the change id to class. But my template doesnt have any id. I also tried to move {% csrf_token %} outside of the loop but it doesnt work either. I think so, i missed something important here. I really appreciate if someone could help me out. Thank you in advance. -
Elasticsearch Default Settings in Django
In Django I can connect elastic_search = Elasticsearch(['http://elastic:elastic@localhost:9200/'], verify_certs=True) if elastic_search.ping(): # No problem! What I want is, I want to add this connection information to settings.py... ELASTICSEARCH_DSL = { 'default': { 'hosts': 'elastic:elastic@localhost:9200' }, } and call Elasticsearch this way: elastic_search = Elasticsearch() But this doesn't work. Ping only returns false. I also tried to add 'verify_certs': False to the settings but no chance. Is there a way to run Elasticsearch() function directly? -
Get all related objects with filter on through model
I have the next database structure: class Artwork(): id = models.IntegerField(_('id'), primary_key=True) artists = models.ManyToManyField('gql_service.Artist', through='gql_service.ArtistArtwork') class ArtistArtwork(models.Model): artist = models.ForeignKey('gql_service.Artist') artwork = models.ForeignKey('gql_service.Artwork') is_main_artist = models.BooleanField(default=False) class Artist(models.Model): id = models.IntegerField(_('id'), primary_key=True) is_main_artist feature flag used to define is this artist main for this artwork. In ArtworkNode I want to define main_artist field: class ArtworkNode(PrimaryKeyMixin, DjangoObjectType): main_artist = graphene.Field('escher.gql_service.schema.artist_node.ArtistNode') def resolve_main_artist(self, _): return ArtworkInfo(self).main_artist And then in the ArtworkService I can access artwork artists like: class ArtworkInfo(object): @property def main_artist(self): artist = self.artwork.artists.first() return artist Is there any way I can filter artists on ArtworkInfo and get only one main artist? -
Django Select2MultipleWidget leads to form continuously trying to load
I'm trying to incorporate Select2 into my django form -- specifically ModelSelect2MultipleWidget -- so that the user can associate multiple event objects to another model (like CheckboxSelectMultiple). The associated models are: from django.contrib.auth import get_user_model from django.db import models class F4Events(models.Model): name = models.CharField(max_length=300) handling_type = models.ManyToManyField(WaferHandlingType) def __str__(self): return self.name class ToolPm(models.Model): ceid = models.ForeignKey(CEID, on_delete=models.CASCADE) name = models.CharField(max_length=250) wafer_handling = models.BooleanField(default=True) wafer_based = models.BooleanField(default=False) frequency = models.FloatField(blank=True, null=True) handling_type = models.ManyToManyField(WaferHandlingType, blank=True) user_edited = models.BooleanField(default=False) pm_f4_events = models.ManyToManyField('F4Events', blank=True) def __str__(self): return str(self.name) if self.name else '' class Meta: ordering = ('ceid', 'name') My forms.py file is: from django import forms from .models import Entity, ToolPm, CEID, PDL, F4Events, WaferHandlingType from django_select2 import forms as s2forms class F4EventWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ 'name__icontains', ] attrs = {'data-placeholder': 'Please Choose F4 Events'} class PMForm(forms.ModelForm): class Meta: model = ToolPm fields = ['wafer_handling', 'wafer_based', 'handling_type', 'pm_f4_events'] widgets = {'handling_type': forms.CheckboxSelectMultiple, 'pm_f4_events': F4EventWidget } my view.py is: from datetime import datetime, timedelta from django.db.models import Sum from django.http import JsonResponse, HttpResponseRedirect from django.http.response import HttpResponse from django.shortcuts import render, get_object_or_404, redirect from django.views import View from django.views.generic import ListView from django_filters.views import FilterView from pages.filter import CeidFilter, PmRunDateFilter from tools.forms import EntityForm, … -
I want to make django chat application
I want to make a django chat app but I searched hours and I couldn't find how , youtube tutorials use react and I don't know react js Pls give me a way to study on how to make it and where to get it Done through official django docs but got errror with redis... It would be kind if you also can tell me about the steps involved in making.... -
How zero or many, one or many, zero or one are crated in django?
I have a Vacancy that can have zero or many Benefits and currently use a ManytToMany in Vacancy like this: class Vacancy(models.Model): benefits = models.ManyToManyField(Benefits) My question is how can I define that there is a possibility that a Vacancy has no Benefit? And how can I define that it must have at least one benefit? How does this apply to OneToOne and ForeignKey relationships in django? -
Can you make a view that redirects the user to another app based on a random variable?
as the title says, I want to create a functions that redirects the user to another app based on a random variable. I created a function and gave a random value to a variable that calls the corresponding view of another app, but only the first value of the random range works fine, while the other get an error at the form validation. -
Handling user choice with conditional logic in Jinja template (caesar cipher Django web app)
I’m writing a Django web app which basically presents the web visitor with the option to encrypt / decrypt a message using a very rudimentary caesar cipher. I got the encryption function to work but when I tried to implement conditional logic in my template to handle the user’s initial choice on the landing page (the option to encrypt or decrypt), Django is not serving the client the option. I’m not sure why. I’m expecting Django to give the web visitor this choice on the landing page: Would you like to encrypt a plaintext message? Or would you like to decrypt a scrambled message? (...where each question is a hyperlink that takes the visitor to a page to enter their message). When the web visitor lands on the page, neither option is showing. Django just serves a blank template. Here is a temporary mirror of my dev server: https://d0d342ea4934.ngrok.io Here is my views.py: from django.shortcuts import render import string def caesar(request): # Courtesy of Real Python: https://realpython.com/python-practice-problems/ if 'encrypt' in request.GET: plain_text = request.GET['original_entry'] shift_num = request.GET['shift_num'] shift_num = int(shift_num) letters = string.ascii_lowercase mask = letters[shift_num:] + letters[:shift_num] trantab = str.maketrans(letters, mask) output_text = plain_text.translate(trantab) context = {'select_option': False, 'output_text': … -
Using modelForm with CreateView
I have a problem with CreateView. My code is a bit of a frankenstein monster with code from various tutorials, docs, and stackoverflow. I feel like I have misunderstood some fundamental step in the workflow. Here is the models.py: class Customer(models.Model): name = models.CharField(max_length=200, null=False, blank=False) phone = models.CharField(max_length=50, null=False, blank=True) Here is the forms.py: class CustomerForm(forms.ModelForm): def clean(self): super().clean() name = form.cleaned_data['name'].upper() form.cleaned_data['name'] = name class Meta: model = Customer fields = ['name', 'phone'] widgets = { 'name': forms.TextInput(attrs={"class": "form-control"}), 'phone': forms.TextInput(attrs={"class": "form-control"}),} Here is the views.py: class CustomerCreateView(LoginRequiredMixin, CreateView): model = Customer form_class = CustomerForm context_object_name = 'customer_create' template_name = 'customers/customer-create.html' login_url = 'account_login' def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) And lastly here is the template: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The problem is that when I hit save the page just refreshes and the new object is not created. What am I doing wrong? -
How can I add column to the admin from other table, that isn't directly connected?
I am trying to add field to admin view, which goes through several tables. Using shell I have no issue getting the result I want, but I don't know how to add that field to the view. I have table meeting, which has foreign key of table person. Table person has many-to-many relationship with table ConditionDict. I wish to use one field from ConditionDict to Meeting view, without their direct link (as from database perspective it seems redundant), but I do not know how to do it. Here is shell I use to go through all these tables which works meeting.objects.filter(id=1).values('person_in_need__person_c__condition__issue') but I do not know how to add the 'issue' field to the meeting model. -
Why MyModel.objects.none() == MyModel.objects.none() returns False in django shell
I have a model named Program in my django project. I entered shell and tested this: Program.objects.none() == Program.objects.none() It is returning False!! Any idea why? -
ValidationError with Datatime field in Django
I am working with the date picker of Tempus Dominus Bootstrap 4 in my Django project. template's date-picker link: Doc in my models.py: class Industry(models.Model): name = models.CharField(max_length=200, blank=True) mycustomdate = models.DateTimeField(null=True, blank=True) in my views.py: if request.method == "POST": this_mycustomdate = request.POST['mycustomdate'] print(this_mycustomdate) Industry_obj = Industry.objects.create(name=this_name, mycustomdate = this_mycustomdate) Industry_obj.save() But it says error like: ValidationError at /industrySignup/ ['“03/04/2021 5:06 PM” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] with the line: Industry_obj = Industry.objects.create(name=this_name, mycustomdate = this_mycustomdate) How can I solve this problem? -
Dynamically inherit class based on parameter to make 2 classes be 1
I am facing this issue that I can't seem to solve by myself. My goal is to create a custom model field based on both FileField and ImageField from django. I also need to add extra parameters (bucket_name, privacy (not mandatory because it has a default fallback)) to handle upload I want to call, in an app's models.py, MyCustomFileField instead of either of the two mentioned above, like this: image = MyCustomFileField( 'Image', upload_to='path', blank=True, null=True, max_length=255, privacy='public', bucket_name='somebucket', file_type='file' # or 'image' ) my custom field logic: class MyCustomFileField(models.FileField): <---- This would need to be dynamic based on kwargs['file_type'] def __init__(self, *args, **kwargs): if 'bucket_name' not in kwargs: raise ImproperlyConfigured( "No parameter `bucket_name` was passed to `%s`" % (self.__class__.__name__) ) if 'privacy' not in kwargs: kwargs['storage'] = storage_backends.PublicMediaStorage(bucket_name=kwargs['bucket_name']) else: if kwargs['privacy'] == 'private': kwargs['storage'] = storage_backends.PrivateMediaStorage(bucket_name=kwargs['bucket_name']) elif kwargs['privacy'] == 'public': kwargs['storage'] = storage_backends.PublicMediaStorage(bucket_name=kwargs['bucket_name']) else: raise ImproperlyConfigured( "Parameter `privacy` only accepts following values: '%s', '%s'" % ('private', 'public') ) kwargs.pop('privacy', None) kwargs.pop('bucket_name', None) super().__init__(*args, **kwargs) I could have two classes, one for each inheritance (ImageField and FileField) but the logic inside the class (where I manage the bucket and the privacy) is so far the exact same. So i'd have … -
How do I make a user pay before creating user account Django
Okay.. so I am trying to create a website where the user would have to pay before registration. Any help please?? The question might be weird but I am actually a beginner -
Exclude specific instance from the field in serialization Django REST API
I want to get the list of user's chats (fields are: chat id, chat participants), but I don't want the user itself to be listed among chat participants (I mean user has to be among chat participants for sure, but there is no need for user to see his own name listed among other names when he requests the list of his chats, as it is pointless). Here is the Chat model: class Chat(models.Model): id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32) chat_participants = models.ManyToManyField(User, blank=True) class Meta: db_table = 'chat' verbose_name_plural = 'chats' Here is Chat serializer: class ChatSerializer(serializers.ModelSerializer): chat_participants = ChatParticipantsSerializer(many=True, read_only=True) class Meta: model = Chat fields = '__all__' PS ChatParticipantsSerializer (which's model is User) is for getting the name and surname of the participants, and not only their id's. Here is the view: class ChatsListAPIView(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = ChatSerializer def get_queryset(self): return Chat.objects.filter(chat_participants=self.request.user.id) PS in get_queryset function I check if the user in the chat group (if he is among the chat participants of the group) Now I get in JSON this: [ { "id": "a38609b1c86f4d71b0b300381db747b4", "chat_participants": [ { "id": "044ad4f8876d4b8bb057a63769a33027", "first_name": "Jean", "last_name": "Mel" }, { "id": "c01473b5d72a4b0ea40a4047ed297d77", "first_name": "Sasha", "last_name": "King" } ] … -
Sniffing Django database query packets
I'm not sure if this is the good place to ask this type of question. I have the following set up: DB_HOST=localhost DB_PORT=5432 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ["DB_NAME"], 'USER': os.environ["DB_USER"], 'PASSWORD': os.environ["DB_PASS"], 'HOST': os.environ["DB_HOST"], 'PORT': os.environ["DB_PORT"], }, } and was able run a query and get the data back: >>> from app1.models import Facility >>> facility = Facility.objects.filter(id=32432148) >>> print("NAME:"+facility[0].algo_name) NAME:FBNR_LE >>> print("FAC_ID:"+facility[0].fac_id) FAC_ID:FBNR_LE_BNS What I want to do is to bascally sniff the DB query packets sent from Django over to Postgresql server. So I run tcpdump for duration of the query: # tcpdump 'tcp port 5432' -w /tmp/tcp_dump.pcap However, the query and the data returned from it can not be found in the output file. Anyone have idea how I can capture and view Django query packets? -
Should I implement the django rest framework above django?
Currently i have a Django blog website. (Fully functional) I have read that django rest framework helps you to serialize your data. Could I just check about the DRF: Is serializing data important? Meaning to say what huge benefits would I get by having an additional django rest framework, and also any possible disadvantages? Would it be very difficult to "add" the framework into my project. Eg does it require me to download a lot of things and change a lot of my codes? Where does DRF stand, is it in the backend of frontend or is it more of like in the middle. How does it integrate into my current IT architecture: with django as backend, htmlcssjs as frontend and postgresql as database Thank you! Also if anyone is kind enough to share resources about DRF/ open to a short zoom sharing session on DRF, please feel free to contact at kimjoowon777@gmail.com -
no 'DATA' attribute in request in my view.py
i'm trying to pass data with js in function UpdateUserOrder $(document).ready(function() { document.querySelectorAll('.update-cart').forEach(item =>{ item.addEventListener('click', () => { var productId = item.dataset.product var action = item.dataset.action if(user === 'AnonymousUser'){ console.log('not logged in') }else{ UpdateUserOrder(productId, action) } }) }) }) function UpdateUserOrder(productId, action){ console.log('user logged in') var url = 'add_to_cart/' 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) }) } {% for product in products %} <div> <label id="title-label" for="title">Title</label> <p id="title">{{ product.title }}</p> <label id="author-label" for="author">Author</label> <p id="author">{{ product.author }}</p> <label for="user">Seller</label> <p id="user">{{ product.user }}</p> <p><img src="{{ product.image }}" alt="none"></p> <a id="link" href="{% url 'market_detail' product.id %}">Details</a> <button data-product="{{ product.id }}" data-action="add" class="update-cart">add</button> </div> {% endfor %} views.py: def home(request): products = Product.objects.filter(sold=False) context = {'products': products} return render(request, 'market/home.html', context) def add_to_cart(request): data = json.loads(request.DATA) productId = data['productId'] action = data['action'] print('action:', action, 'productId:', productId) return JsonResponse('item was added', safe=False) urls.py : urlpatterns = [ path('', home, name='home'), path('detail/<int:pk>/', BookDetailView.as_view(), name='market_detail'), path('search/', book_search, name='book_search'), path('add_to_cart/', add_to_cart, name='add_to_cart'), ] the error i'm getting in my console: and my terminal in pycharm is saying this: AttributeError: 'WSGIRequest' object has no attribute 'data' -
Ajax request lost after changing page
I have an issue with a Django project. I have developped a button which is supposed to generate and download a csv file. The function to achieve that is very long and so I used celery task to avoid monopolizing the server for only one user downloading. To do that I have an ajax function which call api and wait for the end of the generating file. It works fine if the user stay on the same page. <a class="dropdown-item" onclick="exportToExcel('mission', 'man')">TEST</a> function exportToExcel(expt, t){ var selectedTime = $("#weekSelect").children("option:selected").val(); var week = ''; var year = ''; if (selectedTime) { var week = selectedTime.toString().split("/")[0].substring(1); var year = selectedTime.toString().split("/")[1]; } var current_path = location.pathname; var manager = current_path.split("/")[1]; var url = ""; if (week === ""){ url = `/api/export/${expt}-${manager}/${t}/`; } else { url = `/api/export/${expt}-${manager}/${t}/${week}-${year}/`; } console.log(url) $.get(url).done(function ExportAsyncResults(data) { // bind syncResults to itself to avoid clashing with the prior get request context: this // see the URL setup for where this url came from const exportAsyncUrl = `/api/export_async_results/${data.task_id}/` $.get(exportAsyncUrl) .done(function(asyncData, status, xhr) { context: this // if the status doesn't respond with 202, that means that the task finished successfully if (xhr.status !== 202) { // stop making get … -
Getting TypeError at /login/: authenticate() got an unexpected keyword argument 'username'
I am trying to authenticate the user using Django in-built User model. Here is the view of the login page: if request.user.is_authenticated: return redirect('dashboard') usern = '' if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') userinfo = User.objects.filter(email=email) print('entering') for user_det in userinfo: usern=user_det.username print(usern) user = authenticate(request, username=usern, password=password) print(user) if user is not None: print('available') login(request, user) return redirect('dashboard') else: messages.info(request, 'Username or password incorrect') return render(request, 'account/login.html') return render(request, 'account/login.html') After logging in, I am getting the following error: TypeError at /login/ authenticate() got an unexpected keyword argument 'username' I have seen some stack overflow before and they suggested ambiguity issue with a view and auth function naming. I would really appreciate the help. Thanks in advance! -
How to convert for loop to ORM in python django
I have these models: class Employee(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, null=True, blank=True) location = models.CharField(max_length=100, default='Helsinki') experience_brief = fields.RichTextField(null=True, blank=True) image = models.ImageField(upload_to='employees', blank=True, null=True) class ParticipationLog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) employee = models.ForeignKey(Employee, on_delete=models.PROTECT) project = models.ForeignKey(Project, on_delete=models.PROTECT) months = models.IntegerField(blank=True, null=True) skills = models.ManyToManyField(Skill, blank=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) description = fields.RichTextField(blank=True, null=True) class Project(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) description = fields.RichTextField(blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) start_date = models.DateField() end_date = models.DateField(blank=True, null=True) anders_project = models.BooleanField(default=True) skills = models.ManyToManyField(Skill, blank=True) I need to filter employees with their skills and experience (years) like this: filter skill:[python][3y] => Filter people with 3 or more years in python For any skill find projects that have that skill. Then the amount of experience is calculated from: If that log has months field filled => Use that value If participation has a start or end dates => count it from those If nothing, just use the project's start date until this date. I wrote for loop to filter them and it works well: @staticmethod def diff_month(d1, d2): return (d1.year - d2.year) * 12 + d1.month - d2.month … -
Fastest way to getting closest date matches from a django model
I have this function that gets the closest matches for every countryCode (based on a date in epoch time) from a model to a certain given time, dt being the the difference in time, limit being the amount of best matches (but one per country) and max offset being the max amount it can differ from the given date, it's pretty slow right now so I was wondering if there is a faster way to do this. Code: def get_tile_increase(dt=86400, limit = 10, maxoffset=0.1): t = time.time() - dt qer = CountryTilePrice.objects.filter(epochDate__gte=t - dt*maxoffset, epochDate__lte=t + dt*maxoffset) .annotate(abs_diff=Func(F('epochDate') - t, function='ABS')).order_by('countryCode', '-abs_diff').distinct('countryCode') ret = [] for i in qer: ret.append([i.countryCode, CountryTilePriceLatest.objects.get(countryCode=i.countryCode).totalTilesSold - i.totalTilesSold, i.country.countryName if len(i.country.countryName) <= 22 else i.country.countryName[:19] + '...']) ret.sort(key=lambda x: x[1], reverse=True) return ret[:limit] -
Using Oauth2 with Django
I am new to working with Oauth2 and am confused about how refresh tokens are used with Django. I understand the flow of authorization but do not understand the best practice for refreshing a token in Python. I will be using the Calendly API for this app. https://calendly.stoplight.io/docs/api-docs/docs/A-API-Getting-Started.md So in Django, when a user grants access to their Calendly, do I save the access token and refresh token as a field in the database? Is there a library for working with access and refresh tokens, or do I build my own functions? Is this what the request process looks like?: Request to Calendly with Auth token --> check response --> if token expired get new access token --> Make request -
Django with Fetch API
Im trying to send data to my django backend using javascript Fetch API. My current working url is 127.0.0.1:8000/store And im trying to send data to 127.0.0.1:8000/recommend_product/ using fetch as follows var url = '/recommend_product/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId }) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:', data) location.reload() }) } else { alert('Please Login to recommend products') } My problem is that Fetch API redirecting me to '127.0.0.1:8000/store/recommend_product/' instead of 127.0.0.1:8000/recommend_product/. How to fix this? -
Python Django Virtual Environment Configuration?
I am new to using Django, I am currently working on my first project in a virtual environment. I am having trouble working with psycopg2 and pillow. I am using psycopg2 so that I can connect with a postgres database. When I try to use the adapters/modules i get error saying: Error loading psycopg2 module: No module named 'psycopg2' when I try to pip install these tools from my virtual environment, I get message saying: Requirement already satisfied: psycopg2 in /Users/owner/work/anaconda3/lib/python3.8/site-packages At some point, I installed anaconda. I am working with Django in a different virtual environment, so I believe it's getting confused with the "requirement" location of anaconda vs. django virtual environment? Any tips on how to resolve this issue?