Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding custom godaddy domain to railway web app
I deployed my web app on Railway. They gave the following settings: I went to GoDaddy where I bought a custom domain - and it was impossible to enter @ as Name. I called support - their representative entered the following settings himself. But it still doesn't work, 72 hours have passed. How should I resolve this? -
Django Form : cleaned_data.get(field name) is returning None in clean() method
I am following the Django documentation of Django form but unable to understand what is the issue in my code. I am writing the below code in the clean method to check if both name and email starts with lowercase s or not but Django is returning None in cleaned_data.get(field name) method and I am getting "Attribute error" : 'NoneType' object has no attribute 'startswith'. Please help me on this: Reference: https://docs.djangoproject.com/en/4.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other from django import forms from django.core.exceptions import ValidationError class GirlsFeedback(forms.Form): name = forms.CharField(label = 'Enter Your Name', label_suffix = " ", required=True, disabled=False, min_length = 5, max_length = 100, strip=True) password = forms.CharField(label='Enter Your Password', label_suffix = " ", required=True, disabled=False, min_length=8, max_length=10, help_text="Minimum 8 and Maximum 10 characters are allowed.", widget=forms.PasswordInput) email = forms.EmailField(error_messages={'required': 'Email is mandatory'}) def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') email = cleaned_data.get('email') if name.startswith('s') and email.startswith('s') !=True: raise ValidationError('Name and email both should start with a lowercase s') Error: AttributeError at /feedback3/ 'NoneType' object has no attribute 'startswith' Request Method: POST Request URL: http://localhost:8000/feedback3/ Django Version: 4.1.2 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'startswith' Exception Location: C:\Users\singh\Desktop\Journey\Django Journey\Geeky Shows\Eleven\Feedback3\forms.py, line 72, in clean Raised during: Feedback3.views.feedback Python … -
Django TestCase using self.client.post() is sending a GET resquest
I'm creating a integration Test Class. The self.client.get is working fine, but self.client.post is sending GET and I'm receiving a [httpResponse("Method Not Allowed", 405)]. from django.test import TestCase import json class Test_Integration(TestCase): def test_create_exist_product(self): response = self.client.post('http://127.0.0.1:8201/v1/products/create', {"name": "product7", "latest_version": "0"}, follow=True, secure=False) print(response) self.assertEqual(response, "Product name already exists") Function def create_product(request): logger.info("Entering function create_product..") logger.info("REQUEST TYPE: "+str(request.method)) if request.method == "POST": CODE HERE return HttpResponse("Method Not Allowed", 405) Log errors: Found 4 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). INFO 2022-11-16 13:45:12,066 views 13612 19052 Entering function create_product.. INFO 2022-11-16 13:45:12,068 views 13612 19052 REQUEST TYPE: GET <HttpResponse status_code=200, "405"> ====================================================================== FAIL: test_create_exist_product (project.Tests.test_integration.Test_Integration) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\backend\project\Tests\test_integration.py", line 23, in test_create_exist_product self.assertEqual(response, "Product name already exists") AssertionError: <HttpResponse status_code=200, "405"> != 'Product name already exists' ---------------------------------------------------------------------- Ran 4 tests in 6.523s FAILED (failures=1) Destroying test database for alias 'default'... -
How can I display total likes received to an user to his post on django
I want to display total likes received to an user to his posts on django and display it by monthly basis def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["views"] = posts.objects.filter(likes=self.request.user) return context -
Create a new record using another for default values
What would be the best way to implement a feature whereby a user selects an existing record as a template for the creation of a new one? Ideally I'd like a list of all existing records in a ListView and the user clicks on one of these records and is taken to a CreateView whereby the fields are populated with the selected record's values as new default, starting values. Would this method essentially be a standard ListView-to-UpdateView however the save method would instead create a new record instead of updating? -
How to get the data from a post request using Django Python Templates
I have two projects, the first one is Node.JS. jsonobj = JSON.stringify(generateMockData) xhrToSoftware.send(jsonobj); xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true); xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhrToAPI.send(jsonobj); It's sending data to the second project Django Python. I can receive the data using my views.py. post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible? for example: <script> //get the data that posted by the node.js </script> I tried using this one: fetch('http://127.0.0.1:8000/path/') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => console.error(error)); but I'm having an error it says that: SyntaxError: Unexpected token '<', "<!-- <d"... is not valid JSON I think that's because I'm returning an html file in my views.py: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return render(request, 'waterplant/iot/data.html') so, I change it to jsonresponse like this: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return JsonResponse({"msg": value}, status=200) After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. How can I prevent that? … -
one upload function for pdf and a second upload function for excel
I have a template with two upload functionaliteis: one for pdf and one for excel. And I have two texareas for showing the data from the uploaded file: one textarea for data from the pdf and one texarea for the data from excel But my problem now is, how to combine this two in the views.py? So this is how the template looks: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-warning">Upload!</button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="70" rows="25"> {{content}}</textarea > </div> </div> </div> </form> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-warning">Upload!</button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="65" rows="25"> {{content_excel}}</textarea > </div> </div> </div> </form> </div> </body> </html> {% endblock content … -
How to overwrite a default value in Views
I have several views which use the same model and template due to the need for unique urls. Each view needs to set its own unique default values for several of the model's fields. For example in View 1, the models' field titled 'name' should have a default value of 'Name for a View 1 item', likewise 'Name for a View 2 item' under View 2 etc. How would I specify / overwrite a default value for a field in a view? -
SQL User History Table, Get last updated SPECIFIC FIELD
I have such a user_history table. Every time my users table is updated, records are dropped here as well. How can I get the date when my user updated his last salary information, that is, 2.01.2022 with SQL? I need to get the date it went from 200 to 300 (money field),so "2.01.2022" I need to do this with DJANGO ORM but I couldn't even do more normal SQL query. I tried to use sql lag,lead methods, but I could not succeed. -
My AWS pipeline keeps on failing, but not sure why one of the instances fails there?
My set up is : - Elastic Beanstalk Env - GitHub - S3 Bucket (for storage of static-files) The source stage is fine but thank it fails. ERROR: Latest action execution message Deployment completed, but with errors: During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version. Failed to deploy application. Unsuccessful command execution on instance id(s) 'i-08ec1ec805e434ba5'. Aborting the operation. [Instance: i-08ec1ec805e434ba5] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. Instance deployment failed. For details, see 'eb-engine.log'. -
How to display items on html table from django model base on its category
I have items in a Stock model and each item has a category that it belongs to. I want to show it in HTML tabular form like this, part no desc bal b/d etc CATEGORY1 1 item1 55 2 item2 69 3 item3 33 CATEGORY2 4 item4 54 5 item5 77 CATEGORY3 6 item6 55 7 item7 99 and so on... I want it to iterate through the Stock model, find the distinct category, display the items that relate to that category, and display the category name as a caption above the related items. model.py class Stock(models.Model): user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True) part_No = models.CharField(max_length=100, null=True) item_name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=100, null=True) unit = models.CharField(max_length=50, null=True) balance_bd = models.IntegerField(default='0', null = True) received = models.IntegerField(default='0', null = True) issued = models.IntegerField(default='0', null=True) unit_price = models.DecimalField(max_digits=20, decimal_places=2, null=True) obsolete = models.BooleanField(default=False, null=True) views.py def stock(request): stocks = Stock.objects.all() context = { 'stocks':stocks, } return render(request, 'base/stock.html', context) html template <!-- DATA TABLE--> <div class="table-responsive m-b-40"> <table class="table table-borderless table-data3"> <thead> <tr class="bg-primary"> <th>NO</th> <th>PART NO</th> <th>DESCRIPTION</th> <th>CATEGORY</th> <th>UNIT</th> <th>BALANCE B/D</th> <th>RECEIVED</th> <th>TOTAL BAL</th> <th>ISSUED</th> <th>TALLY CARD BAL</th> <th>UNIT PRICE</th> <th>TOTAL PRICE</th> <th>ACTION</th> </tr> </thead> <tbody> … -
how to set query for show followed posts in home page
its my models.py ` class Relation(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') created = models.DateTimeField(auto_now_add=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') avatar = models.FileField(default='default.jpg', verbose_name='avatar') age = models.PositiveSmallIntegerField(default=0) location = models.CharField(max_length=30, blank=True) work_at = models.TextField(null=True, blank=True) bio = models.TextField(null=True, blank=True) ` i want to make query to show all followd posts in main page make query for show followed posts in home page? -
how to apply distinct and group by in django or in postgres?
table production code part qty process_id 1 21 10 10 1 22 12 10 2 22 15 10 1 21 10 12 1 22 12 12 how to get data like this in postgresql or in django process_id qty 10 27 12 12 I tried in this way Production.objects.filter(q).values('process').distinct('code').annotate(total_qty=Sum('quantity')) -
Django querry set
I would like to have an example of a dango query that allows you to select elements contained in two different tables in a database in a single query I would like to have an example of a dango query that allows you to select elements contained in two different tables in a database in a single query -
Django-filter custom filter for custom field
I am using django-filter package to filter my queryset. However, for one of the fields I need to receive input similar to MultipleChoiceFilter but without using a fixed list of choices. For example: STATUS_CHOICES = ( (0, "Regular"), (1, "Manager"), (2, "Admin"), (3, "Staff"), ) class SomeFilter(django_filters.FilterSet): mychoices = django_filters.MultipleChoiceFilter( choices=STATUS_CHOICES, method="get_some_data" ) def get_some_data(self, queryset, field_name, value): print(value) # ['1','2','3'] class Meta: model = SomeModel when I use MultipleChoiceFilter, the URL looks like myurl/path/?mychoices=1&mychoices=2&mychoices=3 and then I receive these input values as a list e.g. ['1', '2', '3'] However, I need to create new filter field, say, openlistchoices where I can send a url request url/path/?ch=something1&ch=something2&ch=1234&ch=abc234 and still be able to have values as a list. Basically I want to create a filter for one of the fields where I have full control of what's being input. I'll sanitise and whitelist what's being received. -
Django Get Last Object for each Value in List
I have a model called Purchase, with two fields, User and amount_spent. This is models.py: class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount_spent = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I want to get the last purchases from a list of users. On views.py I have a list with some User's objects, and I want to get the last purchase for each user in the list. I can't find a way of doing this in a single query, I checked the latest() operator on QuerySets, but it only returns one object. This is views.py: purchases = Purchase.objects.filter(user__in=list_of_users) # purchases contains all the purchases from users, now I need to get the most recent onces for each user. I now I could group the purchases by user and then get the most recent ones, but I was wondering it there is a way of making this as a single query to DB. -
How to auto insert slashes in expiry date fields into django forms input
I want to insert a slash after 2 digit press like the same mechanism of MM/YY through Django forms input. The following has my code that is not working well. Models.py from django.db import models from creditcards.models import CardExpiryField class MyUser(models.Model): cc_expiry = CardExpiryField('expiration date', null=True) def __str__(self): return self.cc_expiry forms.py from django import forms from .models import MyUser from django.forms import TextInput class MyUserForm(forms.ModelForm): class Meta: model = MyUser fields = ('cc_expiry') widgets = { 'cc_expiry': TextInput(attrs={'placeholder': 'MM/YY'}), } views.py def cc_page(request): form = MyUserForm(request.POST or None) context = { "form": form } if form.is_valid(): form.save() return render(request, 'cc_thanks.html') return render(request, 'index.html', context) index.html {% load static %} {% load widget_tweaks %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="regForm" method="post" action=" "> {% csrf_token %} <div class="tab"> {{ form.cc_expiry.errors }} <p>{{ form.cc_expiry|add_class:"form-control" }}</p> </div> </form> </body> </html> In the following has the simple HTML JS code for the automatic insert slash after 2 digit press and it's working fine. And the similar result I expected. <input maxlength='5' placeholder="MM/YY" type="text" onkeyup="formatString(event);"> <script type="text/javascript"> function formatString(e) { var inputChar = String.fromCharCode(event.keyCode); var code = event.keyCode; var allowedKeys = [8]; if (allowedKeys.indexOf(code) !== -1) { return; } … -
can we run console command by django function
I want to run this command with the help of django function can we do this? python manage.py rebuild_index i want this when post_save function run how i can do this? -
How to upload document on an Article using article id when it does not even exists
currently i am in a very weird situation. I am trying to upload document using article id and user id to an article. But the issue is when I try to select article id from the document model, it gives error that article doesnt exists. And tbh that is true, because how can i upload document to an article when it doesnt even exists. So how can i use article id in such situation? Below is my document model in which i am sending user id and article id for uploading document. documentmodels.py class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") user_fk_doc=models.ForeignKey(User, on_delete=models.CASCADE, related_name="users_fk_doc") article_fk_doc=models.ForeignKey(Article, on_delete=models.CASCADE, related_name="articles_fk_doc") document=models.FileField(max_length=350, validators=[FileExtensionValidator(extensions)], upload_to=uploaded_files) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0, blank=True) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) and below is the articles models, class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) published=models.DateTimeField(auto_now_add=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") -
Django Admin Limit Model list
i have this models in my project: ` class Luce(models.Model): appartamento = models.ForeignKey('Appartamento', on_delete=models.CASCADE, related_name="bollette") numero = models.IntegerField() data = models.DateField() dal = models.DateField() al = models.DateField() importo = models.FloatField() file = models.FileField(upload_to='fatture/%Y/%m/%d') def __str__(self): return "Fattura Luce dal " + str(self.dal.strftime('%d/%m/%Y')) + " al " + str(self.al.strftime('%d/%m/%Y')) def file_link(self): if self.file: return format_html("<a href='%s'>Scarica</a>" % (self.file.url,)) else: return "No allegato" file_link.allow_tags = True class Meta: verbose_name = "Luce" verbose_name_plural = "Luce" class Appartamento(models.Model): nome = models.CharField(max_length=50) camere = models.IntegerField() class Meta: verbose_name = "Appartamento" verbose_name_plural = "Appartamenti" def __str__(self): return self.nome ` What i would do is to limit the visibility of model "Luce" in the way some users ( staff user ) can access only to their "Appartamento" My admin.py is this one: ` class LuceAdmin(admin.ModelAdmin): list_display = ('data', 'dal', 'al', 'importo', 'file_link') search_fields = ['data', 'dal', 'al'] list_filter = ('appartamento',) admin.site.register(Luce, LuceAdmin) class AppartamentoAdmin(admin.ModelAdmin): list_display = ('nome', 'camere') admin.site.register(Appartamento, AppartamentoAdmin) ` What ca i do ? I mean some staff user has limited access only to objects of type "Luce" assigned to one specific category "Appartamento". THanks -
Server Error (500) - rendering lists in django
I am getting a Server Error (500) when i'm trying to render a list to one of my web pages in Django. def find_jobs(request): job_details = [job_position for job_position in JobPost.objects.all() if job_position.Status is not JobPostStatus.Closed] Seeker_applied_job = seeker_applied_job() print(job_details) content = {'title': "Job seekers", 'jobs': job_details, 'message': "to view job postings", } print(content) return render(request, 'seek_job.html', content) the print(job_details) line returns this [<JobPost: Opportunist at OpportunityM>, <JobPost: Digital Marketer at OpportunityM>, <JobPost: Nurse at NHS>] When I remove 'jobs': job_details from content, the seek_job.html page renders. But when I try adding it back, it returns a Server Error (500) page. I have another view function similar to this one which works fine. -
Implementing JS in Django templates
I have a list of ingredients, for every ingredient, I would like to give the option to delete the current ingredient via using a popup that asks the user "are you sure they want to delete this?" If confirmed, I want that ingredient to be deleted. Currently, no matter which ingredient I choose to delete, it always the deletes the first ingredient in the list. For example, if the list of ingredients is ['cheese', 'lettuce'], I click remove ingredient under lettuce, and it will still delete cheese. I've never used javascript in Django templates before, I think I need to pass the ingredient into the openPopup function, but I'm not sure how to do it, any help would be appreciated! I've looked at the Django docs for using JS in templates but it's not crystal clear to me. How do I go about doing this? <div class="ingredient-container"> {% for ingredient in ingredients %} <div class="ingredient"> <b>{{ ingredient|title }}</b><br> <small><a href="{% url 'core:edit_ingredient' ingredient.id %}">Edit Ingredient</a></small> {% empty %} {% endfor %} <!-- This button opens the popup up to confirm deletion of the ingredient--> <button class="remove" type="submit" onclick="openPopup()">Remove Ingredient</button> <div class="popup" id="popup"> <h2>Delete Confirmation</h2> <p>Are you sure you want to … -
Django multiple models that have a foreign key to another model
Example: A system that processes different types of csv files. The different types of csv files have different content inside. So the current way im thinking about modeling this is: File model that stores some generic info about each file processed, like the name, date etc. class File(models.Model): name = models.CharField() Then models that stores the content for each type of file and these models link back to the File model: class Example1File(models.Model): file = models.ForeignKey(File, related_name=example_file_1_content) ... (all columns for this file) class Example2File(models.Model): file = models.ForeignKey(File, related_name=example_file_2_content) ... (all columns for this file) Is there an easy way for example to loop through the files table and get the content for each file and django would just know in which table to go look? for file in File.objects.all(): file.??? Or would I only be able to do this by storing a type field on the file and then getting the content with the reverse relationship like this. for file in File.objects.all(): if file.type == FileTypes.ExampleFile1: file.example_file_1_content But what if there are a lot of different file types? Im still in the process of learning about how django handles relationships/reverse relationships so I might just not be there yet … -
django issue : i get erro 404 page note found
I try to write a django code fo a registration page the error snip and code: enter image description here """ """ -
Django configuration in PyCharm
After few years using Mac and Linux for my dev I have to pass on windows now. I have a project which run on docker-compose and that works very well on Mac and Linux but on windows I have some configuration problems with PyCharm. If I run the docker compose by hand: works well If I run the project threw the "run" or "debug" in pycharm: works well But when I try to run the "manage.py command" threw pycharm I got this traceback: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. That would be just a small problem but it seems that Pycharm does not recognize django in the docker interpreter because all the django specific code is highlighted and the autocompletion doen't work anymore. Basic example: if I use {% load ... %}, the load tag is not recognized. It is definitly a problem in the configuration of pycharm but I can not find where it is. Any idea?