Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to build custom url with GET PARAMETERS in Django template?
I am trying to build a simple e-commerce website and now I am stuck. I want to define href attribute of anchor tag where it should point to url like: /abc?param1=value1 but it should also make sure that if my current url already is /abc/param1=somevalue then it should update the url to /abc/param1=value1. Now, another problem is that the href should be able to handle multiple params like: /abc?param1=value1&param2=value2... I cannot find a topic to solve this. Please help. -
Disable Djongo '__schema__' collection
Hi I know that djongo create the 'schema' collection to autoincrement the django ids but on my project, I use mongodb ids as django ids : from djongo import models from django.utils.timezone import now class Station(models.Model): _id = models.ObjectIdField(db_column='_id', primary_key=True) name = models.CharField(max_length=50, blank=False, default='', unique=True) last_update = models.DateTimeField(default=now) So I just do't have autoincrement fields and the 'schema' collection is useless. however, it still create it, I just wanna know if there is a way to delete it or at least disable it thx -
Django Pagination by Queryset
I'm implementing pagination based on a filtered query, it works okay before clicking on a page number but after clicking on a page number it shows all the objects including the ones which have not been filtered. Started occurring after upgrading to the lastest version of django. Pagination before clicking. Pagination after clicking on page 2. The fitered objects are 4 and given 2 items per page paginator the pagination should stop at Page number 2 but it is showing a new paginator with all the objects even the ones not filtered. Below are some snippets. Any help would be greatly appreciated. Views.py def searchPropertyListView(request): city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") categories = Category.objects.all() purposes = Purpose.objects.all() featured = list(Property.objects.filter(featured=True)) shuffle(featured) querySet = Property.objects.all() city_or_neighborhood = request.GET.get('city_or_neighborhood') category = request.GET.get('category') purpose = request.GET.get('purpose') if city_or_neighborhood != '' and city_or_neighborhood is not None: querySet = querySet.filter(Q(city__title__icontains=city_or_neighborhood) | Q(neighborhood__title__icontains=city_or_neighborhood) ).distinct() elif category != '' and category is not None: querySet = querySet.filter(category__title=category) elif purpose != '' and purpose is not None: querySet = querySet.filter(purpose__title=purpose) paginator = Paginator(querySet, 2) page = request.GET.get('page') try: querySet = paginator.get_page(page) except PageNotAnInteger: querySet = paginator.get_page(1) except EmptyPage: querySet = paginator.get_page(paginator.num_pages) context = { 'city': city, 'featured': featured, 'querySet': querySet, … -
Getting date from a date picker template in Django's function based view
I am trying to get the date-time from the user and save it into the database. my template: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Static Example</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- Font Awesome --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script> <!-- Tempus Dominus Bootstrap 4 --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script> </head> <body> <form method="post" class="col-xl-3 mx-auto my-5"> <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" name="mycustomdate" data-target="#datetimepicker1"/> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <button type="submit" class="btn btn-primary my-3">Submit</button> </form> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> </body> </html> my models.py: class ABC(models.Model): union_date = models.DateTimeField(blank=True) now I want to take users inputed data and save it in my database by a function-based view with a post method like this: if request.method == "POST": this_mycustomdate = request.POST['mycustomdate'] ABC.objects.create(mycustomdate=this_mycustomdate) ABC.save() but it is not working, how can I fix it?