Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ListView and get_queryset with two models
I have 2 models in which I need to do a search: class Movies(models.Model): title = models.CharField(max_length=100) class Meta: db_table = "movies" def __str__(self): return self.title class Actors(models.Model): name = models.CharField(max_length=100) movies = models.ManyToManyField(Movies, related_name="actors") class Meta: db_table = "actors" def __str__(self): return self.name I have a search form and need to search in Movies title and Actors name. I know how to make view for search in one model: class SearchView(ListView): template_name = "search_results.html" model = Actors def get_queryset(self): query = self.request.GET.get('q') object_list = Actors.objects.filter(name__icontains=query) return object_list But how to make when I want to search in two models? The result should then list the occurrences in actor names and occurrences in movie titles separately in the template. How to update my View easily? I tried to add a method get_context_data to extend the context, but unfortunately I don't know how to access the second model in get_query-set. I use default db.sqlite3. Thank you very much! -
Django ORM select distinct list of models where a foreign key exists
In my Django project I have two models that connect to each other by way of a foreign key relationship: Invite (has one Event) to Event (has many invites) I am able to select a list of relevant Invites that I care about as follows: invites = Invite.objects.filter(guest = guest) I could access each event per invite but this likely results in duplicates. From the above, I would like to get a unique list of events. What is the best way to achieve this? -
Django in Colab - can't access admin login page
I am trying to start a new project on djago in google colab. I have created new project and also pasted- "ALLOWED_HOSTS = ['colab.research.google.com','*']" to settings.py. And using this- "from google.colab.output import eval_js" "print(eval_js("google.colab.kernel.proxyPort(8000)"))" to get the external link to access that port. And managed to run the server by running this- "!python manage.py runserver 8000" But I can only land on the "The install worked successfully! Congratulations!" page. And Created a super user using this- "!python manage.py createsuperuser" But I can't access the admin page and other pages. Please Help me.Thank You -
How to implement a request envelope in Django Rest Framework?
I'm trying to implement a request envelope in DRF. The format should be (for now): { "data": {} | [] } I could implement this via a custom parser, but then this would not be reflected in the generated OpenAPI Spec or the Browsable API. I tried building something like a "wrapper serializer": class RequestEnvelopeSerializer(serializers.Serializer): data = MyStuffSerializer(source="*") But that works only for single entities because in a list, every entity now is serialized like [ { "data": ... }, { "data": ... } ] I want a list of entities to be serialized as { "data": [ { ... }, { ... } ] } What is the best way to achieve that in Django? Thanks in advance. -
How to add a Django form field dynamically depending on if the previous field was filled?
I have a Form (Formset) for users to update their profiles. This is a standard User model form, and custom Participants model form. Now, in cases when a participant provide his phone number, I need to refresh the whole Form with a new 'Code' filed dynamically. And the participant will type the code he received my SMS. Here is how I am trying to do it: def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): form.save() seller_form = SellerForm(self.request.POST, instance=self.object.seller) if seller_form.is_valid(): seller = self.request.user.seller seller.inn = seller_form.cleaned_data.get('inn') if seller_form.cleaned_data.get('phone_number'): seller_form.fields['code'] = models.CharField(max_length=4) return render(request, self.template_name, {'form': form, 'seller_form': seller_form}) seller.save() return HttpResponse('Seller updated') return render(request, self.template_name, {'form': form, 'seller_form': seller_form}) Well I am not sure if this is the way I can add additional field. What would you suggest to handle this situation? -
How do I iterate ManyToMany field in Django template tag?
So I have an object that contains a Many-to-Many field. I'm trying to iterate this field in Django template, but apparently I can't. Let me show you the code first. model class Book(models.Model): title = models.CharField(max_length = 100, blank=True) category = models.ManyToManyField(Category) def __str__(self): return self.title views.py def book_list(request): books = Book.objects.all().order_by('-pk') context = { 'books' : books, } return render(request, 'contents/book_list.html', context) Now template. {% for b in books %} <div> {{c.title}} {% for cat in b.category %} {{cat}} {% endfor %} </div> {% endfor %} Now I get 'ManyRelatedManager' object is not iterable error. How do I iterate the field and show all the category in each object? Thanks. -
Django Celery Beat not sending tasks to Celery Worker
I am using Celery in Django in order to run tasks in specific time intervals. When I first start the Docker, all the tasks run without any issue. If I stop the docker (i.e. docker-compose down) and then restart the docker (i.e. docker-compose up), celery-beat does not send the tasks to the celery worker in order for them to get executed. If I visit the Admin panel and disable the tasks and then re-enable them it starts working! Also if I do not use the django_celery_beat.schedulers:DatabaseScheduler and allow celery beat to use the default scheduler it also works. Even though this method works, is not the best scenario since the tasks are not longer editable in Django admin panel Is there a solution to this issue? Postgresql is not part of the docker-compose. I have a native PostgreSQL 10.5 installation. settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS":{"max_connections":50, "retry_on_timeout": True} } } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" CELERY_TIMEZONE = "Europe/Amsterdam" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_BROKER_URL="redis://redis:6379" CELERY_CACHE_BACKEND = 'default' CELERY_BEAT_SCHEDULE = { "sendemails_task":{ "task":"demoapp.tasks.testing", "schedule":crontab(minute='*/2') }, } docker-compose.yml services: redis: image: redis restart: unless-stopped expose: - 6379 web: … -
making an API that adds instances to ManyToMany fields of a model in django rest framework
I am making a movie watching website in which there are users and films and the user model has a ManyToMany Field that references the film model. it's called WatchList and an authenticated user can add any movie they want to this watchlist. My problem is that I want an API that only gets the ID of a film and adds it to the user's watch list. these are my models and serializers and I am trying to make a view to implement this API. # models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) # ... class User(AbstractBaseUser, PermissionsMixin): userID = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True, validators=[RegexValidator(regex="^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$")]) email= models.EmailField(max_length=100, unique=True, validators=[EmailValidator()]) name = models.CharField(max_length=100) watchList = models.ManyToManyField(Film) objects = UserManager() USERNAME_FIELD = 'username' # serializers.py class WatchListSerializer(serializers.ModelSerializer): class FilmSerializer(serializers.ModelSerializer): model = Film fields = ('filmID', 'title',) read_only_fields = ('filmID', 'title') film_set = FilmSerializer(read_only=True, many=True) class Meta: model = get_user_model() fields = ('userID', 'film_set') read_only_fields = ('userID',) # views.py class WatchListAddView(...): pass The serializer can be changed. but this kind of shows what I want the api to be. the authentication validation part is already taken care of, so imagine that any request to the view is from an authenticated … -
Saving pandas dataframe to django model with logic to avoid storing duplicate entries for a field in database
How can we add some logic to avoid duplicate entries for the incoming data. For example I am able to save the excel file in my database using to_sql. I have to validate that no two duplicate entries can be created for a column in this case I have title column and validate if two products have same title or name, the entry does not get added to the database. import pandas as pd from django.core.management.base import BaseCommand from store.models import Product from sqlalchemy import create_engine from django.conf import settings class Command(BaseCommand): help = "A command to add data from an Excel file to the database" def handle(self, *args, **options): excel_file = 'Product_data.xlsx' df = pd.read_excel(excel_file) #connection to mysql user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'mysql://{user}:{password}@localhost:3306/{database_name}'.format(user=user,password=password,database_name=database_name) engine = create_engine(database_url, echo=False) df.to_sql(Product._meta.db_table, if_exists='append', con=engine, index=False) So I have to add the validation logic before the data is inserted into the database such that in my case, we cannot store duplicate products that have same title or product_name. -
Django query list order changes in local and production
main_filter = Consumer.objects.none() filtering = Consumer.objects.filter(created_date=date).values().order_by('-created_date')[:1] main_filter |= filtering I just run these in a while loop by stepping down date to fetch latest record of each date. The problem is the order of main_filter item in local system is just reverse of the order of main_filter item in production. For Example In local main_filter = [{'Consumer': 'A'}, {'Consumer': 'B'}] In production main_filter = [{'Consumer': 'B'}, {'Consumer': 'A'}] What is the cause of this order change?(Note: There is no change in code in local and production) -
Why does my default django admin page look terrible when deployed to heroku?
I finally deployed my django project to heroku but for some reason the styling of the admin page looks really ugly. I have no idea why that is. -
Filtering by multiple values inside attribute
I have an object Post that contains a set of Comments composed by a string field Text and a boolean field Deleted. I am using ElasticSearch for getting all this Posts having a comment containing a specific string. But I want to exclude these comments with Deleted = True. I am trying with a bool filter over Posts like this: { "bool": { "must": [ { "match": { "comments.text": "the string to match", } }, { "match": { "comments.deleted": False, } }, ], }, } Nonetheless, as soon as a comment is deleted (set Deleted=True), the whole Post with such a comment gets excluded. I guess this is happening because the filter does not know that what I want is to match by these comments that matches the string AND are not deleted. So my question is: Is there a way to filter the comments over witch I want to apply the match? Thank you a lot by advance! pd: I am working with Django to manage my domain, so actually Post.comments is a queryset that gives to me all comments of this post. -
countdow data in ios returns nan
I have problems with set data on ios. On android and other devices it works perfectly while on ios it gives me nan ... how can I fix it? views django data = settaggio.data.strftime("%m %d, %Y %H:%M:%S") my script <script> var countDownDate = new Date("{{data}}").getTime(); // var istante = Date.now(); // console.log(istante); var x = setInterval(function() { var now = new Date().getTime(); //differenza var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("giorni").innerHTML = days; document.getElementById("ore").innerHTML = hours; document.getElementById("min").innerHTML = minutes; document.getElementById("sec").innerHTML = seconds; if (distance < 0) { clearInterval(x); document.getElementById("giorni").innerHTML = 0; document.getElementById("ore").innerHTML = 0; document.getElementById("min").innerHTML = 0; document.getElementById("sec").innerHTML = 0; setInterval(function() { location.reload(); },500); } },1000); </script> -
django mptt tag recursetree => is there any counter like forloop.counter or we have to declare a counter variable
We have forloop.counter for iteration in django template this is a built-in template operation. Using this loop counter we can display the number and also utilize for various decisions of color or odd/even etc., UI work. similarly, I am utilizing the recursetree of the django mptt tags, wondering any counter variable available. or do we need to create a counter variable and increment for the display of the sequence. -
Django not calling function from urls.py
I am trying to call a function using urls.py path('Show_Message', Show_Message, name='Show_Message') is within my urls.py, no typos. This is my webhook.py from django.http import HttpResponse def Show_Message(request): print('HERERERERE') if request.method == 'POST': print(request.body) return HttpResponse(status=200) I have configured the webhook correctly too :) Wondering what is going on here, I am getting this response too: [31/Jan/2022 20:54:32] "POST / HTTP/1.1" 200 924 -
Getting an error when trying to delete team Django
When I try to add delete to my views I receive an error: Team matching query does not exist. What am I doing wrong in here? It seems like traceback leads me to context_processor.py. This is my code below: Views.py @login_required def team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) invitations = team.invitations.filter(status=Invitation.INVITED) return render(request, 'team/team.html', {'team': team, 'invitations': invitations}) @login_required def activate_team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) userprofile = request.user.profile userprofile.active_team_id = team.id userprofile.save() messages.info(request, 'The team was activated') return redirect('team:team', team_id=team.id) @login_required def add(request): profile = request.user.profile form = TeamForm() if request.method == 'POST': form = TeamForm(request.POST, request.FILES) if form.is_valid(): team = form.save(commit=False) team.created_by = request.user team.save() team.members.add(request.user) profile.active_team_id = team.id profile.save() return redirect('account') context = {'form': form} return render(request, 'team/add.html', context) @login_required def edit(request): #profile = request.user.profile team = get_object_or_404(Team, pk=request.user.profile.active_team_id, status=Team.ACTIVE, members__in=[request.user]) form = TeamForm(instance=team) if request.method == 'POST': form = TeamForm(request.POST, request.FILES, instance=team) if form.is_valid(): team.save() messages.info(request, 'The changes was saved') return redirect('team:team', team_id=team.id) context = {'form': form, 'team': team} return render(request, 'team/edit.html', context) @login_required def delete(request, pk): team = Team.objects.get(pk=request.user.profile.active_team_id) if request.method == 'POST': team.delete() return redirect('account') context = {'object': team} return render(request, 'team/delete.html', context) urls.py urlpatterns = [ path('add/', add, name='add'), … -
Django add Attributes to Boolean model form
My Model Form looks like this: class ToggleSettingsForm(forms.ModelForm): class Meta: model = ToggleSettings fields = ( 'background', ) widgets = { 'background': forms.BooleanField(widget=forms.CheckboxInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'your_id'})) } And I get this error in the template AttributeErro 'BooleanField' object has no attribute 'is_hidden' Request Method: GET Request URL: http://localhost:8000/auth/dashboard/ Django Version: 4.0.1 Exception Type: AttributeError But I need a Boolean Field (checkbox) with an ID, as well as classes. How else would I give a Boolean Field of a Model Form ID's and classes? To add Attributes to a BooleanField I tried it with this post: How to assign id attribute to BooleanField in ModelForm for jsonresponse -
How to prevent sentry from logging errors while on Django local server?
I am trying to prevent Sentry from logging errors to my Sentry dashboard while I'm working on my local server (i.e http://127.0.0.1:8000/). The only time I want sentry to log errors to my dashboard is when my code is in production. How can I go about this? I have tried this below, but it doesn't work: if DEBUG == True sentry_sdk.init( dsn=os.environ.get('SENTRY_DSN', None), integrations=[DjangoIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True ) -
social-auth-app-django: how to disconnect a user without password
On my site (www.raptors.ru) I'm using social-auth-app-django to authorize users from Facebook. To make their logging in easier I made following setting: ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = True so that users do not need to enter their password. When the FB user logs in the first time, a record is created in the table users. What is important, this user has no password on my site. However, this user is fully functional: he is able to publish posts, make comments, etc. The problems begin if the user wants to disconnect from his social account. First, if one tries to disconnect his account via the LoginCancelledView (direct link is https://raptors.ru/accounts/social/login/cancelled/, he gets a message that he successfully disconnected, but it's not truth since his username is still on the page header (see the the screenshot). Second way to disconnect is from the connections page (https://raptors.ru/accounts/social/connections/). However, if the user clicks the Remove button, Django doesn't do it and report following error: Your account has no password set up. Please tell me, which is the correct and working way to disconnect (or completely remove) the Facebook user from my site? FB insists that I should provide this option. -
Django ORM in multi threading task does not save data into model
In my django app i schedule a threading process for run every n seconds a thread designed for save data into a table. in my init file i do: class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False so, from my init i do: ... rc = RepeatedTimer(300, save_calc) ... ok, my cll start as a thread and in this method a save some data in two different table, but just the first save() call was ok, the second does'n do anything: ... vr = VarsResults(key_res=Results.objects.get(res_key=p.res_key), var_id=v_id, var_val= v_original, var_val_conv = v_conv, var_hash=hash_vars.hexdigest()) vr.save() time.sleep(0.5) # if val trigger alarm save in if v_alarm and v_alarm.alarms_val: if eval(str(v_conv)+v_alarm.alarms_val): av = VarsAlarm(n_occurence=2, var_id=ModbusVariable.objects.get(id=int(v_id))) av.save() time.sleep(0.5) Why after the first vr.save() nothing appen?the second query does not execute (the query is correct, also if i insert a print or a logging code nothing appen) There are ome other way for achieve this in multithreading mode? So many … -
Django Form is not submitting for some reason
My Django form is not submitting for some reason, When I click submit and go to the admin page to see the instance I don't find anything, Here's the code: views.py: from django.shortcuts import render from .models import User from .forms import SignUpForm def signup(request): username = request.POST.get('username') password = request.POST.get('password') data = User(username=username, password=password) return render(request, 'pages/signup.html', {'suf': SignUpForm}) forms.py: from django import forms class SignUpForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(max_length=50) models.py: from random import choice from statistics import mode from django import views from django.db import models from django.forms import ModelForm class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __str__(self): return self.username admin.py: from django.contrib import admin from .models import User admin.site.register(User) signup.html: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Sign Up</title> </head> <body> <div class="signContainer"> <form name="signUpForm" method="POST"> {% csrf_token %} {{suf}} <input type="submit" value="Sign Up" class="submitButton" /> </form> </div> </body> </html> {% endblock content %} -
I want to update a small part of my webpage using ajax How can I do that in Django?
Basically I have three models class category(models.Model): name = models.CharField(max_length=40) class subCategory(models.Model): category = models.ForeignKey(category, on_delete= models.CASCADE) name = models.CharField(max_length=40) class product(models.Model): name = models.CharField(max_length= 40) image = models.ImageField(upload_to="media/upload_to") price = models.DecimalField(max_digits=10, decimal_places= 3) price_off = models.DecimalField(max_digits=10, decimal_places=3) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(category, on_delete= models.CASCADE) sub_category = models.ForeignKey(subCategory, on_delete= models.CASCADE) These are the models that I have worked on Now I have to apply ajax on my given template so I don't know how to start There is my image When I clicked on Samsung then Samsungs product will show and as well others This is my index.html <div id="mobile-list" class="section-container bg-silver p-t-0"> <!-- BEGIN container --> <div class="container"> <!-- BEGIN section-title --> <h4 class="section-title clearfix"> <a href="#" class="pull-right">SHOW ALL</a> Mobile Phones <small>Shop and get your favourite phone at amazing prices!</small> </h4> <!-- END section-title --> <!-- BEGIN category-container --> <div class="category-container"> <!-- BEGIN category-sidebar --> <div class="category-sidebar"> <ul class="category-list"> {% for data in mc %} <li class="hit" name="{{ data.name }}" data-name="{{ data.name }}"><a href="#"> {{data.name}}</a></li> {% endfor %} </ul> </div> <div class="category-detail"> <!-- BEGIN category-item --> <a href="#" class="category-item full"> <div class="item"> {% for data in mobilePhone %} {% if forloop.counter == 1 %} <div … -
How to stop the following python code after a certain time?
I have to run a python command function in the following manner: from django.core.management import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('length', type=int) parser.add_argument('breadth', type=int) def handle(self,*args,**options): func= Library_Class() result= func.library_function(length,breadth) return This code gives arguments to the library function which in turn returns the required output. I want to stop this command function after 10 seconds of run time. How Do I use multiprocessing or any other library to do that? -
how to fill a table in my database automatically with data added to another table?
I am currently developing a management application and I have reached a level where I have to ensure that one of my tables, precisely the stock table, must be automatically filled with data from the location and article tables. In other words, the stock is created when there is a location and a product created. I tried to use the signals as in the documentation but it does not work. Can you help me on this please. models.py class Location(models.Model): class CHOICES(models.TextChoices): FOURNISSEUR = 'Fr', 'Fournisseur' VEHICULE = 'Vl', 'Véhicule' DEPOT = 'Dt', 'Dêpot' location = models.CharField(max_length=255, choices=CHOICES.choices) name = models.CharField(max_length=255, verbose_name="Location Name", unique=True) provider = models.ForeignKey(Provider, on_delete=models.CASCADE, null=True, blank=True) depot = models.ForeignKey(Depot, on_delete=models.CASCADE, null=True, blank=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Stock(TimeStampBaseModel): location = models.ForeignKey(Location, on_delete=models.CASCADE) product = models.ForeignKey(Article, on_delete=models.CASCADE) qty_stock = models.FloatField(verbose_name="Quantity Purchase", db_index=True, default=0) def __str__(self): return self.stock_name class Meta: constraints = [ UniqueConstraint(name='unique_storage', fields=['id', 'location', 'product']) ] signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Location, Stock from article.models import Article @receiver(post_save, sender=Location) def create_stock(sender, instance, created, **kwargs): if created: attrs_needed= ['location', 'product', 'qty_stock'] Stock.objects.create(location=instance.location, product = instance.product, qty_stock=instance.qty_stock) post_save.connect(create_stock, sender=Location, weak=False) -
I added a Like model but I don't know how to increase the number of like
I created a Blog app, and i want to add a Like button to each post in the Blog, how can i do this ? how can i make this happen in view and the template ? the models: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Photo, on_delete=models.CASCADE) def __str__(self): return str(self.user) the view: def viewPhoto(request, pk): post = get_object_or_404(Photo, id=pk) photo = Photo.objects.get(id=pk) return render(request, 'photo.html', {'photo': photo, 'post': post })