Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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); } -
Requests sent from Android phones causing decode error
I have the problem that POST requests sent from certain Android phones are causing TastyPie to raise the following decode error. DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xfc in position 10: invalid start byte. You passed in '{"text":"Z\xfcrich"}' (<type 'str'>) This only happens if the request was sent from some specific Huawei and Nokia Android phones. Requests sent from a Apple, Samsung or Google phone work just fine. The error message indicates that the umlaut in "Zürich" was encoded with latin-1 instead of utf-8. How can that be give the below code? # HTML5 Meta Tag <meta charset="utf-8"> # JavaScript Request $.getJSON( url, function( data ) { var text = data.objects[0].text; $.ajax({ url: "/api/v1/endpoint/", type: "POST", dataType : "json", contentType: "application/json; charset=utf-8", data: JSON.stringify({"text": text}), cache: false, }); }); -
What is the best to populate City table in django-cities-light?
I got the following error with most of the cities after running python manage.py cities_light Saving Sous-Région du Haut-Shaba, Democratic Republic of the Congo failed: IntegrityError('null value in column "region_id" violates not-null constraint\nDETAIL: Failing row contains (44806, Sous-Région du Haut-Shaba, Sous-Region du Haut-Shaba, sous-region-du-haut-shaba, 923173, , Sous-Région du Haut-Shaba, Democratic Republic of the Congo, 923173, 40, null).\n',) -
Django migrations are not applied to database
A bit of backgound: We use docker container to run our django project and since there are a number of us working on the project we have put migrations folder into gitignore (whether this is right or wrong is a separate matter) to avoid merge conflicts. Everytime makemigrations are run - it's always 001_initial.py as Docker copies the git project which has no migrations in it. It's up to migrate command which changes to apply to database. It's becoming a common issue now that sometimes when there is a new field (or a field renamed), although these changes are in myapp\migrations\001_initial.py - once migrate command is run, django thinks those changes are already in the database and it doesn't apply any migrations. We are wiping the database and re-doing the migrations which works fine for development, but obviously it doesn't work for production. There are questions relating to this and people recommended to revert to the previous migrations which seems to reset and worked for us on some occasions - for example: python manage.py migrate myapp zero But it doesn't work always if there are relations in database with entirely new tables (so django complains that table doesn't exist) and … -
Django, difference between get and filter method
This may be possible duplication of question (https://stackoverflow.com/a/46439518/10515390) which says, get() returns an object that matches lookup criterion. filter() returns a QuerySet that matches lookup criterion. Consider below model, class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) When I try to query the authors list based on specific Entry objects got error as attached below Why don't the filter queryset have no attribute 'authors' ? -
How do I check authentication across all views in Django using Pyrebase?
Okay so, ordinary Django allows you to simply: if request.user.is_authenticated: I want to be able to do the same in Pyrebase. Have the views sort of already know which user has logged in based on the current session without having to sign the user in in all views. I have tried: def sign_in(request): user = firebase.auth().sign_in_with_email_and_password('email', 'password') user_token = firebase.auth().refresh(user['refreshToken'] request.session['session_id'] = user_token I noticed this creates a session ID for me. But I don't know how to associate it with the current user and I know it has something to do with the refresh token. If I don't check authentication, anyone can visit any page of my site without signing in.