Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing max_length on a CharField for a ModelForm
I have defined the max_length on a field to be 50 in the model definition. When a form is created it takes those attributes to make the fields, but I would like to overwrite that max_length for that specific form without changing the model itself. This is what I have in my model text_field01 = models.CharField(max_length=50, default="") text_field02 = models.CharField(max_length=50, default="") I tried overwriting the widget with a new widget in my forms.py but that threw an error. I also tried it in the init but that seemed to have no effect. I am a bit stuck, any help would be greatly appreciated. EDIT At first I tried setting the widgets in class meta as shown below. widgets = { 'text_field01': forms.CharField(max_length=10) This produced an error "CharField" object has no attribute 'is_hidden' Then I tried doing it in init as shown below. def __init__(self, *args, **kwargs): super(AutomationForm, self).__init__(data=data, files=files, *args, **kwargs) if self.instance: if self.fields['text_field01']: self.fields['text_field01'].max_length = 2 Which simply had no effect. -
Overwrite 'Personal info' field in the admin/Users?
During my first Django app i've managed to hit this 'road-block' where i'm trying to extend User model from my .forms file where forms.py looks like this: #forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) phone = forms.CharField(max_length=50, required=False) class Meta: model = User fields = ['username', 'email', 'phone', 'password1', 'password2'] class UserLoginForm(AuthenticationForm): class Meta: model = User fields = ['username', 'password'] In my .models file i'm only having a 'Profile' model which is being registered within admin.py: #admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import * from .forms import UserRegisterForm admin.site.unregister(User) class CustomUserAdmin(UserAdmin, UserRegisterForm): fieldsets = UserAdmin.fieldsets + ( (('Personal info'), {'fields': ('phone',)}), ) admin.site.register(User, CustomUserAdmin) admin.site.register(Profile) ...and i'm getting this back(bare in mind i've tried also passing just my form class which resulted in allot more errors): #error FieldError at /admin/auth/user/1/change/ Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://127.0.0.1:8000/admin/auth/user/1/change/ Django Version: 3.0.4 So the end goal would be to have another field available in my Users/'Personal info'(that's been extended within forms.py) and also would be nice to get that field when creating a … -
Django admin panel checkbox have label to the left
I have a Django checkbox in the admin panel. However it looks bad and doesn't conform to the other properties with a label on the left and then the option on the right. Is it possible to change it? default checkbox class myForm(models.Model): required = models.BooleanField(default=False) -
what books are best for django 3?
what books are best for django 3? Thanks in advance for your suggestions. -
Changing a value in a django template when a condition is fullfilled
What i am trying to do is that the last td tag in the table containing the text 'Pendiente...' change to 'Finalizado' when the condition following that tag is fullfilled, i was trying inserting inside the condition but that would just add another td, when i want is only to change the text inside it! Can i have some help please! Template {%extends 'base.html'%} {%load staticfiles%} {%block body_block%} <link rel="stylesheet" href="{%static 'appointments/css/appointments_index.css'%}"> {%if consults%} <h1 id="Heading">Consultas <h5 id="Date">{% now "j F Y" %}</h5></h1> <table align="center"> <thead> <th>Codigo de Paciente</th> <th>Paciente</th> <th>Fecha</th> <th>Motivo</th> <th>Padecimiento</th> <th>Estado</th> </thead> <tbody> {%for consult in consults%} <tr> <td>{{consult.Paciente.Codigo}}</td> <td>{{consult.Paciente.Nombres}} {{consult.Paciente.Apellidos}}</td> <td>{{consult.Fecha}}</td> <td>{{consult.Motivo}}</td> <td>{{consult.Padecimiento}}</td> <td>Pendiente...</td> <td><div class="perform"><a href="{%url 'appointmentupdate' consult.id %}">Realizar</a></div></td> {% if consult.Medicamento%} <td><div class="receipt"><a href="">Receta</a></div></td> {%endif%} </tr> {%endfor%} </tbody> </table> {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/patients?page={{ page_obj.previous_page_number }}">Anterior</a> {% endif %} <span class="page-current"> Pag {{ page_obj.number }} de {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/patients?page={{ page_obj.next_page_number }}">Siguiente</a> {% endif %} </span> </div> {% endif %} {%else%} <h1 id="noregisters">No tiene consultas pendientes.</h1> {%endif%} <button id="Add"><a class="fas fa-plus" href="{%url 'addappointment'%}"></a></button> <button id="Registers"><a href="{%url 'appointmentlist'%}">Registros</a></button> {%endblock%} -
OOP and Design Pattern in Django
I am new in django and could not find proper documents on OOP in django and design patterns in django . kindly help me to find OOP and design pattren in django resources. Regards, -
How to connect react and django together?
I was learning django and wanted create a project involving django rest framework + react. Then I found this article https://www.valentinog.com/blog/drf/#django-rest-with-react-django-rest-serializers showing ways to connect react and django together. Here are those ways of react + django connection: Option 1. React in its own "frontend" Django app: load a single HTML template and let React manage the frontend (difficulty: medium) Option 2. Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication) Option 3. Mix and match: mini React apps inside Django templates (difficulty: simple, but not so maintainable in the long run) Pls guys can you help with choosing the right way to connect react and django together and what are the pros and cons of each above approach. The option 2 looked logical to me since we just use create-react-app and the boilerplate is ready and we have separate backend and frontend but I do not know why that way was labelled as hard to implement. -
Passing HTML input value into Ajax and back to Views.py?
So I need to return an input value from my html in order to render the corresponding chart values from my db, the only problem is I'm not seeing the correct console output when I try to incorporate it into my function.. I tried a smaller snippet of code to make sure I was on the right track <form autocomplete="off" action="" method="GET"> <div class="autocomplete"> <input id="myInput" type="text" name="Item" placeholder="Search..."> </div> <input type="submit" id="submitBtn" value="Search"> </form> <script> $('#submitBtn').click(function(){ var input_value = document.getElementById('myInput').value; alert(input_value) }) </script> This works perfectly fine on its own, but when I try to combine it with my Ajax, it doesn't seem to render my chart anymore and console.log(input_value) doesn't give me anything. <div class="chart-container"> <canvas id="myChart"></canvas> <script type="text/javascript"> var endpoint = 'api/chart/data/' var dataset = [] var labels = [] $('#submitBtn').click(function(){ var input_value = document.getElementById('myInput').value; $.ajax({ method: "GET", url: endpoint, data: { itemName = input_value, }, success: function(data){ labels = data.labels dataset = data.dataset var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: dataset }] }, options: { responsive:true, layout: { padding: { left: 50, … -
Save Django Model Form and refresh after selecting a Foreign Key Object
I have the following models: class Pic(models.Model): name = models.CharField(max_length=50) img = ImageField(upload_to='images/', default=None, null=True, blank=True) class InputTest(models.Model): pic_id = models.ForeignKey(Pic, on_delete=models.CASCADE) image_field_crop = CropperImageField(upload_to='images/', default=None, null=True, blank=True) When adding a new InputTest object, the admin selects a PicID Object (foreign key) from the existing ones. I want right after selecting it, the object to save and refresh. For example: When adding a new InputTest object, I select PIC#1 as foreign key. The program will run this overwritted method: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(InputTest, self).save(force_insert, force_update, using, update_fields) self.image_field_crop = self.pic_id.img super(InputTest, self).save(force_insert, force_update, using, update_fields) Then when the pages refreshes, the image_field_crop is auto-completed with the PIC#1.img and I can use it in CropperJS (using CropperImageField) Is it possible to do this? To auto-save the object and refresh the page right after selecting the pic_id when adding a new InputTest. -
How to use python to web scrape a website which doesn't store data in a good way?
I am working on a project of school student's guide in django.I want to scrape a pre-existing website.But that website does not stores its data like it is not ordered.Here is an example link:http://www.brainkart.com/article/Exercise-1-1--Inverse-of-a-Non-Singular-Square-Matrix_39061/ How do i scrape that website with python?By doing so,I could use those images in the website appropriately.Any help would be appreciated. Thank You, in advance. -
Django deployment checker
Some time ago, I found a website which checks you django deployment url. It checked headers, best practices, ssl, common mistakes, vulnerabilities, etc. all open. But I lost the url of that. Do you know about it site? have you it url? pls -
Django: User administration (create, change, delete) restricted to own group
I have a django application with different user roles. Depending on the roles different content is available: class User(AbstractUser): is_appadmin = models.BooleanField(default=False) is_appuser = models.BooleanField(default=False) is_someuser = models.BooleanField(default=False) The same roles should be used for administration. Especially should it be possible to have one "admin" (A) per value of D to create / edit / delete user profiles but without having superuser privileges and without users of other values for D's displayed. What is the easiest way to achieve this? group / role A: create, change and delete users of B and C with the same value for D access to admin interface group / role B + C: change own user profiles not necessarily access to admin interface group / role C: may belong to different D D: m:n relationship table used to filter data displayed -
Filtering foreign Key content in django templated using if statement
I have two models with one being a foreign key to another. A user can only submit an answer. am trying to use the if statement to check if an answer exit for a user then the submit answer button should change the update button the template. class Assignment(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=500) course = models.ForeignKey(Course, on_delete=models.CASCADE) class_or_level = models.ForeignKey(StudentClass, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) file = models.FileField(upload_to='assignment', blank=True, null=True) Text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) date_expire = models.DateTimeField() class Answer(models.Model): slug = models.SlugField(max_length=500) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) student = models.OneToOneField(User, on_delete=models.CASCADE) file = models.FileField(upload_to='assignment') date_added = models.DateTimeField(auto_now_add=True) this the template> What the users submitted answer to show if he does submit one else show the form like to submit answer {% for assignment in assignment_list %} <h4>{{ assignment.title|truncatewords:12 }}</h4> {% if assignment.answer %} {{ assignment.answer.file }} <button> <a href="">Update Answer</a></button> {% else %} <button> <a href="">Summit Answer</a></button> {% endif %} {% endfor %} -
How to implement Razor-pay in Django?
I am new to Django and new to payments in Django and am having a hard time understanding Razor-pay integration from their official docs. Is there a open-source project that I can reference or some tutorials that can help? Thanks in advance -
Give a ForeignKey Form Field a value of a Queryset
So I have two Models that I want to relate with a ForeignKey. One of the ModelForms I want to have it's Foreign Key field pre populated before the model gets created. The info from the ForeignKey comes from a ListView (List of Cars that belong to clients) template. MODELS.PY class ClientCar(models.Model): license_plate = models.CharField(max_length=20, unique=True, name='license_plate') def__str__: pk = self.pk license_plate = self.license_plate return f"pk:{pk} license_plate {license_plate}" class CarDetail(model.Model): car = models.ForeignKey(ClientCar, on_delete=models.CASCADE, null=False) detail = models.CharField(max_length=40, null=False) So the ListView template will have the basic crud of the Car model but I also want to add a "Wash button", the wash button will pass the selected Car's pk to the CarDetail Form template. It is here where I am having issues. I can Query the PK of the car from Kwargs but I can't seem to populate the Form's field with that query or have it render on the template. VIEWS.PY class WashService(LoginRequiredMixin, CreateView): model = CarDetail form_class = WashServiceForm template_name = 'service_app/standard_wash_form.html' def get_form_kwargs(self, *args, **kwargs): kwargs = super(WashService, self).get_form_kwargs(*args, **kwargs) ctd = ClientCar.objects.filter(pk=self.kwargs.get('pk')).values('license_plate') kwargs['initial']['car'] = ctd return kwargs I have researched this and came to the understanding that in the Form for creating this model I … -
Can't find images heroku django
I deployed the project on heroku, and everything seems to load, except for images, I do not understand what the problem is. There is an assumption that this is due to different folder names on the server and local machine, based on this screenshot: Local storage - static/img Static settings: STATIC_URL = '/static/' STATIC_ROOT = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' -
Search across multiple data models in Django
My search on the site is implemented as follows: views.py: class SearchResultsView(ListView): model = Post template_name = 'app/search_results.html' def get_queryset(self): if 'q' in self.request.GET and self.request.GET['q']: query = self.request.GET['q'] object_list = Post.objects.filter(Q(title__icontains=query) | Q(text__icontains=query)) return object_list else: return None urls.py: path('search/', SearchResultsView.as_view(), name='search_results'), As you can see this is true only for one model, but I also need to do a search on all the necessary models and combine the result. How is it better to implement in your opinion? -
How can I compare 3 dates using Django?
I want to compare 3 dates to knowing the lecture is start or not. For that I have created 3 attributes which are lecture_start_date, lecture_finish_date and current date. But when I comparing them I get an error like strptime() argument 1 must be str, not DeferredAttribute but my Lecture.l_date is also string. Here is the my work def about(request,pk_test): classes = Classroom.objects.get(classroom_name=pk_test) department = Department.objects.all() ads= Ads.objects.all() student=Student.objects.all() lectures = Lecture.objects.all() mydate = datetime.today() lecture_start_date = datetime.strptime(Lecture.l_date, '%Y-%m-%`enter code here`d %H:%M:%S') lecture_finish_date = datetime.strptime(Lecture.l_date_end, '%Y-%m-%d %H:%M:%S') if mydate > lecture_start_date and mydate < lecture_finish_date : print("The lecture has been started.") In summary, I want to find the lecture is start or not according to the my local time. To find my local time I used mydate = datetime.today() and I have lecture start time and lecture and time which are coming from my database. How can I compare those ? -
Heroku Django Images not loading
Been trying to fix this a few hours, can't seem to wrap my head around it. I have whitenoise installed and the website works fine besides the images not loading. Here are my media codes: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Using Numpy in Django
I want to display the arrays elements in the given board. But I'm not able to do so. This is my views.py ''' from django.shortcuts import render from django.http import HttpResponse import numpy as np import random from time import sleep #the home will accept request when the client will send it def play(request): #for request a response is created #in HTTP format(changed) return render(request,'play.html',{'name':'M'}) # Creates an empty board def create_board(request): arr=np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) return render(request,'play.html',{'array':arr}) ''' Below is the HTML code: ''' <table> <tr> <td></td> <td class="vert"></td> <td></td> </tr> <tr> <td class="hori">{{array}}</td> <td class="vert hori"></td> <td class="hori"></td> </tr> <tr> <td></td> <td class="vert"></td> <td></td> </tr> </table> ''' Below is the webpage's table where I wish to display array elements: -
How to redirect to a path with parameter using Django Bootstrap Modal Form?
I have been struggling for a while with Bootstrap modal form for Django. My main problem right now is that I can't redirect/refresh page on success because the current URL is a path with a parameter. The URL where the modal appear is : http://127.0.0.1:8000/cheatsheet/sheet/django As in my urls.py : app_name = "cheatsheet" urlpatterns = [ path('sheet/<str:sheet_name>', views.view_sheet, name="view_sheet"), ] Now the problem is in my views.py : class CreateCategoryView(BSModalCreateView): template_name = 'testform.html' form_class = CategoryForm success_message = 'Success !' success_url = reverse_lazy('cheatsheet:view_sheet') Of course, the succes_url does not work because view_sheet is expecting a parameter that would be django in this case. But I have no idea how to pass it and really can't find the solution. By the way my final goal here would be for it to be more dynamic using AJAX. Here, the BS modal form is just creating a "category" as it could create a comment under an article. So idealy it wouldn't have to refresh the whole page but just the correct div when you create or edit a category (as you would create or edit a comment for example). -
Reload specific form field with new content using JQuery
I'm trying to dynamically filter query-set in one of my forms. The idea was i capture group and subgroup values from auxiliary forms with ajax, send them back to form's __init__ method, filter content in my form and reload it with jquery. class Press(models.Model): group = models.CharField() // ChoiceField subgroup = models.CharField() // ChoiceField class Order(models.Model): origin = models.ForeignKey(Press) class OrderCreateView(CreateView): def get_form_kwargs(self, **kwargs): kwargs = super(OrderCreateView, self).get_form_kwargs() request = self.request group = request.GET.get('group') subgroup = request.GET.get('subgroup') kwargs.update(request=request) kwargs.update(group=group) kwargs.update(subgroup=subgroup) return kwargs class OrderCreateForm(forms.ModelForm): def __init__(self, request=None, group=None, subgroup=None, *args, **kwargs): super(OrderCreateForm, self).__init__(*args, **kwargs) self.fields['local'].queryset = Press.objects.filter( group=group, subgroup=subgroup) urlpatterns = [ path('order/create/', OrderCreateView.as_view(), name='new_order'), path('ajax/order/create/', OrderCreateView.as_view(), name='ajax_new_order'), ] <script> $("#groupSelect, #subgroupSelect").change(function () { var endpoint = "{% url 'ajax_new_order' %}"; var group = $("#groupSelect").val(); var subgroup = $("#subgroupSelect").val(); $.ajax({ url: endpoint, data: { 'group': group, 'subgroup': subgroup, }, success: function () { $("#idOrigin").load(); } }); }); {% endblock %} </script> <form action="{% url 'new_order' %}" method='post' id="orderForm"> {% csrf_token %} ... <select class="form-control" name="group" id="groupSelect"> ... <select class="form-control" name="subgroup" id="subgroupSelect"> ... <div class="col-sm" id="idOrigin"> {{ form.origin }} ... <button name="submit" role="button">Save order</button> </form> But I don't know how to refresh form field so it loads with new content. I … -
Django Multiple Forms and one view
I have an issue, i don't know how to get correctly one field of one of my forms. I have a null value in the result page. Here is my code : class CharacterCreate(CreateView): model = Attributes fields = ['strength'] template_name = 'character/create.html' success_url = reverse_lazy('character-manage') def get_context_data(self, **kwargs): data = super(CharacterCreate, self).get_context_data(**kwargs) data['background'] = self.request.POST.get('background') if self.request.POST: data['character'] = CharacterFormSet(self.request.POST) else: data['character'] = CharacterFormSet() return data def form_valid(self, form): context = self.get_context_data() character = context['character'] name = self.request.POST.get('char_name') with transaction.atomic(): self.object = form.save() if character.is_valid(): account = self.request.user character.instance = self.object character.instance.account_id = account character.save() char = create.create_object(key=name) return super(CharacterCreate, self).form_valid(form) How can i get the value of my field name ? I need this value because when the form is submitted, i create another object which has the same name submitted by the form. Thanks in advance. -
Adding comment - redierecting to wrong page - get absolute url is not working
this is my views.py class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name ='Blog/comment_create.html' fields = ['cont'] def form_valid(self, form): request=self.request post = get_object_or_404(Post, id = request.POST.get('id')) form.instance.post = Post return super().form_valid(form) this is my models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) cont = models.TextField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title,str(self.user.username) ) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) on submitting comment it shows error:Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/post/4/comment/ Raised by: Blog.views.CommentCreateView No Post matches the given query. 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. traceback error:is not found it is becouse get_absolute_url is not working if i remove get_absolute_url method then the issue is exact same, it changes nothing -
Close all forms with a button in Django
I building a threaded comment system (Reddit-like) in Django 3.0 A comment can have as many replies as possible. For each comment made, a Reply form is shown below it. Now, if I don't hide the forms, the page looks very bad, cluttered with textareas. I need the following: A 'Reply' button, clicking which the reply form can be displayed/hidden. Here's what I have tried: Added a class .replyForm to the forms. Added a class .hideBtn to the hide Buttons. Used JQuery: $(".hideBtn").click(function(){ $(".replyForm").toggle(); }); Now, this works fine, but clicking a reply button opens up all the forms at the same time. This is expected as the class belonging to each form is the same. Using Django's template tags I managed to make the id of each form and button unique. Example: id = "replyForm{{comment.id}}" which renders as replyForm123 if comment.id = 123 But I am not able to use this in any productive way. I can't access the id outside the for loop (which displays the comments). I tried adding the JQuery script inside the loop, and created 2 variable, one for the id for the button, and other for the form's id. But as the loop executes, …