Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Реализация ограничения пространства(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 -
Django - Append Path to get_absolute_url
Is it possible to append path to get_absolute_url? For instance, I want to append /credentials/ to the following code so the final output would be something like /api/v2/job_templates/9/credentials/", if obj.unified_job_template: res['unified_job_template'] = obj.unified_job_template.get_absolute_url(self.context.get('request')) This is what it looks like at the moment.. Here is the full code: class WorkflowJobTemplateNodeSerializer(LaunchConfigurationBaseSerializer): success_nodes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) failure_nodes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) always_nodes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) exclude_errors = ('required',) # required variables may be provided by WFJT or on launch credentials = serializers.PrimaryKeyRelatedField( many=True, queryset=Credential.objects.all(), required=False, write_only=True ) class Meta: model = WorkflowJobTemplateNode fields = ('*', 'workflow_job_template', '-name', '-description', 'id', 'url', 'related', 'unified_job_template', 'success_nodes', 'failure_nodes', 'credentials', 'always_nodes', 'all_parents_must_converge', 'identifier') def get_related(self, obj): res = super(WorkflowJobTemplateNodeSerializer, self).get_related(obj) res['create_approval_template'] = self.reverse('api:workflow_job_template_node_create_approval', kwargs={'pk': obj.pk}) res['success_nodes'] = self.reverse('api:workflow_job_template_node_success_nodes_list', kwargs={'pk': obj.pk}) res['failure_nodes'] = self.reverse('api:workflow_job_template_node_failure_nodes_list', kwargs={'pk': obj.pk}) res['always_nodes'] = self.reverse('api:workflow_job_template_node_always_nodes_list', kwargs={'pk': obj.pk}) if obj.unified_job_template: res['unified_job_template'] = obj.unified_job_template.get_absolute_url(self.context.get('request')) try: res['workflow_job_template'] = self.reverse('api:workflow_job_template_detail', kwargs={'pk': obj.workflow_job_template.pk}) except WorkflowJobTemplate.DoesNotExist: pass return res def build_relational_field(self, field_name, relation_info): field_class, field_kwargs = super(WorkflowJobTemplateNodeSerializer, self).build_relational_field(field_name, relation_info) # workflow_job_template is read-only unless creating a new node. if self.instance and field_name == 'workflow_job_template': field_kwargs['read_only'] = True field_kwargs.pop('queryset', None) return field_class, field_kwargs def get_summary_fields(self, obj): summary_fields = super(WorkflowJobTemplateNodeSerializer, self).get_summary_fields(obj) if isinstance(obj.unified_job_template, WorkflowApprovalTemplate): summary_fields['unified_job_template']['timeout'] = obj.unified_job_template.timeout return summary_fields -
How to filter a query according to creation date?
I have a query and I want to list the objects that created today. query_emails = Email.objects.values('mail_from').annotate(mail_count=Count('mail_from'), mailts=F('mail_timestamp')).order_by() mail_timestamp is the created day and it should be today, so like .filter(mail_timestamp=today) The output of the mail_timestamp is 'mailts': datetime.datetime(2021, 11, 8, 8, 9, 35, tzinfo=<UTC>) I used today = datetime.now() but it didn't work. How can I filter this type date? -
How to override Django Q() model?
I want to query like this in Django ORM from django.db.models import Q MyModel.objects.filter((Q(flag=True) & Q(model_num__gt=15)) | (Q(flag=True) & Q(model_num__lt=7))) Are there any way I can restrict the (Q(flag=True) & Q(model_num__gt=15)) results to only first query element? Do we need to override Q model or we are having another apporach? -
after adding unique_together constraint, existing data conflicts
I have a model: class Product(BaseModel): name=models.CharField(max_length=255) shop = models.ForeignKey('shop.Shop', models.CASCADE, 'products') And there is existing data. Now I want that one shop cannot include products whose names are the same using unique_together: class Product(BaseModel): name=models.CharField(max_length=255) shop = models.ForeignKey('shop.Shop', models.CASCADE, 'products') class Meta: unique_together = ['name', 'shop'] That is ideal for new database, but for exist database exist duplicate names are problem. How to ignore or except exist data? How can I apply unique_together to incoming products? -
Adapt page display along with jQuery result
I have a Django project which executes a task and then renders a page in which I want to display different things following the state of the task. To show an example of what I want, I have these three div, with each one being displayed for a particular task state : <div id="SUCCESS"> <!-- What I want to display when the execution of my task succeeded --> </div> <div id="FAILURE"> <!-- What I want to display when the execution of my task failed --> </div> <div id="EXECUTING"> <!-- What I want to display when my task is still executing --> </div> I finally found a way of doing that by adding a style="display:none" on the div for the success and failure state, and updates the display of the divs when the state of task changes. For example, at first, only the div with id="EXECUTING" will be displayed, and then when the task state changes to 'failed', the div with id="EXECUTING" will have its display attribute changed to display:none and the div with id="FAILURE" will be changed to display:"" The code for doing this is the following : <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { let task_id = '{{ task_id }}' updateState(task_id) … -
Where the save operation triggered in django admin? And how to add confirmation button before save?
I am looking to add confirmation before save operation in django admin. I made a lot of research unable to find the correct solution. Guide me.