Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why do I get error in Django : unsupported operand type(s) for |: 'Model' and 'Model'
So I have a model named Question. There are three types of objects in Question, and I'm trying to query those objects separately, then merge first objects of each. Like this: def getQuestion(request): typeOne = Question.objects.filter(type=1).order_by('question_number') typeTwo = Question.objects.filter(type=2).order_by('question_number') typeThree = Question.objects.filter(type=3).order_by('question_number') questionsOfTheDay = depthOne[0] | depthTwo[0] | depthThree[0] # I've tried below as well, with chain imported # questionsOfTheDay = chain(depthOne[0], depthTwo[0], depthThree[0]) serialized = QuestionSerializer(questionsOfTheDay, many=True) return Response(serialized.data) I don't see what I've done wrong, but I keep getting the error "unsupported operand type(s) for |: 'Question' and 'Question'". What do you think is the problem? I appreciate it in advance. -
XmlHttpRequest request element is None
I am using Django and trying to send webcam data using XMLHttpRequest to background (view.py) in order to process each frame. I follow this link and most people suggests similar method for my problem. $(document).ready(function(){ $('#trigger_button').click(function(){ navigator.mediaDevices.getUserMedia(constraints) .then(stream => { document.getElementById("myVideo").srcObject = stream; }) .catch(err => { alert('navigator.getUserMedia error: ', err) }); drawCanvas.width = v.videoWidth; drawCanvas.height = v.videoHeight; imageCanvas.width = uploadWidth; imageCanvas.height = uploadWidth * (v.videoHeight / v.videoWidth); drawCtx.lineWidth = 4; drawCtx.strokeStyle = "cyan"; drawCtx.font = "20px Verdana"; drawCtx.fillStyle = "cyan"; imageCanvas.getContext("2d").drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth)); imageCanvas.toBlob(postFile, 'image/jpeg'); }); }); function postFile(file) { var formdata = new FormData(); formdata.append("image", file); formdata.append("threshold", scoreThreshold); var xhr = new XMLHttpRequest(); xhr.open('POST', apiServer, true); xhr.onload = function () { if (this.status === 200) { var objects = JSON.parse(this.response); drawBoxes(objects); imageCtx.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth)); imageCanvas.toBlob(postFile, 'image/jpeg'); } else { alert(this.status); } }; xhr.send(formdata); } Then, I am trying to access data in the request in view.py as follow: def control4(request): print(request.POST.get('image')) print(request.POST.get('threshold')) return render(request, 'local.html') However, although request.Post.get('threshold') returns a value, request.POST.get('image') returns None. Besides, this method repeats three times and then it stops to send feedback. I … -
define you own Meta class options
the following link list all possible metadata options for a Django model: https://docs.djangoproject.com/en/3.1/ref/models/options. Does Django provide a framework to extend the list by defining my own metadata options? e.g., I want to add a custom option secured = True to mask the value of some fields. If so, how? -
Django TypeError 'dict' object is not callable
I get an Error for the line: username = login_form.cleaned_data('username'), because somewhere it seems to be a dict, but I cannot understand why. Can anyone please tell me, what the problem is? views.py def index(request): return render(request, 'web/base.html') def register_view(request): register_form = UserCreationForm() if request.method == "POST": register_form = UserCreationForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data("username") password = register_form.cleaned_data("password1") user = authenticate(request, username=username, password=password) if user: login(request, user) return render(request, 'web/register.html', {'register_form': register_form}) def login_view(request): login_form = AuthenticationForm() if request.method == 'POST': login_form = AuthenticationForm(data=request.POST) if login_form.is_valid(): username = login_form.cleaned_data('username') password = login_form.cleaned_data('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return render(request, 'web/login.html', {'login_form': login_form}) def logout_view(request): logout(request) return redirect(reverse('web:index')) -
How to select data from oracle table and return into nested json with django rest framework
I have data in oracle as below And I want to return nested json like this I have data in oracle as below Currently I have to create another table for machine code to use foreign key in models.py and serializers.py but I want to know is it possible to select from 1 table and return into nested json? -
how to display the information that related to a specific user
i have this Model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = models.CharField(max_length=200, null=False) zipcode = models.CharField(max_length=200, null=False) date_added = models.DateTimeField(auto_now_add=True) and this view def view_profile(request): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.all() args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} return render(request, 'store/profile.html', args) template {% for sa in shippingAddress %} <p>address: {{ sa.address }}</p> <p>city: {{ sa.city }}</p> <p>state: {{ sa.state }}</p> <p>zipcode: {{ sa.zipcode }}</p> {% endfor %}`enter code here` the problem is the template display all the Shipping Addresses in the DB and i want it just to display the Shipping Address that related to the signed in user Thanks -
Translating a pluralized string in Django
When working with a translated string that needs a pluralized word, is it best to just pass in the pluralized word or use ngettext and have a singular/plural sentence? Example 1 (passing in the pluralized word): ugettext("You have {count} {apple_pluralized}").format( count=apple_count, apple_pluralized=ngettext("apple", "apples", apple_count) )` Example 2: ngettext("You have {count} apple", "You have {count} apples", apple_count).format(count=apple_count) My understanding is the second approach is always recommended because it's not always as simple as swapping in a word. For example, even in English, there is 1 object vs there are 2 objects. Is this correct? And if so, are there any situations where the first approach might be preferred? -
not able to access any course materiel in open edx
I have installed open edx and now want to set up ios app but I can not see my courses content I get this error ( your action could not be completed) -
Django admin: created users have plain text password and can't login
I want to have a custom tab for staff users so in admin.py I do: class StaffUser(User): class Meta: proxy = True @admin.register(StaffUser) class AdminUserAdmin(admin.ModelAdmin): pass But on the admin site, whenever I add a new user with this interface I can't log in with it since for some reason it sets it's password as plain text instead of hashing it. I've read this post BUT if I do that and change StaffUser to inherint from AdminUserI get this other error AttributeError: type object 'StaffUser' has no attribute '_meta' -
How to print all model fields ignoring reverse related and relates fields
I am trying to print all model fields and their values as follows def pretty_print_model_fields(m: Model): if not m: data = None else: data = {} for f in m._meta.fields(): data[f.name] = getattr(m, f.name) return data The issue is some of reverse_related does not exist -> error RelatedObjectDoesNotExist How can I ignore reverse_related and related fields all together -
When deploying Django application on cpanel, application does not connect to static files
I am trying to deploy django application from cpanel. I have managed to deploy the site and everything works apart from the static files part, because my website loads without any styling. My settings.py part looks like this : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'assets'), ] STATIC_ROOT= os.path.join(BASE_DIR,'static') When I run command on cpanel terminal command "python manage.py collectstatic", It runs fine and copies over the files however website loads without styling. Also my base html looks something like this (in case I need to change something there however on local server everything was running fine): {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>About</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Work+Sans:100,200,300,400,700,800" rel="stylesheet"> <!-- {% static 'website/css/owl.carousel.min.cs' %} --> <link rel="stylesheet" href="{% static 'website/css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'website/css/animate.css' %}"> -
Trying to write a unit test for django-rest-passwordreset, but the password seemingly will not change in the test?
I have the standard installation of django-rest-passwordreset. I am trying to test the password reset process. Here is my unit test: def test__password_reset_resets_password_success(self): testing_password = "Testing12345" # Generate a user and trigger the password reset user = self.login_basic_user() user.set_password(wrong_password) body = {"email": user.email} self.make_request("POST", url=self.password_reset_url, data=body) # Go and get the password reset email and token self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] url, token = self.get_url_and_token(message.body) # Resetting the password body = {"password": testing_password, "token": token} resp = self.make_request("POST", url=self.password_change_password_url, data=body) self.assertEqual(resp["status"], "OK") self.assertTrue(user.check_password(testing_password)) However, for some reason the check_password at the end does not return True with the new password. It only returns true with the old password. It seems that for some reason the POST is not causing the new password to be saved to the database. Why might this be? I have tested the urls manually with the DRF interface, so I know the password resets successfully that way. -
Django: MultipleChoiceFilter on Model TextChoices
I have a Model which holds models.TextChoices. class Visit(BaseModel): class VisitStatus(models.TextChoices): INQUIRED = 'INQ', _('Inquired') OPTIONAL = 'OPT', _('Optional') CONFIRMED = 'CON', _('Confirmed') ACTIVE = 'ACT', _('Active') INACTIVE = 'INA', _('Inactive') CANCELLED = 'CXL', _('Cancelled') I am trying to use the MultipleChoiceFilter from django-filter as follows: class VisitFilter(django_filters.FilterSet): status = django_filters.filters.ChoiceFilter(choices=models.Visit.VisitStatus, empty_label=None) class Meta: model = models.Visit fields = ['status'] I keep getting the following TypeError Exception Type: TypeError Exception Value: __call__() missing 1 required positional argument: 'value' Any suggestions? -
Manually rendered form fields do not save data
I really wanted to figure this out myself and I spent over 4 hours on the subject but I give up now. I have a form that is supposed to save data, and if I lay out the form with the {{ form }} tag everything works great. If I put in to form with individual tags like {{ form.client_email }}, the form data is not saved to the database. I need to render these fields manually for front end purposes but I just couldn't figure out how to do it. I appreciate your help a lot. Here is my code. views.py def client_list_view(request): if request.method == 'POST': form = ClientModelForm(request.POST) if form.is_valid(): client_title = form.cleaned_data["client_title"] client_email = form.cleaned_data["client_email"] client_turkishid_no = form.cleaned_data["client_turkishid_no"] client_tax_no = form.cleaned_data["client_tax_no"] client_tax_office = form.cleaned_data["client_tax_office"] client_contactperson = form.cleaned_data["client_contactperson"] client_phone_number = form.cleaned_data["client_phone_number"] Client.objects.create( client_title=client_title, client_email=client_email, client_turkishid_no=client_turkishid_no, client_tax_no=client_tax_no, client_tax_office=client_tax_office, client_contactperson=client_contactperson, client_phone_number=client_phone_number ).save() return redirect("books:client-list") else: form = ClientModelForm() client_list = Client.objects.all().order_by("client_title") context = {'client_list' : client_list, "form": ClientModelForm} return render(request, 'clients/client_list.html', context=context) Working template <div id="clientModal" class="modal bottom-sheet"> <div class="modal-content"> <form method="POST"> {% csrf_token %} {{form}} <button class="btn">Ekle</button> </form> </div> </div> Not Working Template <div id="clientModal" class="modal bottom-sheet"> <div class="modal-content"> <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab … -
Django - getting the selected results return from data in template inside a for- loop
I having some issues in getting the selected to show on my res summary. I was able to get data from an api and load inside a Django template. On the Django template, this data is in a for loop, . it only works when I selected the first data inside that for loop which I am able to display on the res summary and insert into the database but for the rest of the data I cannot. -
Django + nginx security in production
I recently found a big security breach in a project I did with django. The application was deployed in production and worked properlly using Nginx, I also use python decouple to separate my sensitive information. Here is the permissions on the project files: -rw-r--r-- 1 rouizi rouizi 151 Oct 8 21:30 .env -rw-rw-r-- 1 rouizi rouizi 65 Jul 9 07:50 .env.example drwxrwxr-x 8 rouizi rouizi 4096 Sep 23 15:50 .git -rw-rw-r-- 1 rouizi rouizi 244 Jul 14 09:18 .gitignore drwxrwxr-x 5 rouizi rouizi 4096 Sep 22 16:17 core -rwxrwxr-x 1 rouizi rouizi 624 Jun 25 13:58 manage.py drwxrwxr-x 3 rouizi rouizi 4096 Oct 8 21:27 prof -rw-rw-r-- 1 rouizi rouizi 599 Jul 14 09:18 requirements.txt drwxrwxr-x 4 rouizi rouizi 4096 Jun 25 13:58 static drwxrwxr-x 5 rouizi rouizi 4096 Jun 25 14:02 staticfiles drwxrwxr-x 3 rouizi rouizi 4096 Oct 6 09:11 templates drwxrwxr-x 4 rouizi rouizi 4096 Jun 25 14:02 users drwxrwxr-x 6 rouizi rouizi 4096 Jun 25 13:59 venv let say my domain name is exemple.com. What I didn't know is if I try to access exemple.com/.env I can see the content of the .env file. This is really bad because this file contains the secret key and other … -
Delete db item in Django Python via Javascript button
I have written a small application in which want to build in a function which provides the possibility to delete database items (stored earlier) via a html button and Jinja (dynamic link building). Models.py Forms.py Views.py Etc. Have all been updated correctly. However the problem in building the link to delete a certain item gets triggered by the fact that i can't seem to succes in passing the db item (item.id) to the dynamic link because i have decided to put a javascript pop-up in between that asks for a confirmation before deleting the item. All attempts have failed until now. After endless searching for a solution i hope anyone can help me with this... First i generated a for loop that displays all the items in the db to which i have added a button "delete". This buttons triggers a javascript pop-up which works fine asking if the item must be deleted or the command should be cancelled. i don't seem to succeed in putting the dynamic link behind the last confirmation button. Python > Django > HTML > HTML Jinja > Javascript > HTML Jina For the moment the link has been build (lacking any better solution) as … -
Django not able to submit form using ModelForm
The form is always sending a Get request instead of a Post which has been explicitly added using method = "POST". So, not able to persist the data to db. I have just started with Django so, any help will be appreciated. Below are the code snippets: create_order.html <form method="POST" action="{% url 'home' %}"> {% csrf_token %} {{form}} <input class="btn btn-primary btn-sm" type="submit" name="Submit"> </form> urls.py urlpatterns = [ path('', views.dashboard, name='home'), path('products/', views.product, name='products'), path('customer/<str:cust_id>/', views.customer, name='customer'), path('create_order/', views.create_order, name='create_order'), ] views.py def create_order(request): form = OrderForm() if request.method == 'POST': print("In Post", request.method) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: print("In else", request.method) print(form.is_valid()) if form.is_valid(): form.save() return redirect('/') context = {'form' : form} return render(request, 'accounts/create_order.html', context) terminal output In else GET False -
Django merge querysets in one page
In django rest framework i am using pagination of 20 on a model. Now i want to make a queryset which takes 5 items which has the featured field as true. The other 15 should be items which has the featured field as false. Does anyone have an idea how to make this work? -
Django url without pk or slug (One to Many Relationship)
Please can anyone help me ou with this, I am totally lost.I am new and trying to learn django. I am trying to update my model formset using update views without using the model primary key on the url (eg: update-pet-health/<int:pet_id>/<pk>) I want it to be just update-pet-health/<int:pet_id> scenario: A pet in a vet clinic might have multiple health concerns. Model: class PetHealth(models.Model): pet_health_id = models.BigAutoField(primary_key=True, null=False) pet = models.ForeignKey('Pet', null=False, on_delete=models.PROTECT) symptom_type = models.CharField(null=True, blank=True) date_of_symptom = models.DateTimeField(null=False, auto_now_add=True) symptom_observed_by = models.CharField(null=True, blank=True) date_of_cure = models.DateTimeField(null=False, auto_now_add=True) cured_by = models.CharField(null=True, blank=True) give_medication = models.BooleanField('Propose Medication', null=False) date_medication_proposed = models.DateField('Date Medication Proposed', null=True, blank=True) Medication_given_by = models.CharField(null=True, blank=True) comments = models.TextField('Comments', null=True, blank=True) This is the form I used for...it is the same as the createview cbv Form: class PetHealthForm(forms.ModelForm): class Meta: model = PetHealth fields = [ 'symptom_type ', 'symptom_observed_by', 'cured_by ', 'give_medication', ] PetHealthFormset = modelformset_factory(PetHealth, form=PetHealthForm, extra=3) I'm trying to update the form using update view and here is my cbv for update View: @method_decorator(login_required, name='dispatch') class UpdatePetHealth(UpdateView): base = ... template_name = base + '/update_pet_observation.html' model = PetHealth form_class = PetHealthForm def get(self, request, *args, **kwargs): pet_id = self.kwargs.get('pet_id', None) formset = PetHealthFormset(queryset=PetHealth.objects.filter(pet_id=pet_id)) context = {'pethealthissues': … -
Django Foreign key relation views.py and template html
I have 3 tables related for listing a product with features, i want to list FeatureItem values with for loop in template html file. I ve tried to write a view class but i couldn't succeed. Any Suggestion which approach for views.py and template.html file would be best solution? Thanks. class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField() category = models.ForeignKey(Category, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) class FeatureItem(models.Model): feature_title = models.CharField(max_length=100) feature_description = models.CharField(max_length=100) feature_id = models.ForeignKey(Feature, on_delete=models.CASCADE) class Feature(models.Model): title = models.CharField(max_length=100) description = models.TextField() -
How can I filter the queryset I use in my ModelChoiceField field?
I have looked at several answers on SO but I haven't found one that address my particular case. I have this ModelForm which I am using in Django admin panel. class AssignInventoryForm(ModelForm): class Meta: model = Driver fields = [] template = forms.ModelChoiceField(queryset=ItemTemplate.objects.all(), empty_label="(Select Template)") template.label = 'Template' def save(self, driver): driver = self.form_action(driver) return driver I would like to be able to filter ItemTemplate like so: ItemTemplate.objects.filter(id=driver.item.id) But obviously driver is not defined at that point of the code. -
How would you write an `is_pdf(path_to_file)` function in Python?
I have a Django project that creates PDFs using Java as a background task. Sometimes the process can take awhile, so the client uses polling like this: The first request starts the build process and returns None. Each subsequent request checks to see if the PDF has been built. If it has been, it returns the PDF. If it hasn't, it returns None again and the client schedules another request to check again in n seconds. The problem I have is that I don't know how to check if the PDF is finished building. The Java process creates the file in stages. If I just check if the PDF exists, then the PDF that gets returned is often invalid, because it is still being built. So, what I need is an is_pdf(path_to_file) function that returns True if the file is a valid PDF and False otherwise. I'd like to do this without a library if possible, but will use a library if necessary. I'm on Linux. -
Upload multiple images with Django Rest Framework
I am trying to upload multiple images from a Vue app to a Django Rest Framework api. Works fine for one image and thanks to this post I made it work for multiple images. But it feels like I missed something and I was wondering how I could improve this code. It feels like hacky code because: the serializer only returns one serialized object (and although it works the serialized object seems odd) I now need to create another serializer for simple get requests with one single image Should I split the images at view level a call a simple serializer with many=True? In create method or perform_create method? Tried a couple of things but without success Thanks for any help you may provide! models.py class Photo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='photos') owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='photos') image = models.ImageField(upload_to=upload_path) view.py class PhotoViewSet(viewsets.ModelViewSet): serializer_class = PhotoSerializer permission_classes = (IsOwner,) parser_classes = (MultiPartParser, FormParser,) def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self): user = self.request.user project = self.request.query_params.get('project') if user.is_authenticated: return Photo.objects.filter(owner=user, project=project) raise PermissionDenied() serializers.py class PhotoSerializer(serializers.ModelSerializer): image = serializers.ListField( child=serializers.ImageField(allow_empty_file=False) ) class Meta: model = Photo fields = ['id', 'image', 'project'] def create(self, validated_data): images = validated_data.pop('image') for image in images: … -
Django 2.2 and Rest Framework 3.11 - partial updating model "owner" field (ForeignKey) with owner's username string instead of pk
Django 2.2 and Rest Framework 3.11 I have an Alarm model. Every alarm instance can optionally have an owner (the standard django User model). I want to be able to partially update (PATCH) an alarm by setting its owner just using his/her username (string) instead of the pk. Right now, I can update an alarm's owner only by using his/her pk. I tried various things, like: override the update() method in the AlarmSerializer class but whenever I use the owner's username string instead of the pk in the PATCH call, I get back: { "owner": [ "Incorrect type. Expected pk value, received str." ] } play with nested serializers and lookup_field but no luck so far. The api call (PATCH) should look like this: url: /api/alarms/{alarm_id}/ Payload: { "owner": "owner_username" } How can I do that? Thanks models.py from django.db import models from django.conf import settings class Alarm(models.Model): """ this class is meant to represent a network alarm (a.k.a. event or ticket) coming from some monitoring system (Zabbix, Nagios, etc.) """ customer = models.CharField(max_length=50) owner = models.ForeignKey( settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True, ) managed = models.BooleanField(default=False, blank=False, verbose_name="Managed ?") device_type = models.CharField(max_length=150) ... serializers.py from django.contrib.auth.models import User from rest_framework import …