Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set Django constraints to allow one enabled (BooleanField) object per item?
How to set Django constraints (or unique_together) to allow one enabled object per item? class Subscription(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) enabled = models.BooleanField(default=False) Should not allow to: item1 = Item.objects.get(...) sub1 = Subscription(item=item1, enabled=True) sub2 = Subscription(item=item1, enabled=True) but this should be allowed: item1 = Item.objects.get(...) sub1 = Subscription(item=item1, enabled=True) sub2 = Subscription(item=item1, enabled=False) -
To pass a value from js(HTML) to Django backend
I have done a project on building a QR Code scanner using Javascript , the value of qr was returned in a js variable. Now i cannot pass the value to django backend for futher operations My JS code <h4>SCAN RESULT</h4> <div id="result">Result Here</div> function onScanSuccess(qrCodeMessage) { document.getElementById('result').innerHTML = ''+qrCodeMessage+''; } I tried using Buttons instead of div so that clicking the button passes the button value to backend <button type="submit" id="result" name="xyz">QR VALUE</button> and in views.py def qrscanner(request): obj=request.POST.get("xyz") print(obj) return render(request,"qr_scanner.html") and this didn't succeed either, is there any way i could pass the qr value to django views -
Docker ignores middleware.py in Django Rest Project?
I have made a project where it uses blockchain service from a folder within the root of the project and middleware.py file uses the service. I have dockerized the application but when I run docker-compose it completely ignores the middleware file and just runs the Django rest framework app, but when I run the app using manage.py it uses the middleware? This is what happens when I run Docker-compose Starting ssa2_webrun_1 ... done Attaching to ssa2_webrun_1 webrun_1 | Watching for file changes with StatReloader webrun_1 | Performing system checks... webrun_1 | webrun_1 | System check identified no issues (0 silenced). webrun_1 | May 19, 2022 - 11:47:58 webrun_1 | Django version 4.0.2, using settings 'ssfa.settings' webrun_1 | Starting development server at http://0.0.0.0:8000/ webrun_1 | Quit the server with CONTROL-C. webrun_1 | RBV1sF8ExF9UhpLHZKaf27JC1Ee87pg3hL webrun_1 | [19/May/2022 11:48:03] "GET / HTTP/1.1" 200 5264 webrun_1 | RBV1sF8ExF9UhpLHZKaf27JC1Ee87pg3hL webrun_1 | Not Found: /favicon.ico webrun_1 | [19/May/2022 11:48:04] "GET /favicon.ico HTTP/1.1" 404 3295 This is what happens when I run from manage.py runserver (Correct) Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 19, 2022 - 11:49:19 Django version 4.0.2, using settings 'ssfa.settings' Starting development server at … -
Invalid HTTP_HOST header: Amazon ec2 Django
I am getting this error in my email Invalid HTTP_HOST header: ip'xx.xxxx.xxx.xx'. You may need to add ip'xx.xxxx.xxx.xx' to ALLOWED_HOSTS. I have seen many similar questions but all are giving fixes to either add this to the Allowed host or don't send this error to email. But I want to know the cause of this. Why is the ec2 instance sending a request to the Django server? -
Django admin - how to get a parameter from the url
I'm trying to make a default value in my table via the URL. I try to use the function get_year, but it returns me the first value in Year. For example, I have 2 tables: model.py class Year (models.Model): year = models.IntegerField(primary_key=True, verbose_name='Year') def __str__(self): return str(self.year) class Meta: ordering = ['year'] class RFCSTForm (models.Model): id = models.AutoField(primary_key=True) def get_year(self): selection = Year.objects.values_list('year')[0] return selection year = models.ForeignKey(Year, verbose_name='Year', null=True, blank=True, on_delete=models.CASCADE, default=get_year(Year)) budget_q1 = models.IntegerField(verbose_name='Budget Q1', null=True, blank=True) budget_q2 = models.IntegerField(verbose_name='Budget Q2', null=True, blank=True) budget_q3 = models.IntegerField(verbose_name='Budget Q3', null=True, blank=True) budget_q4 = models.IntegerField(verbose_name='Budget Q4', null=True, blank=True) avi = models.CharField(verbose_name='avi', max_length=200, null=True, blank=True) def __str__(self): return str(self.id) def total_budget(self): return self.budget_q1 + self.budget_q2 + self.budget_q3 + self.budget_q4 class Meta: ordering = ['id'] # unique_together = ('year', 'scenario') verbose_name = "RFCST Form" #Title on the maint page for this table verbose_name_plural = "RFCST Form" #Title for the navbar navigation The url: (if to be more precise, I want part of the URL, '2022') TNX -
Passing Data into Forms Django
Hypothetically; I have a simple system that has a list of choices on a screen. Each item has a button so you can add multiple supplementary items/information alongside the item selected but not change the item selected. Each item has a unique id which I want to pass into the form so that the comment is always associated with the item. I have a model that contains a foreign key that links the comment to the item and the Modelform works but I have to select the item from a drop down and I would like this information to be pre-populated in the form. This seems so simple but I have been going round in circles for days. Any pointers would be greatly appreciated -
Реализация ограничения пространства(Django 4) [closed]
Доброе время суток,подскажите пожалуйста как сделать так,чтобы юзер при регистрации получал 2 гб памяти для заливки документов, фоток итд.Как вручную с админки менять эту память? -
How would I render data from a Django model with a React frontend?
I'm currently working on a personal portfolio website using Django for the backend and database, and React for all the frontend stuff. In this program, I have various fields that I would like to update every once in a while; I have Django tables for my education history, my work experiences, my skills, and a table to hold portfolio entries. I'd like to display this information on my React frontend, where I could display a page containing cards with all the portfolio projects I've created, and a page where my work experience, skills, and education history is all displayed. Using plain Django, I would have simply selected the items from the table in views.py and passed it to the context, rendering the items as needed. With React, I don't know how I would handle such a request. The way my code currently works, in the React components, I declare objects with the required fields such as const myExperiences = [{ name: "Company name", title: "job title", description: "job description", startDate: "start", endDate: "end", location: "city, country", }] and I display them by using the map function to put them in the desired format. This is not ideal as it'd require … -
Filter field of manytomany field by a list
I would like to do the following with Django REST Framework: Filter results based on a field of a manytomany field. The query would look like this: https://endpoint.com/api/artwork/?having_style=Modern,Contemporary I would expect the result to contain all ArtWork objects which contain a relation to a Style object with name "Modern", "Contemporary" or both. The code below is not working and I don't know why. models.py class Style(models.Model): name = models.CharField(validators=[validate_style], max_length=100, unique=True) class ArtWork(models.Model): styles = models.ManyToManyField(Style, default=None) filters.py class ArtWorkFilter(filters_rest.FilterSet): having_style = django_filters.Filter(field_name="styles__name", lookup_expr='in') class Meta: model = ArtWork fields = ['having_style'] class StyleSerializer(serializers.ModelSerializer): class Meta: model = Style fields = ('name',) class ArtWorkSerializer(serializers.ModelSerializer): styles = StyleSerializer(many=True) class Meta: model = ArtWork fields = ('styles'/) views.py class ArtWorkViewSet(viewsets.ModelViewSet): permission_classes = [] queryset = ArtWork.objects.all() serializer_class = ArtWorkSerializer filter_backends = [filters_rest.DjangoFilterBackend,] filterset_class= ArtWorkFilter pagination_class = CursorSetPagination Thank you in advance! -
Django POST request parameters returns none in views.py
I want to take values from a POST request. I want to take "taken_name" value from html form to views. I tried several question's answers, but I think I' m missing very simple thing. I can not figure it out nearly 2 hours. Parameter name in html is 'taken_name'. Also urls and views parameters are true and matching with the methods which mentioned on stackoverflow. I' m getting this error : 'null value in column "visitor_name" of relation "visitor" violates not-null constraint DETAIL: Failing row contains (15, null, null, null).' This means I can't get the value from html. Tried: get value from POST request in Django res.html {% for i in allList %} <div id="createRecordModal-{{forloop.counter}}" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <form method="POST" action="/session/{{visitor_id}}"> {% csrf_token %} <div class="modal-header"> <h4 class="modal-title" name="taken_table">Masa {{i.table_number}}</h4> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-hidden="Close" ></button> </div> <div class="modal-body"> <div class="form-group"> <label>İsim</label> <input name="taken_name" type="text" class="form-control" required /> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" aria-label="Close" > İptal </button> <a href="/session/{{visitor_no}}" type="submit" class="btn btn-danger">Kaydet</a> </div> </form> </div> </div> </div> {% endfor %} urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.loginUser, name="login"), path('reservation', views.reservation, name="reservation"), path('delete/<str:table_number>', views.delete, name='delete'), path('create/<str:table_number>', views.create, name='create'), path('session/<str:visitor_id>', views.createSession, name='create2') … -
Not submitting form with enter key
I have search field and beneath it, I have a button which returns an HTMX form when being pressed. However, when I search something and press enter, the HTMX is being submitted which returns the create form. I don't want this behavior, I only want the HTMX form to appear when the button is being clicked, not when the enter key is being pushed. When I press enter for the second time though, it searches correctly! All solutions I have seen to this problem involves javascript, I would really prefer it if javascript was not being used at all. I have tried to change the "hx-trigger" but I can't get it to work. Is this possible or do I have to use JavaScript? If it is to any help, I am using django. -
Saving and fingerprint template or simply fingerpirint data in Django project
I am trying to find a way to save fingerprint data in a database within a Django project, my idea after doing some research is that I want to allow users to upload their fingerprint template to the website, but I didn't find yet the best way to store the fingerprint data if there's a better to allow users providing their fingerprint data to the backend and how the data is going to be stored in the database, I appreciate it and thanks in advance -
Append string to variable returns unsupported operand type
I want to append "credentials/" to the kwargs['request'] but I'm getting the following error.. I want the final url has credentials/ appended to it. Error: TypeError: unsupported operand type(s) for +: 'Request' and 'str' Any idea how I can append string? Function code: def reverse(self, *args, **kwargs): kwargs['request'] = self.context.get('request') + "credentials/" return reverse(*args, **kwargs) -
Django / an argument with HttpResponseRedirect is empty in my HTML page
In Views.py return HttpResponseRedirect('add_scenes?submitted=True?linkToPrevScene=%s'%ScenePrevious) ScenePrevious is a string containing "water2" In my URL of add_scenes.html it works : http://127.0.0.1:8000/scenes3d/add_scenes?submitted=True?linkToPrevScene=water2 But in the file add_scenes.html {% if submitted %} your scene was submitted successfully after {{ linkToPrevScene }} {% else %} this HTML code doesn't give output for {{ linkToPrevScene }} although {% if submitted %} is evaluated correctly -
Why this error occurs ''The view didnt return a httpredponse object. It returns None instead'
i wrote a view for form that game me this error : def add_music_view(request): #adding form view if request.method != 'POST': form = add_music_form() else: form = add_music_form(data=request.POST) if form.is_valid(): form.save() return redirect('pages:home') but when i added this unnecessary part to the end of thecode it worked without any error: context = {'form':form} return render(request,'pages/add_music.html',context) have to render each time i write a view -
Need to get existing data and save if available in the create method of nested serializers using django
serializers.py class Product_Serializers(serializers.ModelSerializer): product_id = serializers.CharField(required=False) class Meta: model = Product fields = ('product_id','product_name',) class Clientpost_Serializers(serializers.ModelSerializer): billing_method = Billingmethod_Serializers() product = Product_Serializers(many=True) def create(self, validated_data): billing_method_data = validated_data.pop('billing_method') product_data = validated_data.pop('product') billing_method = Billing_Method.objects.create(**billing_method_data) validated_data['billing_method'] = billing_method client = Client.objects.create(**validated_data) product = [Product.objects.create(**product_data) for product_data in product_data] client.product.set(product) return client def update(self, instance, validated_data): billing_method_data = validated_data.pop('billing_method') billing_method = instance.billing_method instance.currency = validated_data.get('currency', instance.currency) instance.currency_type = validated_data.get('currency_type', instance.currency_type) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.description = validated_data.get('description', instance.description) instance.street_address = validated_data.get('street_address', instance.street_address) instance.city = validated_data.get('city', instance.city) instance.state = validated_data.get('state', instance.state) instance.country = validated_data.get('country', instance.country) instance.pincode = validated_data.get('pincode', instance.pincode) instance.industry = validated_data.get('industry', instance.industry) instance.company_size = validated_data.get('company_size', instance.company_size) instance.client_name = validated_data.get('client_name', instance.client_name) instance.contact_no = validated_data.get('contact_no', instance.contact_no) instance.mobile_no = validated_data.get('mobile_no', instance.mobile_no) instance.email_id = validated_data.get('email_id', instance.email_id) instance.client_logo = validated_data.get('client_logo', instance.client_logo) instance.client_code = validated_data.get('client_code', instance.client_code) instance.save() billing_method.billing_name = billing_method_data.get('billing_name', billing_method.billing_name) billing_method.save() product = validated_data.get('product') for prod in product: product_id = prod.get('product_id', None) if product_id: product_data = Product.objects.get(product_id=product_id, product=instance) product_data.product_name = prod.get('product_name', product_data.product_name) product_data.save() else: Product.objects.create(product=instance, **prod) return instance class Meta: model = Client fields = ('client_id','currency','currency_type','billing_method','first_name',...) When I Tired to do POST and PUT method it is getting posted and updated successfully. But it is getting created everytime when I do POST, as … -
Can I store Django translation files in the database?
I'm busy adding translations to our Django app. I understand that Django finds the translation files as follows: https://docs.djangoproject.com/en/3.2/topics/i18n/translation/#how-django-discovers-translations-1 I would like to be able to edit the translation files 'on the fly'? For instance, suppose I have a DB table with country names. If I add a new country to the list of countries, I don't want to rebuild the translations file for every language as it will require a developer to get involved and deploy a new version of the site. Ideally, I want to create a Locale model and in there I have a text field where I save the translations file. The file can be compiled and saved in the model whenever updated. Django should then read the translations from there. Is something like this possible? Note this is just a simple example - my use case is more complex. We're using Heroku so I can't write to the filesystem. -
Django Sessions using cached_db and redis not fetching or saving session data
Dependencies Django==3.2.6 redis>=3.5.3,<3.6.0 django-redis>=4.12.1,<4.13.0 Settings SESSION_COOKIE_SAMESITE = None SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://:12345678@redis:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, } } MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "corsheaders.middleware.CorsMiddleware", ] Test API view @api_view(["GET"]) def test(request): print(request.session.__dict__) if not request.session.session_key: request.session.save() if not "user_id" in request.session: request.session["user_id"] = "test" request.session.modified = True print(request.session.__dict__) return Response({"hello"}) As you can see I have triggered the session to force save as well as changed the modified value to True Every time a request is made to this API, none of the session data is saved. Does anyone know why this is? -
SSL fingerprint sent to Elasticsearch (Python) not recognized
I have implemented Elasticsearch 8.2 in Python (Django project). When I first ran the Elasticsearch instance on my Mac, it generated a user password, as well as a SHA-256 fingerprint. I am trying to connect to Elasticsearch as follows in my es.py file: es = Elasticsearch('https://elastic:cIibA3=doLeNGBiYLPKc@localhost:9200', ssl_assert_fingerprint=('b87062f65fefa3405306e55906b78939acbf6f10b32e9944908937ad9a43af94')) However, I am getting the following error: TLS error caused by: TlsError(TLS error caused by: SSLError(Fingerprints did not match. Expected "b87062f65fefa3405306e55906b78939acbf6f10b32e9944908937ad9a43af94", got "b'6d4aa6321bad54a49ab0eaf4d6e56d791974031798b4dce15ff77b71f2d75799'".)) What I do not understand is that per the error message, the expected fingerprint does exactly match the one I specified in the "ssl_assert_fingerprint" param, yet it seems Elasticsearch is being sent another value by Python. Any ideas on how to fix this would be appreciated please. Django 4.0.4 Python 3.9.12 -
str indices must be integers or slices, not tuple; perhaps you missed a comma?
I am executing a RAW query in a django function in views.py but I keep getting SyntaxWarning: str indices must be integers or slices, not tuple; perhaps you missed a comma? def addusertoeng(request): alluser = User.objects.all() alleng = Grp.objects.all() if request.method == 'POST': user = request.POST.get('user') user = str(user) engagement = request.POST.get('engagement') cursor = connection.cursor() cursor.execute('''SELECT * FROM main_grp where gname=%s''',[engagement]) row = cursor.fetchone() engid = int(row[0]) print(user,type(user)) print(engid,type(engid)) cursor.execute('''INSERT INTO main_enguser(euser, eid) VALUES (%s,%s)''' [user,engid]) return render(request, 'main/engagement_add_user.html',{'alluser':alluser, 'alleng':alleng}) -
Why doesn't the code on Heroku get updated after updating the code on GitHub?
I'm making a simple TODO app and want to upload it to HEROKU. But after I updated the code on Github, heroku code remained the same. I've tried this and this and the other answers but nothing changed. Site Code Code on github here. As you can see console.log() on site has not disappeared Heroku site I even tried to re-create the app on Heroku but it didn't work. -
How to convert image to base64 in django
so I am trying to encode the image to base64 before saving it to the database here is my code: class Posts(models.Model): picture = models.ImageField(null=False, blank=False, upload_to="images/") title = models.CharField(max_length=255) description = RichTextField(blank=False, null=False) The problem is that I want to convert the image to base64 and save it as a charfield and not as storage -
Failure to save certain attributes from ModelForm to django database (Logic error)
I have a ModelForm called ListingForm. It takes data from a user but I have stopped some of the model attributes from appearing in this form as I want to feed data to those myself. I have put print statements in my createlisting function in views.py to inspect if the data is actually being saved correctltly, it turns out the data is being saved. Here is the createlisting function: def create_listing(request): if request.method == 'POST': import datetime listing_form = ListingForm(request.POST, request.FILES) if listing_form.is_valid(): bid = listing_form.cleaned_data['starting_bid'] print(bid) listing_form.save(commit=False) listing_form.user = request.user print(listing_form.user) listing_form.date_made = datetime.datetime.today() listing_form.is_active = True listing_form.category = Category.objects.get(name=listing_form.cleaned_data['listing_category']) print(listing_form.category) #The form is being saved correctly here, and the print statements give the correct results in my terminal listing_form.save() Bid.objects.create(user= request.user, value=bid, listing=listing_form.instance) all_listings = Listing.objects.all() return render(request, 'auctions/index.html', { 'all_listings': all_listings }) else: listing_form = ListingForm() return render(request, 'auctions/createlisting.html',{ 'listing_form':listing_form }) However, when I try to access the data from the model Listing from which the ListingForm is inheriting, the print statements I have put for debugging return the default values for certain fields (category and user) instead of the values I have saved in the ListingForm. Here is the code that allows me to view the … -
Django Q-Object query returns duplicate entries not matching the database
I am attempting to ascertain the membership of a user in an event (the highest level organization structure in my application). Every event holds users with one (and only one) of three access levels (manager, editor or observer). At any point, there has to be at least one manager, that being the creator of the event by default. I am using the a context processor to query the DB for any events that my currently active user has access to (via holding one of the three roles). This should return a list of all matching event objects. My problem is that when I add at least two additional users of another role to the event, the list of events for my user shows duplicate entries for that event (one per additional role, and two per additional user in that role beyond the first user). Meaning that if I add two editors, I will see two entries for the event. Adding another two observers, I see four entries total, adding a third observer will show me six entries. Adding only one observer or editor or any number of additional managers (when my own active user is a manager) will not cause … -
Why does the program open the file? - Too many open files
Previously, Pyrogram version 1.2.11 was caused this error. OSError: [Errno 24] Too many open files And this problem caused the following error: database is locked I also updated to version 1.4.8, but this error still occurs. My robot is not for advertising. Examines a series of posts on multiple channels. I divide all the posts between the bots and if there are, for example, 400 posts, each robot checks 10 posts. I do this using threads. for list_of_posts in sliced: if not __clients: log.info(f"clients are not enough but post available. \n {list_of_posts}") break i = threading.Thread(target = manage_post, args = (list_of_posts, __clients.pop())) threads.append(i) # start threads for thread in threads: thread.start() # wait for complete threads for thread in threads: thread.join() I checked the process, the number of open files varies from 200 to 500 and 1000, now they are at 837. $PID has 837 Open Files. I do not open the file at all Database and Data Storage: Redis, Postgresql Modules: Pyrogram 1.4.8, TgCrypto 1.2.2, Django 3.1.6