Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert a member into a group in Django with a GraphQL Mutation?
I have a basic group in my django-admin-panel and I want to define a mutation, where I can add a member (user) to a group with a graphQL mutation. -
Two model in one UpdateView "Django"
my views : from .models import Settings, SocialMediaSetting class UpdateSocialMediaSetting(LoginRequiredMixin, UpdateView): model = SocialMediaSetting fields = '__all__' template_name = "staff/settings/social-media-settings-update.html" class UpdateSettings(LoginRequiredMixin, UpdateView): model = Settings fields = '__all__' template_name = "staff/settings/settings-update.html" two different class in models without any relation, I want show both in one html and one form both models has just one object -
How to put conditions in filter for ALL or Something in Django
I am getting a some_id from request. If the some_id is -1 I have to select ALL or select the particular some_id. So I want something like this - model.objects.filter(some_id = '*' if some_id_val = -1 else some_id_val) I know I can chain with if like - if some_id_val != -1: model.objects.filter(some_id = some_id_val) . . . But I want a one liner solution. -
Reverse for 'viewed-notification' with arguments '('',)' not found. 1 pattern(s) tried: ['users/notification/(?P<pk>[^/]+)/read$']
What I am doing wrong here? I think the problem in url in html . views.py def notification_read(request, notification_id): notification = get_object_or_404(Notification, pk=notification_id, viewed_at=None, user=request.user) notification.viewed_at = timezone.now() notification.save(update_fields=['viewed_at']) if request.method == 'POST': form = NotificationForm(request.POST, instance=notification) if form.is_valid(): form.save() return redirect('users:notification') else: form = NotificationForm(instance=notification) return render(request, 'auth/notifications.html', {'form': form}) urls.py path('notification/<pk>/read', views.notification_read, name='viewed-notification'), template: <tr> <td> {{ item.message }} <td> <td> {{ item.created_at }} <td> <form method="post" action="{% url 'users:viewed-notification' object.id %}" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <span class="badge badge-error"> {{ form.viewed_at }} <p><input type="submit" value="See it"/></p> </form> </span> </td> </tr> What is the problem here? Where place where I did mistake? On my opinion it is not correct wtitten url?What do you think guys?Can anybody help? -
Django-filter: add atributes to multiple input filter.fields in a search form
How to add placeholders and remove titles to multiple inputs which are rendered into a single form using django-filters module filter.py class AdsFilter(django_filters.FilterSet): class Meta: model =Advert fields={ 'title':['icontains'], 'category': ['exact'], 'location': ['exact'], } index.html <form method="GET" action="{% url 'home' %}" id="form_id"> <div class="col-md-8"> <div id="glass"> <div class="wrapper"> {{ filtered_qs_form}} {{ location.form}} <button3 id="button3"type="submit" class="btn btn-primary">Search</button3> </div> </div> </div> </form> -
PDF from html in django (full support css and static files)?
What's the best way to generate pdf file from html template with full support of css and static files. I would like to pdf looks the same like in (ctrl + p method --> save as pdf). I was trying use xhtml2pdf but unfortunately isn't full css support and static. -
docker-compose run: django and postgres "strange" behavior
When I run the following command: docker-compose run django python manage.py startapp hello OR docker-compose run django python manage.py createsuperuser Instead of starting a new container, it opens a Postgres shell. However, when I'm using exec, like so: docker-compose exec django python manage.py createsuperuser Then it works as expected. Here is my docker-compose.yml file: version: '3.7' services: postgres: image: 'postgres:9.6.9-alpine' volumes: - postgres_data:/var/lib/postgresql/data env_file: - ./.env.dev django: image: django_dev build: context: . dockerfile: ./app/docker/django/Dockerfile volumes: - ./app/:/usr/src/app/ command: /usr/src/app/docker/django/start_dev ports: - 8000:8000 env_file: - ./.env.dev depends_on: - postgres node: image: node_dev build: context: . dockerfile: ./app/docker/node/Dockerfile depends_on: - django volumes: - ./app/:/usr/src/app/ - /usr/src/app/node_modules command: npm run dev ports: - '3000:3000' - "3001:3001" volumes: postgres_data: Dockerfile: FROM python:3.9.5-slim-buster WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt update \ && apt install -y curl \ && curl -sL https://deb.nodesource.com/setup_lts.x | bash - \ && apt-get -y install libpq-dev gcc \ && pip install psycopg2 \ && pip install psycopg2-binary RUN pip install --upgrade pip \ && pip install pipenv COPY ./app/Pipfile /usr/src/app/Pipfile RUN pipenv install --skip-lock --system --dev RUN apt-get update && apt-get install -y libglu1 COPY ./app/docker/django/entrypoint /usr/src/app/docker/django/entrypoint COPY ./app/docker/django/start_dev /usr/src/app/docker/django/start_dev RUN sed -i 's/\r$//g' /usr/src/app/docker/django/start_dev RUN chmod … -
Django - Store form data with changing fields
I am trying to make a platform to handle various custom forms whose fields are are not known beforehand (similar to google forms). How can I manage the data entries from the form to my backend/ database. (django -> sql postgress)? I thought of using the standard Django models, but they need the fields to be pre-specified in code. -
Heroku Redis Error while reading from socket: (104, 'Connection reset by peer')
I'm running a Heroku Redis instance that always worked fine, but after the upgrade when I try to run celery workers I get the following error [2021-07-23 11:06:08,135: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-54-***-***-*.eu-west-1.compute.amazonaws.com:*****//: Error while reading from socket: (104, 'Connection reset by peer'). Trying again in 12.00 seconds... (6/100) Everything seems to be up to date and I can't seem to figure out how to run it again. I tried to drop the redis instance and create it from scratch but nothing. -
Check constraint on django
I have two models class Order(models.Model): ord_number:str ord_date: date ord_ref: str Null=True ord_qty: Decimal ord_desc: str timestamp: datetime created: datetime Class OrderLines(models.Model): order: FK(Order) driver: FK(Driver) truck: FK(Truck) ord_qty: Decimal loaded_quantity: Decimal loading_date: date My schemas on posting will be like this OrderCreateBase = create_schema(Order, exclude=("id", "timestmap", "created")) OrderLineCreateBase = create_schema(OrderLines, exclude=("id)) class OrderCreateSchema(OrderCreateBase): order_lines = List[OrderLineCreateBase] Json data to be used on creating like this "ord_number: "AB123", "order_date: Date(01/01/2021), "ord_ref" Null, "ord_qty": Decimal("10_000"), "ord_desc" "Sample Order", "order_lines"[ {"order_id": 1, "driver_id: 23, "truck_id": 12, "ord_qty": Decimal("10_000"), "loaded_quantity": Decimal("8_000") <----#, "loading_date": Date(01/01/2021)}, {"order_id": 1, "driver_id: 13, "truck_id": 17, "ord_qty": Decimal("10_000"), "loaded_quantity": Decimal("9_000") <----#, "loading_date": Date(01/01/2021)}] } I want check constraint that will ensure total loaded quantity(loaded_quantity) per order will be <= to ordered_quantity (ord_qty) currently my create endpoint is like this @router.post( "/ilr/{ilr_id}/instrunctions", response={HTTPStatus.CREATED: Message, HTTPStatus.BAD_REQUEST: Message}, tags=["ilrs instructions"], summary=_("create loading request instructions"), description=_("API to create ilr instructions lines"), url_name="create_ilr_instructions", ) @transaction.atomic() def create_ilr_instrunctions(request, ilr_id: int, payload: ILRLineCreateSchema): data = payload.dict() ilr = get_object_or_404(ILR, id=ilr_id, status=0) data["request"] = ilr data["order_date"] = ilr.ilr_date # get existing lines total volume total_volume = ILRLine.objects.filter(request=ilr).aggregate(total_volume=Sum("quantity")) if ilr.quantity < total_volume.get("total_volume") + data.get("quantity"): <-----# return HTTPStatus.BAD_REQUEST, { "detail": [{"msg": f"Total loading quantities will be higher than ordered … -
How to assign string value instead of id in a foreign key column in Django view?
I'm working on a Django project where I have to assign a string into a foreign key column. But i'm getting error like this Field 'id' expected a number but got 'Rituparna Das' for this line js.update(Developers=rule[1]) Here's my model.py class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True, primary_key=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developers = models.ForeignKey(developer, on_delete=models.CASCADE,blank=True, null=True) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) Epic = models.CharField(max_length=500, blank=True) class assignmentRule(models.Model): id = models.AutoField(primary_key=True) assignmentRuleName = models.CharField(max_length=300) assignmentObject = models.CharField(max_length=300) assignmentValue = models.CharField(max_length=300) def __str__(self): return self.assignmentRuleName class assignmentRuleItem(models.Model): Jira_Column = models.CharField(max_length=100, blank=True) RelationalOperators= models.CharField(max_length=100) Jira_Value = models.CharField(max_length=500) # LogicalOperator = models.CharField(max_length=30, blank=True) Rule_No = models.ForeignKey(assignmentRule, on_delete=models.CASCADE, blank=True, null=True) And that is my view.py def rule_assignment_developer(request): rules = list(assignmentRule.objects.values_list('id','assignmentValue','assignmentRuleName','assignmentObject').filter(assignmentObject = 'Developer')) for rule in rules: # print(rule[1]) assignmentRuleItems = list(assignmentRuleItem.objects.values_list('Jira_Column', 'RelationalOperators', 'Jira_Value').filter(Rule_No = rule[0])) AR = len(assignmentRuleItems) print(AR) myString = '' for i in range(AR): kwargs = {} if myString == "": myString = myString + assignmentRuleItems[i][0] + assignmentRuleItems[i][1]+assignmentRuleItems[i][2] else: myString = myString+","+assignmentRuleItems[i][0]+assignmentRuleItems[i][1]+assignmentRuleItems[i][2] for e in myString.split(','): k, v … -
Please tell me which code needs to be modified
I want to edit the main page of ctfd, but I don't know which part to edit no matter how much I search.I can't use the django web server, so please tell me what part I need to edit to edit the main page text.enter image description here The material I want to fix and edit is at the link below. https://github.com/CTFd/CTFd -
nginx stops working if no requests on server_name
I set up django app with gunicorn and nginx with my laptop dedicated to be a server (works on Xubuntu). All works fine on this laptop, but trouble starts on another devices. I use real ip from my ISP, which is 195.214.223.143 so it's easy to reach site from server laptop and sometimes it's easy to reach the site by this ip from another devices. The thing is that I can't access my site if there are no activity from server laptop. So to run site (http://195.214.223.143:5001) I need to refresh the page of it on my server laptop or just to ping the port from my server laptop (like telnet 195.214.223.143 5001). After this I can reach the site from another device. But if there is no requests from my server laptop, after 1-2 minutes I lose access to site (ERR_CONNECTION_REFUSED). I've already thought about making script which will ping to port every minute, but that looks dumb of course. Below are my gunicorn and nginx configs. /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=holyskills Group=www-data WorkingDirectory=/home/holyskills/Desktop/SimpleBill/ivan-education/main_projec> ExecStart=/home/holyskills/Desktop/SimpleBill/ivan-education/main_project/main_> --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ main_server.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/main_server … -
Django-autocomplete-light filtering and displaying results based on two fields filtering the results based on two fields
I am facing some problem about using Django-autocomplete-light with one filter that able to filtering two different feild.It take about 2 weeek still cannot fix. model.py class Material(models.Model): model_name = "Material" material_code = models.CharField(max_length=50, null=False, blank=False, unique=True) name = models.CharField(max_length=100, null=False, blank=False, unique=True) def __str__(self): return "{} {}".format(self.material_code, self.name) form.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'material': autocomplete.ModelSelect2(url='autocomplete_material'), 'material': autocomplete.ModelSelect2(url='autocomplete_material_name'), } url.py path('autocomplete/material/', autocomplete.Select2QuerySetView.as_view(model=models.Material, **model_field_name="material_code"**), name="autocomplete_material"), path('autocomplete/material_name/', autocomplete.Select2QuerySetView.as_view(model=models.Material, **model_field_name="material_code"**), name="autocomplete_material_name"), For the filter that i want to able filter with two field name,which is material_code and name , that you can be showing in the model.py,right now if i put two autocomplete just can be run the bottom one cannot be filter two field name, that may be got solution that can be combie two model_field_name into one ? Thank !! -
how to create django template tag for custom model
I'm new for django template tag. I am trying to display logged user payment_status and remaining_days on django html template. For this I wrote model and I don't know how to write template tag for this. Request your help on this. models.py class User_subscription(models.Model): user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True) subscription_id = models.ForeignKey(Subscription, on_delete=models.CASCADE) subscripted_date = models.DateTimeField() expired_date = models.DateTimeField() payment_status = models.CharField(max_length=50) payment_details = jsonfield.JSONField() I want to display payment_status above in model and remaining_days = expired_date-subscripted_date -
access one to one related relations inside django template
Applied candidate skill sets class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) Candidate job profile class SeekerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) current_salary = models.IntegerField() # when users appies for a job class JobPostActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE) apply_date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=25, default='onhold') def __str__(self): return self.user.username+''+self.job_post.title class Job_Skillset(models.Model): job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE) skill = models.ForeignKey( Skillset, on_delete=models.CASCADE) skill_level = models.CharField(max_length=20) my view def manage_applic(request): if request.method == 'GET': # getting onhold candidates applied_candi = JobPostActivity.objects.filter( job_post__creater=request.user).exclude(Q(status__iexact='rejected') | Q(status__iexact='selected')) context = { 'applicants': applied_candi, } return render(request, 'jobmanagment/applicants_manage.html', context) Here is what I am trying, I want to get the skills of applied candidates which I am looping through, i having trouble getting those, there is one to one relation of user and seeker profile but how do we access that inside django template my view {% for val in applicants %} <tr> <td>({{val.user.id}}){{val.user.username | capfirst }}</td> <td>{{val.apply_date}}</td> <td> <select class="status_select" name="{{val.job_post.title}}" id="{{val.user.id}}" > <option selected="{{val.status}}" style="font-weight: bolder"> {{val.status}} </option> <option value="onhold">Onhold</option> <option value="selected">Selected</option> <option value="rejected">Rejected</option> </select> </td> <td> <b>{{val.job_post.job_type}}</b> </td> <td>{{val.job_post.title}}</td> <td> {% for cand_skills in val.user.seeker_profile.seeker_skill_set_set.all %} <<-- here is my issue … -
Django allauth:email comfirmation link can be accessed even after confirmation?
I'm using django-allauth to manage signin and signup in my Django app. When a user sign up, an email contains a confirmation link sent to the registered email. In allauth settings, I set ACCOUNT_CONFIRM_EMAIL_ON_GET=False so a user have to click a button to confirm the email address. But the link is still accessible even after user clicked the button. (by click the link in the email or press go back) Can I redirect the user to a specific url (e.g. home) if the user go to the confirmation link after confirmation? -
Sending bulk email from User email account
I have a web-app in Django, an user should be able to send marketing emails to a selected list of recipients but the emails should be sent from the user's personal email. This of course requires communication between my web-app and the user's email provider (for auth and managing emails). Leaving opinions aside, could anyone point to me libraries or tools used to achieve this functionality? Thanks -
Find all occurences of maximum value from a list of tuple?
I have a list of tuple such as: list1=[(1,1),(2,1),(3,1),(4,0),(5,0)] I have found the maximun element using: max_value = max(list1, key=itemgetter(1)) this outputs (1, 1) I want some thing like [(1,1),(2,1),(3,1)] -
Django python sehll from app.models import Modelclass not working
redcube/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) level = models.IntegerField(blank=True) def __str__(self): return self.user.username class Images(models.Model): redcube = models.ForeignKey(Redcube, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.redcube.name from the python shell >>> from redcube.models import Profile Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name 'Profile' from 'redcube.models' (/Users/macos/basic/btp/btp/redcube/models.py) >>> from redcube.models import Images >>> Images.objects.all() <QuerySet [<Images: Hawaii>, <Images: City view hotel>, <Images: Cottage>, <Images: Redcube>, <Images: Phone>, <Images: Flower>, <Images: Miho>]> When I try to import and test the models in the python shell Other model class is working right. but the Profile class is not working! I've tried the from .models import Profile, but not working. Thanks for the help :) -
TypeError at /book/2 string indices must be integers
I'm new to Django, I have encountered this error TypeError at /book/1 string indices must be integers I have a JSON file called book.json (seen below) { "books":[ { "id": 1, "title": "Unlocking Android", "isbn": "1933988673", "status": "PUBLISH", }, ..... I'm trying to get single book using id in the view def show(request, id): with open('bookstore/books.json') as file: books = json.load(file) book = [book for book in books if book['id'] == id] return render(request, 'books/show.html', book) The show.html template has this code <a href="/book/{{book.id}}"> for book links -
Finding the middleware that interrupted a Django request
I was debugging yesterday a Django view that returned a 403 without entering the view code. It turns out it was because I provided a Content-Type: multipart/form-data header without specifying the delimiter. This was "silently" rejected by some Django request parsing logic or middleware, which returned a 403. This makes sense, but the debugging experience wasn't great. Is there a way to make these middlewares (request parsing, auth, CSRF...) print some logs when they interrupt a request? -
Multiple Serializer within the same view.list call
I have a simple model that can contain some sensitive information class Organization(Model): name = CharField() is_private = BooleanField() # the following information is sensitive code = CharField() employee_count = IntegerField() # other confidential fields... I am using regular ModelViewSet and ModelSerializer for this model. when calling the list action of the viewset (GET organizations/) I would like to have my organizations serialized differently depending on whether they are private: show all the fields if the organization is not private only name if it is What I already tried: overriding get_serializer() of viewset => this doesn't fit as the same serializer applies for all objects of the list using serializers.MethodField() => not efficient because I have many fields that I'd need to handle -
I want to make location based app in django
Basically when user will put location name then a map showing that location should get displayed and I want to make it by google api like geocoding So can anyone help me? -
post django form data via iframe
I have a django form that I want to display on another website via iframe. The form displays ok but whenever I try to submit the form that is displayed in the iframe, I get a "server refused to connect" error message. Is it possible to make a django form work with iframe or is there a better way to do it? The views code for the form: from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def booking_create_view(request): form=BookingForm submitted = False if request.method=='POST': form = BookingForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/?submitted=True') else: form = BookingForm if 'submitted' in request.GET: submitted = True return render(request, "booking_form.html",{'form':form, 'submitted': submitted}) HTML for the form: <form class="" action="" method= POST> <div class="form-group"> {% csrf_token %} {{ form.as_p }} <input type="Submit" value="Submit" class = "btn btn-secondary"> </form> {% endif %} The iframe: <h1>The iframe element</h1> <iframe src="http://127.0.0.1:8000/" title="test"> </iframe> Note: I have also tried using a live server (pythonanywhere) that had the same result