Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS is not applying in login form in django
Refused to apply style from 'http://127.0.0.1:8000/%7B%%20static%20'assets/css/Login-Form-Clean.css'%20%7D' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/assets/bootstrap/js/bootstrap.bundle.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE -
Why PASSWORD_HASHERS is a list rather than a string in Django?
At a time we can use only one password hashing algorithm,then what is the purpose of proving a list of password hashing algorithms in django settings file? -
Django filter returns duplicate values
I have Post model linked with Vote model in one-to-many relationship. when i try to filter posts with most votes .filter() returns posts duplicated as many as the votes it received i tried to understand & use .distinct() function as recommended in similar questions but it doesn't turn out to be working. here's the Post model: class Post(models.Model): text = models.CharField(max_length=450) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) posted_at = models.DateTimeField(editable=False, default=timezone.now) status = models.CharField(choices=status, default='PENDING', max_length=15) def __str__(self): return self.text & Vote model: class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return f'{str(self.user)} - {str(self.post)}' views.py: class PostsView(TemplateView): template_name = 'posts.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['most_voted_posts'] = Post.objects.filter(status='PUBLISHED').order_by('-vote') return context -
tried deleted data but failed to delete from django database
I have created models.py, views.py, and urls.py and later on accordingly updated data.html file but when I click on the delete button it gives me an error. so the error file also attached for reference. Help appreciated and waiting for resolution. error file Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/delete/ Using the URLconf defined in student.urls, Django tried these URL patterns, in this order: admin/ [name='index'] export/ [name='export'] export-pdf [name='export-pdf'] register/ [name='register'] login/ [name='login'] home/ [name='home'] logout/ [name='logout'] upload/ [name='upload'] result/ [name='result'] dashbord/ [name='dashbord'] data/ [name='data'] delete/<int:id> ^static/(?P<path>.*)$ The current path, delete/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py path('data/', views.data, name='data'), path('delete/<int:id>', views.delete), data.html <a href="/edit/{{ student.id }}" class="btn btn-success"><span>Edit</span></a <a href="/delete/{{data1.id}}" class="btn btn-danger">Delete</a> views.py def data(request): data1 = Contact.objects.all() # myFilter = OrderFilter() dict = { "data1":data1 } return render(request, 'data.html', context=dict) # Delete Data def delete(request): data1 = Contact.objects.all(id=id) data1.delete() return redirect("/data") model.py from django.db import models from django.db.models.fields import CharField from django.contrib import admin # Create your models here. class Contact(models.Model): name = models.CharField(max_length=50, default="") contact = … -
Django MultiValueDictKeyError Passing input type file
I am getting this error when I am trying to pass the value of the folder to another html. I have stored the form in a database in DB Browser Sqlite. I am trying to pass the input type = file to another HTML. So that when I view the existing type = file, the file will automatically be shown. Below is an attachment from submitclaim.html <form action="/newclaim/" method="post" enctype="multipart/form-data"> <label for="receipt">Receipt: </label> <br> <input id="receipt" type="file" name="receipt_field"> </form> This is my verfiyexistingclaims.html <form method="POST" action="/verifyexistingclaims/{{claims.id}}" enctype="multipart/form-data"> <label for="receipt">Receipt: </label> <input id="receipt" type="file" name="receipt" value={{claims.receipt}}> </form> This is my views.py def financeverifyclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': # update original object claims.receipt = request.FILES['receipt'] # save it with original `ID` claims.save() return render(request, "Login/verifyexistingclaims.html", {'claims':claims, 'user':user}) -
Make a POST request from standalone React to Django
I am trying to make a simple post request from the react server localhost:3000 to Django server localhost:8000 with axios. But I get 403 error. I tried putting csrftoken in the headers but I am still getting the error. How do you make a POST request from standalone React server to standalone Django server? import React, { useState} from 'react'; import axios from 'axios'; const App = () => { const [name, setName] = useState(""); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); const messageHandler = () => { const sentmessage = { name: name, email: email, message: message, } axios.post("/api/messages/", sentmessage, { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken } }, ).then((res) => console.log(res)); } return ( <div className="page"> <div className="message_form"> <p><textarea name="name" onChange={(e) => setName(e.target.value)} placeholder="Enter your name … -
Views from different apps look for templates in different places?
So I'm trying to show the homepage template with templateView but it confused me a lot. Right now I have 3 apps (main, users, polls). With the following structure: . ├── main │ └── ... ├── (Project Folder) │ └── ... ├── polls │ └── ... ├── users │ └── ... └── templates ├── main │ └── ... ├── polls │ └── ... └── base.html (for extends) I already have some views from polls working (CreateView, ListView, DetailView). I know that the templates for default are searched inside the app folder but I changed it to have it at the level of the apps as you can see above. But with this new app (main) where I have the index view, it doesn't work the same. The index.html is searched in templates/index.html and not in templates/main/index.html. Why with the polls app works by having a folder with the app name inside templates but with main don't work like that? Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] main views.py # Django imports from django.views.generic import TemplateView class Index(TemplateView): template_name = 'index.html' main urls.py from … -
Django custom permissions nodes
What I want to achieve is the way how to create a custom permission object and assign this object to the user object model. Firstly, I have swapped the default user model to my custom one, it works as I expect. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): id = models.AutoField(primary_key=True) is_banned = models.BooleanField(default=0) permission = models.JSONField(default=list) I would like to store in the permission field the permissions nodes for my modules, by example, I have one module, planification, and of course it comes with some submodules. Those submodules comes with some features that should be considered too planification manage create delete list query I'm thinking about to create permissions nodes like: planification # to access the main module planification.* # to bypass all the checks planification.manage # to access the module planification.manage.create planification.manage.delete planification.list planification.list.query Then create the methods to add/remove nodes to the permissions object and the checking method for heritance, assign it to the user and of course, store it on the permissions field. The user will have a permissions object like this: [ 'planification.manage.create', 'planification.manage.delete' ] That will allow the user to access the planification module, the manage submodule and the create/delete methods. … -
File writing failing in docker production environment
In my production environments I am failing to write to files. For example, I've set up a test-task with Celery that writes the time to a file every minute: @celery_app.task(name='print_time') def print_time(): now = datetime.datetime.now().strftime('%Y %b %d %a @%H:%M') cur_time = {"now": now} print(f'The date and time sent: {cur_time}') json.dump(cur_time, open(PATH.abspath(PATH.join(APP_DIR, "data", "cur_time.json")), "w")) t = json.load(open(PATH.abspath(PATH.join(APP_DIR, "data", "cur_time.json")))) print(f'The date and time received: {t}') Both of the print statements will give the expected results, as of my writing this, they last printed: The date and time sent: {'now': '2021 May 26 Wed @18:57'} The date and time received: {'now': '2021 May 26 Wed @18:57'} However, when I set up a view to display the contents: class TimeView(TemplateView): def get_context_data(self, **kwargs): time = json.load(open(PATH.abspath(PATH.join(APP_DIR, "data", "cur_time.json")))) return time It becomes clear that the file is not really updating in the development environment when i go to the url and the time continues to remain the same as it was when I originally rsynced the file from my development environment (which is successfully updating the file contents) To verify this further I've also ran cat cur_time.json and stat cur_time.json to verify that the files are not being written to successfully. Knowing … -
How to Create detail view in Django using 2 models having one to many relation (ForeignKey)
It is my first Django Project. I'm trying to get data from list view to Details view. I want to pass both the models using function view but it is not working. Class based view works but I can only get data from one model. Sorry the code presentation is extremely poor. #models class Cadet_Bio(models.Model): C_N = models.PositiveIntegerField() name = models.CharField(max_length=120) entry = models.CharField(max_length=20) house = models.CharField(max_length=20) date_joined = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return f"C/No: {self.C_N}, Name: {self.name}" class Fitness(models.Model): push_ups = models.PositiveSmallIntegerField() chin_ups = models.PositiveSmallIntegerField() sit_ups = models.PositiveSmallIntegerField() One_Mile = models.PositiveSmallIntegerField() Two_Miles = models.PositiveSmallIntegerField() cn = models.ForeignKey(Cadet_Bio, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) average = models.FloatField(blank=True) PT_Test_Date = models.DateField(auto_now=False, auto_now_add=False) def save(self, *args, **kwargs): self.average = ((self.push_ups * 10/100)+(self.sit_ups * 10/100)+(self.chin_ups * 15/100)+(self.One_Mile * 35/100)+(self.Two_Miles * 30/100) * 100)/4 return super().save(*args, **kwargs) def __str__(self): return f"C/NO: {self.cn.C_N}, House: {self.cn.house}, Entry: {self.cn.entry}, Average: {self.average}, Dated: {self.PT_Test_Date}" #views.py def fitness_list_view(request): df1 = None df2 = None cadet_df_merged = None qs = Fitness.objects.all() qs1 = Cadet_Bio.objects.all() qs_df = pd.DataFrame(qs1.values()) if len(qs) > 0: df1 = pd.DataFrame(qs.values()) # print(df1) print('####################') df2 = df1.groupby(['cn_id'], as_index=False).agg({'average':['mean']}) df2.columns = list(map(''.join,df2.columns.values)) # df2 = df1.groupby(['cn_id']).agg({'average': 'mean'}) df2.rename({'cn_id': 'C_No'}, axis=1, inplace=True) df2.rename({'averagemean': 'Avg'}, axis=1, inplace=True) qs_df.rename({'C_N': 'C_No'}, axis=1,inplace=True) qs_df.rename({'date_joined': … -
Django RegexValidator causing AttributeError in Django Admin
I'm using a RegexValidator pretty simply in my User Model: name_regex = RegexValidator(r"^[a-zA-Z0-9\s_]*$") name = models.CharField( _("Name"), default=generate_default_name, max_length=constants.USER_NAME_MAX_LENGTH, help_text=_("The user's display name."), validators=[name_regex], ) But when I use the standard Django UserAdmin I get this error whenever I try to save any field which confuses me greatly: 'RegexValidator' object has no attribute 'search' I don't do anything with search, nor do I reference RegexValidator at all in my standard instantiation of the userAdmin. admin.site.register(User, UserAdmin) Any ideas? -
django User.objects.create() is throwing error
here is the view to signup a user: @api_view(['POST']) def registerUser(request): # data is successfully passed from client data=request.data print("register data", data) try: print(data['name']) print(data['email']) print(make_password(data['password'])) # Everything prints so far but nothing after here user = User.objects.create( first_name=data['name'], username=data['email'], email=data['email'], password=make_password(data['password']) ) print("userrrrrrr",user) # serializer=UserSerializerWithToken(user, many=False) # dont login the user message={"detail":"Successfully registered"} # return Response(serializer.data) # I just want to send a simple message return Response(message) except: message={'detail':"User with this email already exists"} return Response(message, status=status.HTTP_400_BAD_REQUEST) I put notes on code. Data is received and I print everything. BUt User.objects.create() is causing an error so except block gets executed and i am getting error. I also tried User.objects.create_user() but getting same error. User.objects.create( first_name=data['name'], username=data['email'], email=data['email'], password=make_password(data['password']) ) -
Disable Bootstrap warnings from Django Compressor
Is there any way to disable warnings from Django compressor when compressing files? Currently when I'm compressing the files I get a lot of warnings like this: WARNING: The `make-container-max-widths` mixin has been deprecated as of v4.5.2. It will be removed entirely in v5. We're statically hosting Bootstrap, so I don't really care about those messages. I'd really just like them not to show up. -
How to make a chart from uploaded JSON file on webpage?
I have looked at options such as Google Charts, Charts.JS, Pandas, Any chart, etc, but I still feel a little stumped on direction to go forward. I want the chart to grab files saved on the admin side with url: http://127.0.0.1:8000/admin/infographicsite/filesupload/ and make a graph based on any JSON file uploaded to the webapp. There's also percentages/calculations done on a separate file that I will also bring in to connect with so graph can correctly represent said percentages. one JSON file that was uploaded looks like this: { "results":[ { "gender":"female", "name":{ "title":"Mrs", "first":"Debra", "last":"Johnston" }, "location":{ "street":{ "number":2192, "name":"Bridge Road" }, "city":"Coventry", "state":"Shropshire", "country":"United Kingdom", "postcode":"YK74 9FX", "coordinates":{ "latitude":"6.6918", "longitude":"111.6380" }, "timezone":{ "offset":"+5:45", "description":"Kathmandu" } }, "email":"debra.johnston@example.com", "login":{ "uuid":"475c314c-bd42-49b5-b81c-8016ddb1b5e3", "username":"smallleopard142", "password":"beach", "salt":"YqjLSvmF", "md5":"26436a12fdaa430eebb3c39236554b4f", "sha1":"cc972754b8164c7e48dab2e01ef2c107d110006b", "sha256":"8015b915af908793db031cd3e27a67883f0aeb674777fdc8b6226352155b57b4" }, "dob":{ "date":"1949-12-12T14:53:42.446Z", "age":72 }, "registered":{ "date":"2009-10-04T09:05:27.022Z", "age":12 }, "phone":"017687 39061", "cell":"0752-951-872", "id":{ "name":"NINO", "value":"ZT 33 57 79 M" }, "picture":{ "large":"https://randomuser.me/api/portraits/women/84.jpg", "medium":"https://randomuser.me/api/portraits/med/women/84.jpg", "thumbnail":"https://randomuser.me/api/portraits/thumb/women/84.jpg" }, "nat":"GB" }, { "gender":"female", "name":{ "title":"Miss", "first":"Gül", "last":"Türkyılmaz" }, "location":{ "street":{ "number":3425, "name":"Filistin Cd" }, "city":"Kilis", "state":"Antalya", "country":"Turkey", "postcode":32073, "coordinates":{ "latitude":"-15.1737", "longitude":"14.2954" }, "timezone":{ "offset":"-11:00", "description":"Midway Island, Samoa" } }, "email":"gul.turkyilmaz@example.com", "login":{ "uuid":"257f4418-270d-4002-9e84-6e33d9e82a71", "username":"smallpeacock303", "password":"ashley", "salt":"HegxAbaa", "md5":"b5a339d4d6eb3eebe51c437b99ab82ae", "sha1":"aebe19b90d0bc7701fc93ebeb9b251c90d31d08d", "sha256":"c871b4709aa301bf1cf09de5296ad96813a8818e3362860a6b260103502844e5" }, "dob":{ "date":"1993-03-08T17:29:09.139Z", "age":28 }, "registered":{ "date":"2003-02-02T01:58:10.729Z", "age":18 }, "phone":"(324)-499-6198", … -
Django Form after redirect is empty after successfully submitting a form
I have a template called courses for the url http://127.0.0.1:8000/gradebook/courses/. This template lists existing Course objects loads the CourseForm form. The form successfully creates new objects. If I go to the addassessment template with url http://127.0.0.1:8000/gradebook/addassessment/7/, it correctly loads the AssessmentForm. I want to submit this form and then return to the previous courses template. The AssessmentForm submits and the object is saved, but when it redirects back to the courses template, the CourseForm does not load. The courses template loads, the expect html loads correctly other than the form fields. I notice that the url for this page is still http://127.0.0.1:8000/gradebook/addassessment/7/ and not ../gradebook/courses/. app_name = 'gradebook' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('signup/', SignUpView.as_view(), name='signup'), path('courses/', views.courses, name='courses'), path('classroom/', views.classroom, name='classroom'), path('objective/<int:course_id>/', views.addobjective, name='addobjective'), path('addassessment/<int:course_id>/', views.addassessment, name='addassessment'), ] #urls.py project urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('admin/', admin.site.urls), path('gradebook/', include('gradebook.urls')), path('gradebook/', include('django.contrib.auth.urls')), ] #models.py class Course(models.Model): course_name = models.CharField(max_length=10) class Classroom(models.Model): classroom_name = models.CharField(max_length=10) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Assessment(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) assessment_name = models.CharField(max_length=10) objectives = models.ManyToManyField('Objective') class Objective(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) #views.py def courses(request): course_list = Course.objects.order_by('course_name') context = {'course_list': course_list} if request.method == 'POST': details = … -
Django prefetch taking lot of time when accessing result the first time
I have Rule, Condition and Action models. A rule can have conditions and actions. Rule ->condition and rule->action are represented by many to many relationships class Condition(models.Model): id = models.BigAutoField(primary_key=True) rule_var = models.CharField(null=False, max_length=30) rule_var_type = models.CharField(choices=RuleVarType.choices, max_length=30) rule_operator = models.CharField(choices=Operator.choices, max_length=30) rule_value = models.CharField(null=False, max_length=100) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(default=timezone.now) class Meta: indexes = [models.Index(fields=["rule_var"])] class Action(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(null=False, max_length=30) label = models.CharField(null=False, max_length=60) params = models.JSONField(null=False) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(default=timezone.now) class Meta: indexes = [models.Index(fields=["label"]), models.Index(fields=["name"])] class Rule(models.Model): id = models.BigAutoField(primary_key=True) system = models.CharField(choices=System.choices, max_length=30) type = models.CharField(choices=Type.choices, max_length=30) expires_on = models.DateTimeField(default=timezone.now) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(default=timezone.now) conditions_any = models.ManyToManyField(Condition, related_name="condition_any") actions = models.ManyToManyField(Action) class Meta: indexes = [ models.Index(fields=["system", "expires_on", "type",]), ] When i am trying to get rules and associated conditions and actions using prefetch as below , rules = Rule.objects.filter( system=system, expires_on__gte=timezone.now() ).prefetch_related( Prefetch( "conditions_any", queryset=Condition.objects.only( "id", "rule_var", "rule_var_type", "rule_operator", "rule_value" ), to_attr="any_conditions", ) Prefetch( "actions", queryset=Action.objects.only("id", "name", "label", "params"), to_attr="related_actions", ), ) for rule in rules: for condition in rule.any_conditions: #do something for condition in rule.any_conditions: #do something i face the following issue. The debug logs for the db query points out that the prefetch queries … -
Pandas and confusion over passing by value and passing by reference
A function returns a Pandas DataFrame. I try to create a new DataFrame with "newFrame = myFunction()". But the newFrame variable acts more like a reference than a distinct object. Can you help? In these snippets, FrameMaker.py updates a DataFrame object on a timer. It has a function get_frame that returns that DataFrame object. Multiple scripts call that function to get a copy of the DataFrame. GetFrameData.py is an example. It calls the get_frame function and assigns the returned value to a variable. It should then have its own copy of the DataFrame, and anything it does to its copy of the DataFrame should have no effect on any other copies. But it does cause an effect. GetFrameData.py drops columns from the DataFrame. The first time that runs, the "values.drop" line runs successfully. The second time it runs, it gives an error that the DataFrame doesn't have the columns in question. It's like the 'values' variable is a reference to the DataFrame in FrameMaker.py, not a distinct object in the GetFrameData stack. Kind of like how Strings function in most languages. How should I change my code to get a copy of the DataFrame object, not a reference? FrameMaker.py def … -
Having Trouble Creating Nested LISP-Style List in Python
I have a list of functions and values I'd like to put into a nested list. I'd like the result to be a LISP style list(something that looks close to some LISP style executable code) that I can easily process later. This list comes from a "sentence", that gets split into a list by word - it keeps defined phrases (multi word) together, by checking any multi-word tokens in the DB first, gluing them and then separating them later. Any words not in the database are ignored. Punctuation is also ignored. It just matches actual stored Tokens. This lets me write a sentence that can get translated into functions I can process later. We can ignore the fact that these are functions, and just think of them as strings, since that's how they're stored, but functions and arguments describe the use case perfectly, since that's what they are. Functions will be the first item in a list, followed by their arguments in the same list. A function with no arguments will be in a list with only that one element. An argument that is itself a function will be in a list(with it's arguments, if any). The number of arguments … -
Django convert pdf to image
I'm receiving a PDF via form post and before uploading it into my models, I would like to convert it to an image (I'm using the library pdf2image). I'm able to work with a temporary file of the PDF and convert it to an image but I haven't been able to save the image into my models. Any idea?? Here's what I've got so far. Models.py class Files(models.Model): archivo = models.FileField(upload_to='pdf/') Views.py def converter(request): if request.method == 'POST': form = UploadFilesForm(request.POST ,request.FILES ) if form.is_valid(): #new_pdf = Files(archivo = request.FILES['archivo']) new_pdf = request.FILES['archivo'] path = default_storage.save("file.pdf", ContentFile(new_pdf.read())) path = settings.MEDIA_ROOT + '/' + "file.pdf" images = convert_from_path(path,fmt='png',dpi=300,grayscale=True) image = images[0] image.save("imagen.png") else: form = UploadFilesForm() context = {'form':form} return render(request, 'converter.html',context) -
Django form is not creating new entries
I have the following form to create new clients on a database on Django and rendered using crispyforms. However, even thoug it is rendered correctly, it's not creating new entries. models.py class Client (models.Model): def __str__(self): return self.name + ' '+ self.surname name = models.CharField(max_length=120) surname = models.CharField(max_length=120, null=True) phone = models.PositiveIntegerField(null=True) mail = models.EmailField(null=True) sport = models.TextField(blank=True, null=True) gender_options=( ("F", "femenino"), ("M", "masculino"), ) gender = models.CharField(max_length=120, null=True, choices=gender_options) birth = models.DateField(null=True) def get_absolute_url(self): return reverse("clientes:cliente", kwargs={"client_id": self.id}) pass forms.py from django import forms from .models import Client class NewClientForm(forms.Form): name = forms.CharField(label='Nombres') surname = forms.CharField(label='Apellidos') phone = forms.CharField(label='Teléfono') mail = forms.EmailField(label='Correo electrónico') gender = forms.ChoiceField(label='Género', choices= Client.gender_options) birth = forms.DateField(label='Fecha de nacimiento', widget=forms.TextInput(attrs={ 'id': "datepicker", })) sport = forms.CharField(label='Deportes') views.py def new_client_view(request): new_client_form = NewClientForm() if request.method == "POST": new_client_form = NewClientForm(request.POST) if new_client_form.is_valid(): Client.objects.create(**new_client_form.cleaned_data) else: print(new_client_form.errors) context = { "form": new_client_form } return render (request, 'clients/new-client.html', context) html {% extends 'base.html' %} {% load bootstrap4 %} {% load crispy_forms_tags %} {% block content %} <h1>Nuevo cliente</h1> <section class="container"> <form action="." method="POST" class="form-floating mb-3"> {%csrf_token%} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.surname|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ … -
Django Page not found Request Method: GET
I can't seem to figure out why my page can't be found. All the others previous ones are written exactly the same way. Why is this happening? VIEWS: def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logg:topic', topic_id=topic_id) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) URLS: app_name = "learning_logg" urlpatterns = [ #Home Page path('', views.index, name="index"), path('topics/', views.topics, name="topics"), path('topics/<int:topic_id>/', views.topics, name="topics"), path('new_topic/', views.new_topic, name='new_topic'), path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), ] NEW_ENTRY.HTML: {% extends "learning_logs/base.html" %} {% block content %} <p>Add a new entry:</p> <form action="{% url 'learning_logg:new_entry' topic.id %}" method='post'> {% csrf_token %} {{ form.as_pp }} <button name='submit'>Add entry</button> </form> <p><a> href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> {% endblock content %} -
sort element when clicking on a button in django
i want to sort my items when clicking on a button i already did the search function in my list view like that: search_input = self.request.GET.get('search-area') or '' if search_input: context['tasks']=context['tasks'].filter(day="sunday") i want to get all the items which their attribute day is equal to "sunday" in my template i tried this: <form method="GET" style ="margin-top: 20px ; display : flex"> <input type="text" name="search-area" value="{{search_input}}"> <input class ="button" type="submit" value='Search'> </form> but the problem is that i need to write somthing to have the result, i just tried to do it with a form because this the solution that i found in internt but i want to do it just with a button -
Syncing Django Models with Overriden Save Method
I have a client and a user model. Both client and user have a flag called help_desk. The help desk clients and users are to be kept in sync. This means that: When user is marked as help_desk they are added to all help desk clients When user is unmarked as help_desk they are removed from all help desk clients When a client is marked as help_desk all help desk users added to it When a client is unmarked as help_desk all help desk users are removed from it I've been trying to solve this by overriding the save() method with the following: Client def save(self, *args, **kwargs): help_desk_users = get_user_model().objects.filter(is_help_desk=True) if self.help_desk: for user in help_desk_users: self.users.add(user) else: for user in self.users.all(): if user in help_desk_users: self.users.remove(user) super().save(*args, **kwargs) User def save(self, *args, **kwargs): if self.is_help_desk: for client in Client.objects.filter(help_desk=True): client.users.add(self) else: for client in Client.objects.filter(help_desk=True): client.users.remove(self) super().save(*args, **kwargs) The user code is working as expected but the client code is not. I think the reason is because you are unable to bulk update in an overriden save method - see docs. My question is, is this simply a limitation of Django? And if so, what are the best … -
Django json field sorting on first ip address
I have a model which stores ip addresses in json field: class UserIP(models.Model): name = models.TextField() ip_addresses = JsonField() Data looks something like this, UserIP.objects.filter(id__gt=100).values('ip_addresses') <QuerySet [{'ip_addresses': {'172.19.128.1': 1, '192.168.0.129': 1}}, {'ip_addresses': {'10.248.91.72': 1, '10.248.91.73': 1, '10.248.91.74': 1}}, {'ip_addresses': {'1.1.34.13': 1}}]> In output I need to sort the data based on first ip address in each record. So the ideal order should be, 1.1.34.13 10.248.91.72 172.19.128.1 When I do normal Django sorting it prints in order as below, UserIP.objects.filter(id__gt=100).values('ip_addresses').order_by('ip_addresses') 1.1.34.13 172.19.128.1 10.248.91.72 Please advice what would be the solution. -
Django Save Image In Different Formats Using Pillow
I have this site I am making for my school and I need to optimize it, like a lot. So I decided to serve all my images compressed and in next-gen formats like jpeg-2000 and webp. Using Pillow, this is what I have so far: class Bulletin(models.Model): banner = models.ImageField(upload_to='banner/', blank=True) def save(self, *args, **kwargs): super().save() if self.banner: image = Image.open(self.banner.path) resized = image.resize((1600, 900)) resized.save(self.banner.path, quality=50) So I think that this compresses the image (plz tell me if I made mistake with code above). So now I want to be able to save this image in multiple formats I want the one uploaded image to be saved in these formats: webp jpeg2000 jpeg I am thinking of creating more fields on my model banner, like the field banner_webp, and then I would just convert it to webp and during save I would save the converted image to that field. The problem is that I don’t know how to convert image using Pillow, or how to do what I am asking. Thanks for help.