Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to perform AND condition on many to many field django
i have two models class Sale(AuthorTimeStampedModel): product = models.ManyToManyField( Product, related_name='sale_product', null=True, blank=True) def __str__(self): return f"{self.id}" class Product(AuthorTimeStampedModel): id = models.IntegerField() now i want to apply query set to get all sales which have product_id 1 and 2 i am able to find Q function but it will result or condition but i want and condition -
How to modify a field's json in Django Rest Framework
There's this model: class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') savers = models.ManyToManyField('User', blank=True, null=True, related_name='saved_posts') likes = models.IntegerField(default=0) And its Rest serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' There is a field named timestamp in the model. I used to use a custom serializer function inside the model class so it would return the timestamp as: 'timestamp': self.timestamp.strftime('%b %d %Y, %I:%M %p'). How can I do so using Rest? -
Zappa S3 Django Media Upload Times Out
I am trying to configure Zappa and Django to be able to upload media files but I am getting a weird permission error that is not specific enough for me to debug. When I go to the Django admin and upload a file with a few kbs to a model I get a: {"message": "Endpoint request timed out"} After further examination with zappa dev tail [1649077754253] [DEBUG] 2022-04-04T13:09:14.253Z b43408d4-f54d-4187-ab31-af6caf6dcddd Certificate path: /var/task/certifi/cacert.pem [1649077754254] [DEBUG] 2022-04-04T13:09:14.254Z b43408d4-f54d-4187-ab31-af6caf6dcddd Starting new HTTPS connection (1): bucket-static-media.s3.us-east-2.amazonaws.com:443 [1649077783696] 2022-04-04T13:09:43.695Z b43408d4-f54d-4187-ab31-af6caf6dcddd Task timed out after 30.03 seconds So the task times out I am making the assumption that it is some missconfigured permissions between the S3 and the Lambda. However I am not able to figure out what is wrong. If I look at the ZappaLambdaExecutionRole permission: It has a policy called zappa-permissions that has S3 permissions for all actions for all resources. The VPC linked to the Lambda Function is: vpc-b7e14cdc (XXX.XX.0.0/16) | Default Subnets: subnet-1ed00575 (XXX.XX.0.0/20) | us-east-2a subnet-f2cfcc88 (XXX.XX.16.0/20) | us-east-2b subnet-4cc2a900 (XXX.XX.32.0/20) | us-east-2c For the security group: Inbound Rules sgr-033b1c122d9c8fd4b – HTTPS TCP 443 Outbound Rules All I even created a VPC Endpoint to S3 global that connects to the security … -
Databse error while running Django with MongoDB
I'm trying to run my Django project and when I want to load the product to the homepage I encounter this problem : DatabaseError at / No exception message supplied Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1 Exception Type: DatabaseError Exception Location: E:\EKart\env\lib\site-packages\djongo\cursor.py, line 59, in execute Python Executable: E:\EKart\env\Scripts\python.exe Python Version: 3.10.2 Python Path: ['E:\\EKart', 'D:\\Python\\python310.zip', 'D:\\Python\\DLLs', 'D:\\Python\\lib', 'D:\\Python', 'E:\\EKart\\env', 'E:\\EKart\\env\\lib\\site-packages'] Server time: Mon, 04 Apr 2022 15:02:50 +0000 -
fetch record form table and print in views.py django
I am creating a webpage in Django, Where I'm printing some lines using a table from DB. I need to fetch user click and perform seprate action on each button dynamically. Here is my home.html <div> <table style="width:90%"> {% for request_ in request_index %} <tr> <form method="POST" action="{% url 'Request_for_DB_1' %}" enctype="multipart/form-data"> {% csrf_token %} <td><b> Would you like {{ request_.id }} to give {{ request_.user_name }} permission? </b></td> <td>&nbsp; </td> <td><input style="background-color:#CFCFCF; color:blue" type="submit" value="Yes" name={{ request_.id }}></td> <td><input style="background-color:#CFCFCF; color:blue" type="submit" value="No" name={{ request_.id }}></td> </form> </tr> {% endfor %} </table> </div> Here is Views.py def Request_for_DB_1(request): request_index = Permission_Request.objects.all() user_id = request_index.id current_user = request.POST.get('name') if user_id == current_user: clicked_user = "Condition is Correct... " else: clicked_user = "Condition is Wrong... " messages.info (request, clicked_user ) return redirect('/') By this view I am getting current_user = None always and this error 'QuerySet' object has no attribute 'id' The image of my table and tbale name is "Permission_Request" Kindly guide me how to fix this issue. -
Factory boy creation of an object with several default values (reverse foreign key)
I am using django 3.2 and factory boy 3.2.1 and try to create a factory of a plugin model which automatically creates 2 suitable configuration items with it: class PluginConfiguration(Configuration): plugin = models.ForeignKey( ProductPlugin, null=False, blank=False, on_delete=models.CASCADE, related_name="configurations", ) key = models.CharField(max_length=100,) value = models.CharField(max_length=255,) category = models.PositiveIntegerField(choices=Category.choices, default=Category.GENERAL,) class PluginConfigurationFactory(factory.django.DjangoModelFactory): class Meta: model = PluginConfiguration plugin = factory.SubFactory(ProductPluginFactory) key = factory.fuzzy.FuzzyText(length=20) value = factory.fuzzy.FuzzyText(length=20) category = PluginConfiguration.Category.GENERAL class ProductPluginFactory(factory.django.DjangoModelFactory): class Meta: model = ProductPlugin name = "MyPlugin" type = ProductPlugin.Type.APP password_required = False @factory.post_generation def configurations(obj, create, extracted, **kwargs): if not create: return if extracted: for n in range(extracted): PluginConfigurationFactory(plugin=obj) else: PluginConfigurationFactory( plugin=obj, key="base_name", value="cobra", category=PluginConfiguration.Category.GENERAL, ) PluginConfigurationFactory( plugin=obj, key="appId", value="MyApp", category=PluginConfiguration.Category.GENERAL, ) Extracted in this case should simply create a certain amount of config items. The problem is, that if I try to access plugin.configurations.all() I get an error message > configs = plugin.configurations.all() E AttributeError: 'PostGeneration' object has no attribute 'all' The factory is called this way plugin = ProductPluginFactory() configs = plugin.configurations.all() As this is not a simple attribute but an relation (RelationManager) the error is correct, but how would I do what I want then? Thanks & Regards Matt -
Add lat,lon pairs to an openlayers map in Django
I have a django platform that I have a created with the following: Upload/ handle an upload of a CSV file List of items that can be checked/ unchecked Handle an OpenLayers map A section to view a chart using Highcharts My question is how do I: Handle an uploaded CSV file with lat,lon, id so that once it is uploaded, the lat,lon points are automatically loaded on the openlayers map To view a timeseries chart based on the data queried from some database for each of the lat,lon points that is clicked by the user. Here is a sample csv file dataset: [lat,lon,ids] [0,30,1], [-1,31,2], [-3,32.3,3]} items you can check or uncheck to view <button>food price</button> <button>kilograms</button> timeseries data point 1 food price - [12, 15,18] kilograms - [30,41,45] point 2 food price - [10, 11,19] kilograms - [13,14,24] point 3 food price - [24, 65,88] kilograms - [31,41,45] Your help will be much appreciated -
Django Error: ModuleNotFoundError: No module named 'allauth'
I've follow the documentation in "django-allauth" But I got these errors: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' -
I encountered this problem when running a django server
I encountered this problem when running a django server This ptoto shows the problem -
How to import Django models in a script started with Popen()
My question is very similar with this one. The difference in my case is that the python script I want to start is in another Django app. That means the script on which I want to access my models (listener1.py), is not independent from my project. This is my project structure: my_project ├── my_app1 #This app contains models,views etc. │ ├── models.py │ └── apps.py │ └── ... ├── logic_app #This app contains several unrelated python scripts │ └── ManagerScript.py │ └── listener1.py │ └── ... In my apps.py: class MyAppConfig(AppConfig): name = 'my_app1' def ready(self): #Once app is ready, start the following script as a thread thread = Thread(target=ManagerScript.main) thread.start() In ManagerScript.py: #This thread is responsible for starting listener1.py as a Subprocess #(because this is a thread I can successfully import my Models here) #from my_app1 import models #This would work! tmp = ['python3','path/to/listener1.py'] Popen(tmp, preexec_fn=os.setpgrp) In listener1.py: from my_app1 import models #Does not work! ... My question is, considering the fact that the subprocess listener1.py is in logic_app folder, how could I import my Models in listener1.py script without using Django Management Commands? (Because using them would require to change my current project structure) -
How to get only related objects in django serializer with manyToMany?
class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = "__all__" class EmployeeSerializer(serializers.ModelSerializer): bookings_st = BookingSerializer(many=True, read_only=True) class Meta: model = Employee fields = "__all__" class ProjectSerializer(serializers.ModelSerializer): employees = EmployeeSerializer(read_only=True, many=True) class Meta: model = Project fields = "__all__" class Employee(models.Model): name = models.CharField(max_length=127) lastname = models.CharField(max_length=127) class Project(models.Model): title = models.CharField(max_length=127) employees = models.ManyToManyField(Employee, related_name='employees') class Booking(models.Model): start = models.DateField() end = models.DateField() employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='bookings_st') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='bookings_st') I get nested object, but how to get in Emploee only related to both (project and employee) bookings? Now I just get all bookings that this employee has. I mean that structure: project_1: emploee_1: [bookings_that_belong_to_THIS_PROJECT] -
Django: If form doesn't have information set value to
If value in interval is not selected, i would like to use default one ( 1d ) the value of intervals is not check properly if is there -
Django AttributeError: 'str' object has no attribute 'tag' [closed]
I'm new to programming. I have errors that I don't understand. I have a problem with "include". Can u help me please enter image description here -
Password Resetting view displays the django framework template even after adding template name in my urls.py
url path('reset_password/', auth_views.PasswordResetView.as_view(template_name = "registration/reset_password.html"), name ='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name = "registration/password_reset_sent.html"), name ='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name = "registration/password_reset_form.html"), name ='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name = "registration/password_reset_done.html"), name ='password_reset_complete') it only works for this path('reset_password/', auth_views.PasswordResetView.as_view(template_name="registration/reset_password.html"), name='reset_password'), -
Docker-compose executes django twice
I am running in windows 10, and trying to set up a project via docker-compose and django. When I run docker-compose run app django-admin startproject app_settings . I get the following error CommandError: /app /manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. Or when I do this docker-compose run app python manage.py startapp core I get the following error CommandError: 'core' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. Seems like the command is maybe executed twice? Not sure why? Docker file FROM python:3.9-slim ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install RUN apt-get install -y \ libpq-dev \ gcc \ && apt-get clean COPY ./requirements.txt . RUN pip install -r requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app Docker-compose version: "3.9" compute: container_name: compute build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/app:/app ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db -
I want to display current rate depending on the category i select
here is my front-end and everything is working fine however, i don't want all rate to display at once, i want the rate to display one at a time depending on the card category i select. From the image i uploaded, current rate of other card category are showing which i don't want, please i need help even if it will require using javascript of ajax Here is my index(template) {% for giftcard in giftcards %} <!-- Card --> <div class="col-lg-4 gift__card col-6 p-0"> <a type="button" class="btn"> <img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}"> </a> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <select id="category" class="form-select py-2" aria-label="Default select example"> {% for spec in giftcard.category_set.all %} <option value="{{ spec.category }}">{{ spec.category }}</option> {% endfor %} </select> </div> <div class="form-group py-2"> <label for="Amount">Amount</label> <div class="d-flex align-items-center amount"> <input type="text" class="form-control" id="amount" placeholder="Please enter amount"> <span class="">#100,000</span> </div> </div> <div class="form-group py-3"> … -
KeyError: 'request' with django-notifications-hq and Django 3.2
I use django-notifications-hq and recently updated my project from Django version 2.2 to 3.2. Ever since, I get KeyError: 'response' whenever I try to access a template that uses the notifications_unread templatetag. Using django-debug-toolbar, I was able to notice that the template context no longer has the request key, that was present before the update. What am I missing here? The traceback: Template error: In template /var/www/my_project/src/my_project/mp_frontend/templates/front/notifications.html, error at line 10 request 1 : {% load user_profile_tags %} 2 : {% load notifications_tags %} 3 : {% load i18n %} 4 : {% load custom_notification_tags %} 5 : 6 : <li class="dropdown notification-list"> 7 : <a class="nav-link dropdown-toggle waves-effect" data-toggle="dropdown" href="#" role="button" 8 : aria-haspopup="false" aria-expanded="false"> 9 : <i class="far fa-bell"> 10 : {% notifications_unread as unread_count %} 11 : {% if unread_count %} 12 : <span class="badge badge-danger rounded-circle noti-icon-badge">{{ unread_count }}</span> 13 : {% endif %} 14 : </i> 15 : </a> My code: def list_products(request): profile = get_user_profile_from_request(request) context = {'user_tkn': profile.generate_new_token()} return render(request, 'label_catalog/products/index.html', context=context) And if I change it to: def list_products(request): profile = get_user_profile_from_request(request) context = {'request':request, 'user_tkn': profile.generate_new_token()} return render(request, 'label_catalog/products/index.html', context=context) everything works fine. I've searched through django-notifications-hq's issues and Django's release … -
How do I upload a file in Django OneToOne Model's FileField using form?
I have one model Detail which has OneToOne relation with default User Model. I have a field FileField in my Detail model, where I want to upload the files using forms from frontend/templates. I have been working around it a lot but I am not getting it done. I need help, please. My models.py is: from django.db import models from django.contrib.auth.models import User class Detail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) file = models.FileField(verbose_name="CSV File", upload_to='csv_files') file_desc = models.TextField("CSV File Description") def __str__(self): return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name)) My forms.py is: from django.forms import ModelForm from .models import Detail class DetailForm(ModelForm): class Meta: model = Detail fields = ['file', 'file_desc'] My views.py is: from django.views import View class UserAPI(View): template_name = 'accounts/user.html' def get(self, request): form = DetailForm(instance=request.user) context = {'form': form} return render(request, self.template_name, context) def post(self, request): form = DetailForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('user') context = {'form': form} return render(request, self.template_name, context) and my user.html (template) is: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> Every time I go to localhost:8000/user and fill the form and click on Submit Button, it gives me following error on frontend: No File Chosen and also the following … -
concatenate in django template
Why does in this snippet id="{{field_index}}" is empty, it doesn't print me "field_version_" or "field_controparte" depending of key? <form id="formDoc" style="margin-top: 10px;" action="/" method="post"> {% for keyFi,valueFi in tmplVar.jsonKeysDocFields.items %} {% with field_index="field_"|add:keyFi|stringformat:"s" %} <div style="margin-bottom: 5px; display: none;" id="{{field_index}}" class="docFieldWrapper" -
Trading ecommerce platform (Django)
I was looking to create a ecommerce trading platform where users are able to upload their products onto the site and then from there they are able to view other users products. Once they have found a suitable item they wish to trade they can send an offer to this user with one of their previously uploaded items. Is anybody able to tell me how I would go about this ? It would be greatly appreciated. I have tried numerous times however i just cant seem to wrap my head around how i should implement it. -
django formsets - render fields from a model and save inputs to another model
good morning to all! I am Marcos, 2-yr developer, half with Django. I have a doubt about using formset with class-based views, that may be simpler, but i couldn't figured out so far. I have the following models: class ProjectModel(models.Model): charcode = models.Charfield(unique=True) class QuestionModel(models.Model): title = models.Charfield() type = models.CharField(choices=('text','rate')) class SurveyModel(models.Model): project = models.ForeignKey(ProjectModel) active = models.BooleanField(default=False) questions = models.ManyToManyField(QuestionModel) class AnswerModel(models.Model): question = models.ForeignKey(QuestionModel) response_text = models.TextField() response_rate = models.IntegerField(choices=(1,2,3,4,5)) class SubmissionModel(models.Model): user = models.ForeignKey(get_user_model()) survey = models.ForeignKey(SurveyModel) answers = models.ManyToManyField(AnswerModel) I need a view to render questions of a active survey so a user can fill it in a form that will create answers objects and a submission object. so, I have this url: path('submission/<str:charcode>/, SubmissionView.as_view()) this view that receives charcode from url: class SubmissionView(CreateView): form_class = SubmissionFormSet template_name='create_submission.html' and this formset (in construction): class SubmissionFormSet(form.BaseFormSet): # need to get questions from survey_objects.get(project__charcode = 'charcode', active=True) # define each field based on question type to properly widget choice # save answers and submission based on responses from user i really have no idea yet, but i guess i must use formset_factory, maybe inside view like AnswerFormset = formset_factory(AnswerForm, formset=SubmissionFormSet) but not sure how to -
How to use double loop's variable like a variable in Django template?
Django-unicorn returns 2 variables from the database for the table to the html-template: thead header (array) and the body tbody (collection of objects). I need to dynamically draw the body of the table in the template through a double loop like: {% for row in tbody %} <tr class="header"> {% for name_column in thead %} <td>{{ row.column_name }}</td> {% endfor %} </tr> {% endfor %} But this decision is incorrect, because it is not the use of a loop's variable column_name, but an appeal directly to the field column_name. The question: how to do it correctly? -
Django Admin Filter and Search Fields Not Working
I added a file upload field to my django admin class that creates new objects of another type. After adding the form for this, my filter_horizontal and search_fields stopped working. I also can't add more than one author to a book. Here's the code for admin.py. @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('title',) ordering = ('title',) fields = ('title', 'title_en', 'title_ru', 'authors', 'description', 'description_en', 'description_ru', 'image', 'narrators', 'age_range', 'genres', 'top_book', 'audio_files') search_fields = ('title', 'title_en', 'title_ru') filter_horizontal = ('authors', 'narrators') def get_form(self, request, obj=None, **kwargs): try: instance = kwargs['instance'] return BookForm(instance=instance) except KeyError: return BookForm def add_view(self, request, form_url="", extra_context=None): extra_context = extra_context or {} extra_context['form'] = self.get_form(request) return super(BookAdmin, self).add_view(request, form_url=form_url, extra_context=extra_context) def change_view(self, request, object_id, form_url="", extra_context=None): extra_context = extra_context or {} book = Book.objects.get(id=object_id) extra_context["form"] = self.get_form(instance=book, request=request) return super(BookAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context) def save_model(self, request, obj, form, change): obj.save() audio_files = request.FILES.getlist('audio_files') chapter_count = obj.chapter_set.count() for count, audio_file in enumerate(audio_files): Chapter.objects.create(book=obj, audio_file=audio_file, title=f'Մաս {chapter_count + 1 + count}') return super().save_model(request, obj, form, change) Here's the code for the form. class BookForm(forms.ModelForm): audio_files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Book fields = ('title', 'title_en', 'title_ru', 'authors', 'description', 'description_en', 'description_ru', 'image', 'narrators', 'age_range', 'genres', 'top_book') I want … -
Django Form take the option value of a select in the html template
I have this formset which takes data from each form and selects it within the select. How do I get that value? I used value but it only shows me the id and not the option value views tot_gruppi = Gruppo.objects.all() GruppiFormSet = formset_factory(GruppiForm, extra = 0) gruppi_formset = GruppiFormSet(initial=[{'dati_gruppo': x} for x in range(1, tot_gruppi.count()+1)]) html <div class="mb-3"> <p> {{ form.dati_gruppo.value }} </p> {{ form.dati_gruppo }} </div> -
the css in my django project is not working
Please help me out. I don't get any errors in my css file or in finding it, but still the style i would like is not shown. my css file body { background-color: lightblue; } h1 { color: navy; margin-left: 20px; } h2 { color: deeppink !important; } my html page {% extends 'base.html' %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static '../static/css/style.css' %}"> {% block content%} <h1>All synonymes will be shown here</h1> <form method=POST action="{% url 'add-vocabulair' %}"> {% csrf_token %} <input type="search" placeholder="valt onder" aria-label="Search" name="onder" value={{key}}><br/> <input type="search" placeholder="woord" aria-label="Search" name="woord"><br/> <button class="btn btn-outline-secondary" type="submit">Submit</button> </form> {{woord}} <br/> {{onder}} {% endblock %}} what can i do to make the style appear?