Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How do I formulate this complex database query with Django 3.0?
I have the following table: Now I want to group the data by code, have a sum of visitors and the number of total nights the visitors stayed for each. I can do the first bit with this query: result = Entry.objects.filter(owner=request.user).values("code").annotate( total_visitors=Sum("visitors")) This yields something along those lines: [{'code': 'AT - Wien', 'visitors': 2}, {'code': 'CN - China', 'visitors': 4}, ...] I would need something like this: [{'code': 'AT - Wien', 'visitors': 2, 'nights': x}, {'code': 'CN - China', 'visitors': 4, 'nights': x}, ...] Now the problem is the number of total nights they stayed. For each entry, I would need to do the following to calculate that: nights = (departure - arrival) * visitors How do I do this the right way? I can do it in code and iterate over the individual entries but there has to be a cleaner way. Thanks! -
Django logout not working - can't understand why
Hi guys hope someone can help me here. I am just starting to create a simple web app using django and I am confused why this isn't working. views.py from django.shortcuts import render, redirect from django.contrib.auth import login, logout def index(request): return render(request, "fittracker/main.html") def login_view(request): pass def logout_view(request): logout(request) return redirect("fittracker/main.html") def signup(request): pass urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path("logout/", views.logout, name='logout') ] I am getting this error I have tired looking at the official docs, and this should redirect, but I am not sure why it isn't -
How to generate textboxes dynamically based on user input number in django?
I am developing a Todo App in which i want to add a new field which takes input as a number and when the user enters, say 3, the app should return 3 empty textboxes and if the user change the number to say 4, then it should refresh to 4 textboxes . So, how should i do it in django using views, models and html. These are my files: views.py from django.shortcuts import render from django.http import HttpResponseRedirect from . models import TodoItem def todoview(request): all_todo_items= TodoItem.objects.all() return render(request, 'todo.html', {'all_items': all_todo_items }) def addTodo(request): new_item = TodoItem(content =request.POST['content']) new_item.save() return HttpResponseRedirect('/todo/') def deleteTodo(request, todo_id): item_to_delete= TodoItem.objects.get(id=todo_id) item_to_delete.delete() return HttpResponseRedirect('/todo/') models.py from django.db import models class TodoItem(models.Model): content = models.TextField() todo.html <div class="p-3 mb-2 bg-warning text-dark">This is the Todo Page</div> <div class="p-3 mb-2 bg-info text-white">HelloPulkit!!!</div> <ol> {% for todo_item in all_items %} <li>{{todo_item.content}} <form action="/deleteTodo/{{todo_item.id}}/" style="display: inline;" method="post">{% csrf_token %} <input class="btn btn-secondary btn-sm"type="submit" value="delete"/> </form> </li> {% endfor %} </ol> <form action="/addTodo/" method="post">{% csrf_token %} <input type="text" name="content"/> <input class="btn btn-primary btn-sm"type="submit" value="add"/> </form> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> -
Getting error 405 while using ModelFormMixin with DetailView
I want to create a DetailView page which displays the detail of a model but I want to add a Comment section in the DetailView page using ModelFormMixin. This is my views.py code: class PostDetailView(ModelFormMixin, DetailView): model = UserPost context_object_name='post_detail' form_class = UserCommentForm def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(*args, **kwargs) context['form'] = self.get_form() return context def get_absolute_url(self): return reverse(request, 'basic_app:post_detail', kwargs={'pk':self.pk}) But when I hit the submit button it shows the following error: When I hit enter it shows this error. This is the browser with the detailview page -
I get a Type Error when posting data using via REST. It says I may have a writable field on the serializer class that is not a valid argument
full error: Got a `TypeError` when calling `Certificate.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Certificate.objects.create()`. You may need to make the field read-only, or override the CertificateSerializer.create() method to handle this correctly. I have a certificate model which has the clean() and get_remote_image() methods since there are two options of posting image to my database, either with urls or file upload - so when one is already selected the other one is no longer needed. if url is the selected option, it saves to the image field. I get the error when posting data. models.py class Certificate(models.Model): certificate_name = models.CharField(max_length=50) template_img = models.ImageField(blank=True, default='', upload_to='certificate_templates') template_url = models.URLField(blank=True, default='') names_file = models.FileField(blank=True, default='', upload_to='names_files') names_csv = models.TextField(blank=True, default='') Y_RATIO = 1.6268 def get_remote_image(self): if self.template_url and not self.template_img: img_result = requests.get(self.template_url) img_name = os.path.basename(self.template_url) with open(os.path.join(TEMP_DIR, img_name), 'wb') as img_file: img_file.write(img_result.content) self.template_img.save( img_name, open(os.path.join(TEMP_DIR, img_name), 'rb') ) self.save() def clean(self): if not self.template_img and not self.template_url: raise ValidationError({'template_img': 'Either one of template_img or template_url should have a value.'}) if not self.names_csv and not self.names_file: raise ValidationError({'names_csv': 'Either one of names_csv or names_file should have a value.'}) …