Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my form not getting saved in django?
I am trying to save the editted form in django but it is not working. The form is not even getting validated. I don't know what's wrong? Can someone please go through the code and tell me what is going wrong here? models.py: class DocComplaint(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) event_date = models.DateField(null=True, blank=False) document = models.FileField(upload_to='static/documents', blank=False, null=True) def __str__(self): return str(self.event_date) views.py: (Adding this because I feel like it has something to do with this view as well) class EditComplaint(UpdateView): model = Complaint form_class = EditComplaintForm template_name = 'newcomplaint.html' def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( user=self.request.user ) def form_valid(self, form): if form.is_valid(): form.instance.author_id = self.request.user.pk print("Hello") return super().form_valid(form) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) success_url = '/My-History/' class EditDocComplaint(UpdateView): model = DocComplaint form_class = EditDocComplaintForm template_name = 'newcheck.html' def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( user=self.request.user ) def form_valid(self, form): print("Hello") if form.is_valid(): form.instance.author_id = self.request.user.pk print("Hello") return super().form_valid(form) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) success_url = '/My-Documents/' forms.py: class EditDocComplaintForm(ModelForm): class Meta: model = DocComplaint fields = ['event_date', 'document' ] widgets = { … -
How to save multiple forms on Django class based view
my case is as follows: The create view is conformed for multiple forms. All the following data is related to the parent model Form. Example: class PersonForm(forms.ModelForm): class Meta: model = Parent fields = ['Title', 'description'] class EducationForm(forms.ModelForm): class Meta: model = FirstChild fields = ['School', 'Year'] class CarForm(forms.ModelForm): class Meta: model = FirstChild fields = ['Model', 'Color'] [...] My view look as follow: class PersonInformationView(CreateView): model = Person form_class = PersonForm template_name = "example/person/create.html" def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['PersonForm'] = PersonForm context['EducationForm'] = EducationForm context['CarForm'] = CarForm context['JobForm'] = JobForm context['HobbiesForm'] = HobbiesForm context['SocialMediaForm'] = SocialMediaForm return context The template look as follow: <form method="post">{% csrf_token %} <table style="width:100%"> {{ form.as_table }} <tr><td>EDUCATION</td></tr> {{ EducationForm.as_table }} <tr><td>CAR</td></tr> {{ CarForm.as_table }} <tr><td>JOB</td></tr> {{ JobForm.as_table }} <tr><td>HOBBIES</td></tr> {{ HobbiesForm.as_table }} <tr><td>SOCIAL MEDIA</td></tr> {{ SocialMediaForm.as_table }} </table> <div class="text-right"> <button type="submit" class="btn btn-primary">{% trans 'Send' %}</button> <a class="btn btn-danger" href="#" title="{% trans 'Cancel' %}">{% trans 'Cancel' %}</a> </div> </form> At the moment I don't know how to save the data to each child model. Whereas to each child model I must associate the id of the parent model and additional … -
AssertionError: 'RegisterApi' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
AssertionError at /api/auth/register I get this error 'RegisterApi' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method. class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
Python/Django: How to make sure "string".upper and "string".lower work with different languages?
I have a problem with upper and lower functions in Python/Django. I have the following line of code: UserInfo.objects.get(id=user_id).city.upper() The problem is that some of the Turkish users let me know that they are seeing the wrong information. For example one of them is from a city called "izmir". The upper function converts that into "IZMIR" it turns out the actual result should be "İZMİR". What is the right way to use upper or lower functions for any given language? I read about changing the server locale as an answer. Changing server locale for each user request does not make sense to me. What about multi-threaded applications that handle different users simultaneously? Thanks in advance for your time. -
database query via django orm in template
<ul> {% for staff in staff_list %} <li>{{ staff|title }}<br> {% for person in movie.staff.all %} {{ person }}<br> <a href="{% url 'person_page' person.slug %}"><img src="{{ person.photo.url }}"></a></li> {% endfor %} {% endfor %} </ul> I iterate over the list "staff_list" and want to take from the model "movie" the field that is in the variable "staff", but orm django calls the field "staff", but I do not have such a field, and therefore nothing is returned. How to call the data that is in the "staff" variable and not call the "staff" field -
How to create temporary links with simple JWT in Django Rest Framework and React
I'm new in JWT tokens and i want to know if there is a way to create temporary links with simple JWT tokens, i already use JWT tokens for authentication in my app, if there is not a way to do this what is the best way to do it? Thanks. -
Average rating stars and rating assign
hello two question about rating stars I would like to know how to do so that if by clicking the third the three become young is how to make the average -
Django: unable to define initial values of Form
I have the following form: class UpdateForm(forms.Form): name = forms.CharField(max_length = 15, widget=forms.TextInput( attrs={ "class": "form-control", 'required': True, 'placeholder': 'Device name' } )) turn_server = forms.ChoiceField( choices = TURN_CHOICES, widget=forms.Select( attrs={ "class": "form-control form-control-sm", } )) fps = forms.IntegerField( widget=forms.NumberInput( attrs={ 'id':'ex1', 'data-slider-id':'ex1Slider', 'type':"text", 'data-slider-min':"10", 'data-slider-max':"60", 'data-slider-step':"1", } )) bitrate = forms.IntegerField( widget=forms.NumberInput( attrs={ 'id':'ex2', 'data-slider-id':'ex2Slider', 'type':"text", 'data-slider-min':"200", 'data-slider-max':"2000", 'data-slider-step':"1", } )) class Meta: model = Device fields = ['name','fps','bitrate','turn_server'] to be used in the HTML template: <form action="." method="POST"> {% csrf_token %} {% for field in form %} <div class="form-group row{% if field.errors %} invalid{% endif %}"> <label class="col-sm-3 col-form-label" for="{{ field.id_for_label }}">{{ field.label }}</label> <div class="col-sm-6"> {{ field }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> </div> {% endfor %} <button type="submit" class="btn btn-sm btn-light">Save</button> </form> and the view.py: def control(request): template = 'template.html' context = {} context['form'] = UpdateForm(initial={ 'name': 'TestName', 'fps': '45', 'turn_server':'TestServer', 'bitrate':'500' }) return render(request, template, context) For some reason I can't figure it out, the form rendered in the template does not render with the initial values I have defined with initial. For example the fps resulted input html element is the following: <input type="text" name="fps" … -
Django: Separate fields pointing to same model field
I want two separate serializer fields to refer to the same model field, i.e, name and first_name should point to the same column, the request can be sent with either 'name' field, or 'first_name', but not at the same time. How can I do that? -
Can I install Django Rest Framework in an uploaded website in pythonanywhere?
Summary: I decided to use python for my thesis I started my project while simultaneously studying about python and django I've added a lot of contents, models, and apps in my project, and I just now realized that I need to create a Content Management System, and somebody told me to use Django Rest Framework. I started searching on how to use it, and everything that I saw installed it before creating the project, and it might be too late for me because I might have a lot of errors that I might not be able to trace.(or maybe django rest framework should really be installed before starting) Can someone tell me if its possible to just install it? Or a hint/tip for alternatives? I only have less than 2 weeks left before my defense. Thank you for the help and understanding, Im new sorry -
Can someone please answer this question and check why my form is not getting saved?
I have two pages that help my users view and edit the complaints that they register. There are two types of complaints they can register. One is a written and the other is through a document. When the user tries to edit a written complaint, the edits get saved in the model but when i followed the same logic to edit my document complaints, the users can view them but on editing and saving, the edits are not getting saved, what's wrong? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber @property def totalcomplaints(self): return Complaint.objects.count() class DocComplaint(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) event_date = models.DateField(null=True, blank=False) document = models.FileField(upload_to='static/documents', blank=False, null=True) def __str__(self): return str(self.event_date) forms.py: class EditComplaintForm(ModelForm): class Meta: model = Complaint fields = ['reportnumber', 'event_type', 'eventdate', … -
How to disable the password field in djoser for django rest framework?
Can i disable the password field in djoser as i have token authentication so i dont need the user to enter password and ill be using twitter login to verify user -
Wagtail Admin - Allow Editor to Edit Custom Setting
I have created a custom setting in Wagtail, allowing an alert banner to be edited in the admin. from django.db import models from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.admin.edit_handlers import FieldPanel from ckeditor.fields import RichTextField @register_setting class AlertBanner(BaseSetting): enable_alert_banner = models.BooleanField(default=False) text = RichTextField(max_length=3000, default="", blank=True) panels = [ FieldPanel('enable_alert_banner'), FieldPanel('text'), ] class Meta: verbose_name = "Alert Banner" I don't want to have to give Admin privileges to certain users in order for them to access this. Is there a way that I can allow Editors to access this setting from the admin menu? -
How to add data to modal body dynamically while a function in views.py is running in Django
I have a BS Modal as below: <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" align="center">Add Some value</h4> </div> <div class="modal-body"> <form action = "{% url 'add_function' %}" method = "POST" role="form"> {% csrf_token %} <table> <tbody> <tr> <td> TaskId / Topology File </td> <td><input required name="value" type="text"><td> </tr> </tbody> </table> <br> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <input type="submit" value="Save" class="btn btn-success"> </div> </form> </div> </div> </div> </div> After the form is submitted, a function runs in views.py def add_function(request): sometask1 sometask2 sometask3 sometask4 return render(request,'some.html') These task takes some time to get finished. Hence, after submitting the form from Modal, it takes time to load the next page. I want to have a modal, that can dynamically load the status of the steps in execution from add_function in modal body like below: task1: done task2: done task3: running task4: todo -
Django how to save user email from custom model to AbstractUser model through signals?
I am using Abstract user model and just adding new models based on user type. here is my model for subscriber user. class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) how to pass the email of Subscriber model to my Abstract user model through signals? here is my full code: class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) email is saving in my Subscriber model and I also want it will save in my AbstractUser model. here is two screenshot for better understands: #pic1 here you will se the email for Subscriber model: pic2 here is no email for user jhon. I want when email put in Subscriber model then it automatically send the same same eamil to User model: -
Declare custom tag filter in Django template
Am trying to declare a custom function with 2 parameters but it isn't working as expected , am getting this error : Invalid block tag on line 4: 'original|get_customer_by_status:'CONFIRMATION_PENDING'', expected 'endblock'. Did you forget to register or load this tag? This is my template code : {% original|get_customer_by_status:'CONFIRMATION_PENDING' as customer_pending_loan %} Then my custom tag filter : @register.filter def get_ids_in_list(queryset, status): if isinstance(status, list): return queryset.loan_entries.filter( status__in=status).values_list('id', flat=True) return queryset.loan_entries.filter( status=status).values_list('id', flat=True) -
Getting 404 error on some files in static folder Django
I have configured my static file in setting but then though I am getting 404 error on some files. please give me a solution. -
Python Django rest framework external post api call returning un-authorized error
I am ab it new to Django rest framework external post API calls are not working and returning un-authorized error see my view below import json import requests as requests from rest_framework.response import Response from .serializer import * from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer # Create your views here. @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def dataValidateView(request): print('data is') data = request.data.get('data') print(data) import dataValidate.config BASE_URL = dataValidate.config.BASE_URL DATA_VERIFY_URL = "{}/data-verify".format(BASE_URL) HEADERS = {"Accept": "application/json; charset=utf-8", "Authorization": "Bearer " + dataValidate.config.TOKEN, "Content-Type": "application/x-www-form-urlencoded"} print('data is') print(data) myobj = {'data': data} request.META.get('HTTP_X_FORWARDED_FOR', '') r = requests.request("POST", DATA_VERIFY_URL, data=myobj, headers=HEADERS) jsonData = r.json() print(jsonData) serializer = dataValidateSerializer(data=jsonData) if serializer.is_valid(): return Response(serializer.data) I know its working because the prins dont show -
Django and accessing POST data from forms.Form
For some reason, this form appears to only be able to POST the 'email' parameter. I would have expected that calling request.POST in the views.py file down below would have given me access to 4 variables, but I can only access 'email'. Any idea what is going on here? # forms.py class UserContactForm(forms.Form): # Correctly POSTs email = forms.CharField(widget=forms.TextInput( attrs = {'class': 'form-control', 'placeholder': 'Email...'} ), label = "Enter your email to be sent your secure login link." ) # drops from POST request second_field = forms.CharField(widget=forms.TextInput( attrs = {'class': 'form-control', 'placeholder': 'Dropped from POST request'} ), label = "I should be accessible in a POST request :(" ) # drops from POST request product = forms.CharField(widget=forms.HiddenInput(), initial="dropped :(") def __init__(self, *args, **kwargs): product_id = kwargs.pop('product_id') super(UserContactForm, self).__init__(*args, **kwargs) if product_id: self.fields['product'].initial = product_id # template <form action="{% url 'create-magic-token' %}" method="post" id="create-magic-token-form"> {% csrf_token %} {{ form.as_p }} <input type="text" name="testing_html_input_form" class="form-control" placeholder="Still drops..." required="" id="id_testing_html_input_form"> <p><input type="submit" value="Submit" class="btn btn-primary"></p> </form> #views.py @require_http_methods(["POST"]) @csrf_exempt def create_magic_token(request): print("post vars::", request.POST) # post vars:: <QueryDict: {'email': ['email@example.com']}> # the hidden variable, the second defined variable in the form, # and the variable defined by pure HTML are not accessible ... -
Django setUp class only execute once
I am currently following a django tutorial (https://youtu.be/UqSJCVePEWU?t=8655) and he uses the setUp function to make test cases. I did the same thing as him and I get an error that the username is not UNIQUE self.c = Client() User.objects.create(username='admin') Category.objects.create(name='django', slug='django') self.data1 = Product.objects.create(category_id=1, title='django beginners', created_by_id=1, slug='django-beginners', price='19.99', image='django') def test_url_allowed_hosts(self): response = self.c.get('/') self.assertEqual(response.status_code, 200) def test_product_detail_url(self): response = self.c.get(reverse('store:product_detail', args=['django-beginners'])) self.assertEqual(response.status_code, 200) so, after some hours I found that setUp is executed for every test (which does not create any problem in the tutorial) and I changed my function to @classmethod def setUpClass(self): which solves the problem, but now I don't know if I messed something up and the tutorial should work, or something in django has changed since then. Any help is appreciated and if any files or something is needed I'll provide them. Thank you in advance -
How to make web application to listen telegram channel with django
I want to provide web application to transfer messages which are posted in a telegram channel to another group. I implemented as follows with reference to https://python.plainenglish.io/telegram-channel-listener-with-python-8176ebe3c89b. This is the code which I wrote in view.py of django application. def transfer(request): api_id = '####' api_hash = '####' user_input_channel = 'https//####' TOKEN = '####' to_group_id = '####' try: client = TelegramClient('anon', api_id, api_hash) except: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = TelegramClient('anon', api_id, api_hash, loop=loop) @client.on(events.NewMessage(chats=user_input_channel)) async def newMessageListener(event, loop=None): if loop is None: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) #Get message newMessage = event.message.message if len(newMessage) > 0: print(newMessage) send_text(newMessage, to_group_id, TOKEN) else: print('Empty message') #client.start(bot_token = TOKEN) with client: client.run_until_disconnected() But it doesn't work. Error message is follows. Internal Server Error: /start_transfer/ Traceback (most recent call last): File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Documents/telegram/telegramsite/app/views.py", line 211, in transfer with client: File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/helpers.py", line 184, in _sync_enter return loop.run_until_complete(self.__aenter__()) File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/client/auth.py", line 713, in __aenter__ return await self.start() File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/client/auth.py", line 140, in _start await self.connect() File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/client/telegrambaseclient.py", line 524, in connect self.session.auth_key = self._sender.auth_key File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/sessions/sqlite.py", line 180, in … -
unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute'
I am a student learning Django. When I write the code, I get the following error: I wonder which part I wrote wrong. I would be grateful if you could help. Error: unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute' Request Method: POST Request URL: http://127.0.0.1:8000/join/join_create/1/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute' Views.py : if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.value_code = form.cleaned_data['value_code'] for i in designated_object: if i.price == Designated.price + Value.extra_cost: element.designated_code = Designated.objects.get(designated_code=id) element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code == None element.save() -
How to fetch images from Django rest framework?
I am trying to fetch the images from my django API to react. Apart from images every other data is getting fetched perfectly, but images are not showing on react frontend. models.py from django.db import models class Test(models.Model): name = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, default='default.jpg') def __str__(self): return self.name serializers.py class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = '__all__' views.py class Testview(APIView): def get(self, request): test = Test.objects.all() serializers = TestSerializer(test, many=True) return Response(serializers.data) settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'images') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In addition when i tested this api on postman it worked fine. but at front it is not showing any images or error. -
how setting function after a few minutes run again in Django
I trying make a auto function in Django i reseached all afternoon i tried with library Selery but i can't I try this but fail setting.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Makassar' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'MultiLevelApp.tasks.task_number_one', 'schedule': timedelta(seconds=30), } } tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from .views import autocheck @shared_task def task_number_one(): autocheck() print("check") viewss.py from .tasks import task_number_one task_number_one() end it just run 1 times [enter image description here] -
3 table join in Django
I have 3 tables in a Django based course(and related book) management web app. 3 tables are : Title(book table), CourseInfo(course table), material(course-book relation table). Title table: id title 1 book1 ... CourseInfo table: id title code 1 course1 ICT1 ... material table: id book_id course_id 1 1 1 ... material table correlate book and course(one course could have multiple books and vice versa) Now I want to join select from these 3 tables, to get all the course code for each book . how to do that join select in Django?