Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Submit button in a form is not working in django
In my django template when I render whole form at once, submit button works and forms get submitted or error shows up if there's any. this is actually deafult form in django. no styling or no customization has ben done: employee_add_form.html: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="" method="post" id="employee_add_form"> {% csrf_token %} {% bootstrap_form form %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} <div class=""> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> {% endblock %} but when I render like this, when I call form's fields manually one by one and apply some customized design to form like this: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="{% url 'employee:employee-add' %}" method="POST" id="employee_add_form"> {% csrf_token %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} {{ form.non_field_errors }} <div class="container"> <label for=""><b>Personal Info</b></label> <div class="border"> <div class="form-row"> <div class="col"> {{ form.first_name.errors }} <label for="">First Name</label> {{ form.first_name}} </div> <div class="col"> {{ form.last_name.errors }} <label for="">Last … -
Combining django templates with content editable for non-technical users
We use django to generate HTML pages using templates which include javascript. Our website only consists out of a limited number of pages (creating new pages isn't a common use case) and we have people editing the content without python (and html) knowledge. Is there a way to have a simple user interface where non-technical editors can (in the best case) use a WYSIWYG editor to change the content (mainly text) of a template and a developer can build the page with html, css and javascript around it? The problem we see with full CMS system like Wagtail and Django-CMS is that they don't give us the same flexibility to build the pages and don't offer the needed functionality to make our platform configurable (When setting up the system, a user can configure their specific instance of the system as many use cases have the same structure and only need specific configurations). -
form_invalid method not displaying fields in error
I have a CBV CreateView and a django form that behaves correctly when you entered data that is valid. However, when the form has fields in error (duplicate phone number or more than one primary contact phone), then is re-displayed by form_invalid method, but the fields that were previously populated are now displayed blank. The customUser field in the Phone model which is the foreign key to the user CustomUser(AbstractUser) model appears to be blank when I print the request.post data. This is my model: class Phone(models.Model): COUNTRIES = ( (55, _('Brazil')), (1, _('United States of America')), ) PHONETYPES = ( ('1', _('Mobile')), ('2', _('Home')), ('3', _('Work')), ('4', _('Other')), ) status = models.CharField(_("Record Status"), max_length=1, default='A') status_dt = models.DateTimeField(_("Status Date"), default=timezone.now) customUser = models.ForeignKey(CustomUser, verbose_name=_("User"), on_delete=models.CASCADE) phone_name = models.CharField(_("Phone name"), max_length=20, default="PH"+str(random.randint(1,99999))) country = models.IntegerField(_("Country Dialing Code"), choices=COUNTRIES) phone_number = models.CharField(_("Phone Number"), max_length=11) phone_type = models.CharField(_("Phone Type"), max_length=1, default="4", choices=PHONETYPES) verified = models.BooleanField(verbose_name=_('verified'), default=False) primary = models.BooleanField(verbose_name=_('primary'), default=False) at_user = models.CharField(_("Audit Trail (user)"), max_length=255, blank=True) at_ip = models.GenericIPAddressField(_("Audit Trail (IP)"), protocol='both', blank=True, null=True) at_dttm = models.DateTimeField(_("Audit Trail (Date-Time)"), default=timezone.now) at_action = models.CharField(_("Audit Trail (Function performed)"), max_length=255, blank=True) UniqueConstraint(fields=['customUser', 'country', 'phone_number'], name='user_unique_phone_number') class Meta: verbose_name = _("Phone Number") verbose_name_plural = _("Phone … -
update manytomany related field in django
i want to to update a field related to M2M whenever an instance been created i tried signals but it seems complicate to ManyToManyField i tried these ways but non of them worked in my case , i appreciate your helps def mobile_customer(sender,instance,created,*args,**kwargs): if created: for status in instance.imei.all(): Imei.objects.filter(pk=status.id).update(active=False) post_save.connect(mobile_customer,sender=SelectMobileCustomer) and also this in my CreateView class views.py Imei.objects.filter(selectmobile__item=self.object).update(active=False) even if i try to print Imei.objects.filter(selectmobile__item=self.object).update(active=False) the output will be 0 ! this is my model design class MobileCustomer(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=13) mobile = models.ManyToManyField(MobileStorage,through='SelectMobile') class SelectMobile(models.Model): mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) imei = models.ManyToManyField(Imei) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Mobile(models.Model): mobile_name = models.CharField(max_length=40,unique=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i appreciate your helps .. thanks -
Django - Rendering new form fields based on selected choices
Is it possible to render new form fields based on the selected form choices? Consider this model and form: class Task(models.Model): client = models.ForeignKey(models_extra.Client, on_delete = models.CASCADE) task = models.ForeignKey(models_extra.TaskType, on_delete = models.CASCADE) description = models.ForeignKey(models_extra.Description, on_delete = models.CASCADE) class TaskSelectForm(forms.ModelForm): class Meta(): model = Task fields = '__all__' How can i make it so the form renders new fields for every specific task? Assume that i have an extra model (i don't and i'm not sure that the solution is about this): class ExtraInfo(models.Model): task = models.ForeignKey(models.Task, on_delete = models.CASCADE) field = models.CharField(max_length = 100) In this new model i have 3 entries for task nr 1 -> (task1, 'Airport') (task1, 'Order nr') (task1, 'Subject') How can i make it for my template to render the new fields "Airport", "Order nr" and "Subject" when the task with id = 1 is selected? edit. I've already made this question today but i'm simplyfing it in order to get some ideas. -
Django - Class Function not returning page
I am trying to create code for my Django site which will take the user's input, perform a calculation, and then send the data back to the user in the form of a new page, however everytime I run the code, it does not create the new page nor does it post the results. Below is the function itself. def SparkCalc(request): new_item = sparkCalculator() new_item.tix = request.POST['tix'] new_item.tenrolls = request.POST['tenrolls'] new_item.crystals = request.POST['crystals'] new_item.save() total = new_item.getTotal() return render(request, 'SparkResults.html', {"title": "Spark Results"}, {"total": total}) and below is the Django page I am calling it from: <form action="/SparkCalc/" method="POST">{% csrf_token %} <label for ="tix">Please enter your single roll tickets</label> <input type="text" id="tix" name="tix"/> <label for ="tenrolls">Please enter your ten-roll tickets</label> <input type="text" id="tenrolls" name="tenrolls"/> <label for ="tix">Please enter your total crystal amount</label> <input type="text" id="crystals"name="crystals"/> <input type="submit" value="Get Results"/> </form> And finally below is the class I created: class sparkCalculator(models.Model): tix = models.PositiveIntegerField() tenrolls = models.PositiveIntegerField() crystals = models.PositiveIntegerField() def getTotal(self): return (int(self.tix)*300) + (int(self.tenrolls)* 3000) + int(self.crystals) The way I envision the code to work is that once the user enters their information into the form, Django then runs the SparcCalc function, collecting the information entered, performing the math … -
How can I link an object on save in django to an existing one if there is a matching value between them?
I'm using Django and DRF to to reconcile two lists of data (promises to pay, and payments). When uploading new payments, if the payment transaction ID shares the same ID as a promise to pay, I want to link them by saving the corresponding promise in the payment's foreign key field. I have two models: class Promise(models.Model): transaction_id = models.CharField(max_length=50) amount_promised = models.DecimalField(decimal_places=2, max_digits=8) created_on = models.DateTimeField(auto_now_add=True) class Payment(models.Model): promise = models.OneToOneField(Promise, on_delete=models.CASCADE, blank=True) transaction_id = models.CharField(max_length=50) amount_paid = models.DecimalField(decimal_places=2, max_digits=8) created_on = models.DateTimeField(auto_now_add=True) and two views: class PromiseViewSet(viewsets.ModelViewSet): permission_classes = (IsCreatorOrReadOnly,) queryset = Promise.objects.all() serializer_class = PromiseSerializer class PaymentViewSet(viewsets.ModelViewSet): permission_classes = (IsCreatorOrReadOnly,) queryset = Payment.objects.all() serializer_class = PaymentSerializer My understanding is this requires a custom save method, but I'm not certain if the magic should be happening in views or models. Either way, the logic should be something like: Loop through promises...if the new payment.transaction_id = a promise.transaction_id, break and link the two together by saving the promise.pk to the promise foreign key in the newly created payment object. And the solution would look something like this: warning, this is rough! def save(self, *args, **kwargs): #check if promise ID was manually entered, if not continue if self.promise is None: … -
How do I allow groups to access the admin page with an is_staff property?
I have 3 groups and I want two to be able to access the admin page with different permissions. I'm just building off the base user model. The closest I feel I've gotten is from a previous Stackoverflow post Django admin is_staff based on group from django.db import models from django.contrib.auth.models import User class User(User): @property def is_staff(self): if user.groups.filter(name="Level2").exists(): user.is_staff = True else: user.is_staff = False -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte
I've started making a Python project on my old computer and have decided to transfer all the files to the new one. Now, when I run python manage.py runserver it returns UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte June 20, 2020 - 12:05:37 Django version 3.0.7, using settings 'learning_log.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 676, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte``` -
How to get class name of an HTML tag from django backend
Teacher Student these span sets class= active using styles while selecting the span. How I can get the class name of the individual spans, or check any of the span is having a class="active" -
ModuleNotFoundError: No module named 'rest_framework'
I'm trying to follow a tutorial on DRF, but when I'm about to run "migrate" for the database, i get ModuleNotFoundError: No module named 'rest_framework'. As PyCharm hints, the same also applies to django_summernote and djoser I have there. I know there are some threads like this, but nothing from those seems to help - the Python console DOES recognize these modules, and they are added through INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'kursovik.apps.KursovikConfig', 'rest_framework', 'rest_framework.authtoken', 'django_summernote', 'djoser', 'kursovik'] I recently downloaded these through pip install djangorestframework pip install djoser pip install django-summernote do i need to reinstall them? -
django form not posting, but other form on page does?
I have two forms on a page. The first form properly sends a POST request to my view but the second form sends a GET (I need it to also send a POST). I've made this mistake before and this time I made sure that the button is set to "submit", but for some reason it still sends a GET. form 1 (working as intended): <form method="POST"> {% csrf_token %} <div class="row form-row"> <div class="col-sm-6"> <div class="form-group"> <label for="start_date">Start</label> <input class="form-control" type="text" data-flatpickr data-alt-input="true" data-date-format="Y-m-d" name="start_date" data-enable-time="true"> </div> <div class="form-group"> <label for="end_date">End</label> <input class="form-control" type="text" data-flatpickr data-alt-input="true" data-date-format="Y-m-d" name="end_date" data-enable-time="true"> </div> </div> </div> <input type="hidden" name="eventtype" value="availability"> <button class="btn btn-primary" type="submit">Save changes</button> </form> form 2 (sends a GET but I want this to POST): <form method="POST"> {% csrf_token %} {% if form.errors %}{{form.errors}}{% endif %} <input type="hidden" name="pk" value="{{ i.id }}"> <input type="hidden" name="eventtype" value="invite"> <button class="btn btn-primary" type="submit">Confirm</button> </form> views.py def createevent(request): if request.method == 'GET': <<code>> else: try: eventtype = request.POST.get('eventtype', None) print(eventtype) if eventtype == "availability": form = EventForm(request.POST) newEvent = form.save(commit=False) newEvent.mentor_user = request.user newEvent.requester_user = None newEvent.notes = None newEvent.save() elif eventtype == "invite": form = EventForm(request.POST) updatedEvent = form.save(commit=False) updatedEvent.isConfirmed = True updatedEvent.save() return … -
How to disable cookies in django manually
I know that there are apps for django to handle cookies, but I want to do it manually. I have a django application with only two cookies: csrftoken and sessionid. I want to add a cookie consent banner where the user can block all cokies. How can I do that? Thx for your help and stay healthy! -
Exchange instance variables between python script and django web frontend
Setup: I have a python main application that is constantly running control tasks. Django acts as independent frontend. As I operate on a Raspi with SD-card I don't want to utilize the database to minimise write cycles. Furthermore I also want to keep security in mind. Goal: Set variables / run functions in the main app from Django webpage input Show variables from main app on the django webpage like e.g. pressure with 1s update speed Question: How would you implement the exchange of data without the database as temporal storage? Suggestions: I considered Django runscript to start the main app within Django, but that would mean I have no access for debugging from my IDE any more. My prefered solution would be to run django from within main app like this but with the option to pass instance variables: from django.core import management management.call_command('runserver') Other options might be REST API, pipe, signal... Thank you for your prefered solution. -
design and implement a Django application with User and Activity Period models
design and implement a Django application with User and Activity Period models, write a custom management command to populate the database with some dummy data, and design an API to serve that data in the json format given in the link below https://drive.google.com/file/d/10r0o9Y-0a8QALwYXx7zR__cEE4bWGz4K/view?usp=sharing -
Unique message for each permission combined via bitwise operator in DRF
Question is about getting unique message in case of multiple permissions used in DRF. For example I have 2 following permissions classes: class PermOne(permissions.IsAuthenticated): message = ‘message one’ def has_object_permission(self, request, view, obj): return obj.entry_author == request.user class PermTwo(permissions.IsAuthenticated): message = ‘message two’ def has_object_permission(self, request, view, obj): return request.user.is_active class MyView( generics.CreateAPIView): permission_classes = (PermOne |PermTwo) … … … Problem is if I combine 2 or more remission with operators like | &, in case of failure instead of unique message defined in each permission class, I receive standard { "detail": "You do not have permission to perform this action." } , whereas in case of only single permission class message is taken from permission class successfully. Of course I can combine 2 permission in one class and define message choice logic inside this class, but it ok for 2 perms, and what about 5? Seem like it against the flow. Anyway, is it possible to provide unique message being used for each permission class in case of combining them via | or &??? Thank you! -
Django - Changing form fields based on previous selected choices
Is it possible to set up new fields in a form, based on the choices of the original form? Detailing a bit more about my problem, i'll show my models and forms, and i'll explain better down below. class Task(models.Model): client = models.ForeignKey(models_extra.Client, on_delete = models.CASCADE) type = models.ForeignKey(models_extra.TaskType, on_delete = models.CASCADE) description = models.ForeignKey(models_extra.Description, null = True, blank = True, on_delete = models.CASCADE) department = models.ForeignKey(Department, related_name = 'tasks', on_delete = models.CASCADE) class Count(models.Model): task = models.ForeignKey(Task, related_name = 'counts', on_delete = models.CASCADE) start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) time_spent = models.PositiveIntegerField() class TaskSelectForm(forms.ModelForm): class Meta(): model = Task fields = '__all__' exclude = ['department'] class CountAddForm(forms.ModelForm): class Meta(): model = Count fields = '__all__' exclude = ['task'] required = False I use these both forms in the same form element of my template, because what i really want is to create a Count object with a selected task. It's important that the form allows the user to select a non-existant Task object, that's why i do both modelForms instead of including the task field on the "CountAddForm". I want the user to be presented with new fields when … -
Cant Upload Images to Django Admin
I am working on e-commerce project and i am stuck at this. Whenever admin adds new product,it should also add image related to the product. So i added the the column with ImageField but i am getting error again and again. Here is my code for models class Product(models.Model): product_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(db_column='image' , blank=True, null=True) info = models.CharField(max_length=500, blank=True, null=True) def image_tag(self): if self.image: return mark_safe('<img src="%s"/>' % self.image.url) else: return 'No Image Found' image_tag.short_description = 'Image' and in admin.py class ProductAdmin(admin.ModelAdmin): list_display = ('product_id', 'name','image_tag', 'info') readonly_fields = ('image',) admin.site.register(Product, ProductAdmin) But every time i get this error Exception Type: AttributeError Exception Value:'bytes' object has no attribute 'url' I tried using escape but it still not displaying images.I am using MySQL existing database. I could really use the help. Thanks -
Django Rest Framework APIView not CSFR Exempt
Making a POST requests to register a new user returns 403 Forbidden, CSRF verification failed. Request aborted... Going by DRF documentation and knox auth documentation i have everything set up correctly. It appears that Django's SessionAuthentication is being activated even though i do not have it in my DEFAULT_AUTHENTICATION_CLASSES. I have tried every potential solution i could find but nothing is working. The app is a Django rest api with React front end. Any help would be greatly appreciated. Authentication and Permission settings 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), url calling the view as_view re_path('auth/register', Register.as_view(), name='register'), Class based Register view extending APIView which should handle csrf class Register(APIView): """User Registration API View""" def post(self, request, *args, **kwargs): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() data['response'] = 'Account registered successfully' data['firstName'] = user.first_name data['lastName'] = user.last_name data['email'] = user.email data['token'] = AuthToken.objects.get(user=user).key return Response(data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Stack trace error Forbidden (CSRF cookie not set.): /api/account/auth/register [20/Jun/2020 12:15:14] "POST /api/account/auth/register HTTP/1.1" 403 2864 -
How to get multiple user input from django radio form?
I am writing a mcq app in django . I can not figure how to send post values for multiple user raiobutton choice. Do i use formsets?Then how do i go about doing that? I have been stuck on this problem views.py from django.shortcuts import render,get_object_or_404 from django.views import generic from django.urls import reverse from django.http import HttpResponseRedirect from .models import Test,Question,Choice class IndexView(generic.ListView): template_name='quiz/index.html' context_object_name='latest_tests_list' def get_queryset(self): return Test.objects.order_by('date_posted') class OverviewView(generic.DetailView): model=Test template_name='quiz/overview.html' class AnswerView(generic.DetailView): model=Test template_name='quiz/answer.html' I would like to make the post data to return every choice the user made for every question in a test. -
Getting empty request.FILES in Django
I'm new to django and I'm currently working on csv files processing API. The problem is that I'm trying to upload a csv file but request.FILES is always empty. I'm using postman post request with a binary data body to test this API and here is view.py: from django.http import HttpResponse as hp from django.views.decorators.csrf import csrf_exempt @csrf_exempt def uploadStats(req): if req.method == 'POST': print(req.FILES) return hp('No stats') print(req.FILES) returns <MultiValueDict: {}> any help ? -
Password Not Matching while trying to authenticate when using Custom Django Model
def userLogin(request): if request.method=='POST': try: email=request.POST['email'] password = request.POST['password'] if StudentUser.objects.filter(email=email).exists(): user = auth.authenticate(email=email,password=password) if user is not None: auth.login(request,user) messages.success(request,'Successfully Loggedin') return redirect('/') else: messages.warning(request,'Password does not match') return redirect('login') else: messages.error(request,'No Account registered with this mail') return redirect('login') except Exception as problem: messages.error(request,problem) return redirect('login') return render(request,'login.html') As a part of my project I want to have two different kind of user table in my database, one for normal user one for admin users. So while creating a django custom user model I didn't add AUTH_USER_MODEL = 'accounts.User' this line in my settings.py file. So when I am trying to log in or authenticate using this user model it is giving me password does not match error. How can i authenticate it without changing the django Auth model. and while am trying to do this password = password.set_password this is giving me error 'Str type object has no method set_password' , how can I log in or authenticate? -
Django 3 ModelForm has no model class specified
using inbuilt User model but gives error class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model:User fields=('username','email','password') -
starting python Django
I've recently done a 10-hour python course in which I covered numbers, strings, logic, data structures, loops, functions and touched over oop. to start backend web development using Django framework do you think this is enough to start? also, does anyone know a good python Django course out there, I was thinking of doing the Django course https://www.udemy.com/course/django-python/ by mark but any other course suggestions are welcome. thankyou in advance -
JavaScript while loop + setInterval doesn't work in Django
I have a background job in Python RQ. It takes about 10 sec to finish. I need to check whether the job is finished. And when it's finished, display the result. I want to check with JS each second whether the job is finished. If it's not finished - show "Loading ... " message to the user. If it's finished - show the result. I'm trying to do the checking with JavaScript. I've tried several variants, but nothing works. var job_result = {{ job_result }}; var loadingMessage = function () { document.write("Loading ..."); } while (job_result == undefined) { setInterval(loadingMessage, 1000); }