Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Using Faker to fill multiple tables
I am trying to populate my Django project with some test data. I have 3 tables, Person, Address, Employment. Both Address and Employment have a Person FK. My script is creating my person but when it gets to Address it fails at Address.person models class Person(models.Model): first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Address(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) address = models.CharField(max_length=200, blank=True, null=True) class Employment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) employer = models.CharField(max_length=200) My script def populate(n=5): for entry in range(n): person = Person.objects.get_or_create( first_name = fakegen.first_name(), middle_name = fakegen.first_name(), last_name = fakegen.last_name(), FakeAddress(person) FakeEmployment(person) def FakeAddress(person): address = Address.objects.get_or_create( person = person, address = fakegen.street_address(), TypeError: Field 'id' expected a number but got <Person: Michael Baker>. I've tried to pass the Person to the address function and I get TypeError: Field 'id' expected a number but got <Person: Michael Baker>. Next I tried passing the Person's ID instead of the person and I get ValueError: Cannot assign "93": "Address.person" must be a "Person" instance. -
How to notify users of new blog post via django?
I am building a mobile app using Django Rest Framework, Flutter, and MongoDB. In that app users can view posts posted by other users. In my Django app, I don't have any notification model (and honestly don't really know how to use that either!). In Django, I have created endpoints to create posts @api_view(['POST']) def createPost(request): code/logic... , and to retrieve posts class blogsViewSet(ModelViewSet): queryset = Posts.objects.all() serializer_class = PostSerializer pagination_class = pagination.CustomPagination def list(self, request, *args, **kwargs): uid = request.META.get('HTTP_DATA') context = {"user": uid} queryset = Posts.objects.all().order_by('postID') paginatedResult = self.paginate_queryset(queryset) serializer = self.get_serializer(paginatedResult, many=True, context= context) return Response(serializer.data) Now in my app, lets say I have two users: User A, and User B. now if both of them are using the app at the same time and user A creates a new post, I want user B to be notified and showed that new post immediately, without the user B having to reload the page himself/herself. Now my question is, can I achieve this by using Django channel only, or do I have to use Redis (or any similar service). If yes, then how? Thanks! -
Boolean field update due to another field change in Django Admin
I have model Department like: class Department(models.Model): dep_title = models.CharField(max_length=30, verbose_name='Title') dep_description = models.CharField(max_length=100, blank=True, verbose_name='Description') dep_status = models.BooleanField(default=False, verbose_name='Is Active?') dep_start = models.DateField(verbose_name='Date of Establishment') dep_end = models.DateField(blank=True, verbose_name='Closing Date', null=True) and DepartmentAdmin: class DepartmentAdmin(admin.ModelAdmin): list_display= ('dep_title','dep_description','dep_status', 'dep_start', 'dep_end') I want to check dep_end date and if date is expired, set automatically dep_status = False How can I implement this? -
how to fix django.db.utils.IntegrityError
I have two nested models (task and Proposal) with a foreign key relationship, i've followed every necessary step but i'm getting an inegrity error below is d err and codes Serializer 1st serializer class JobSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username', read_only=True ) user_id = serializers.CharField(source='user.id', read_only=True) proposals = ProposalSerializer(many=True, read_only=True) class Meta: model = JobPost fields = [ 'user', 'user_id', 'id', 'proposals', 'etc' ] 2nd Serializer class ProposalSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username',read_only=True) class Meta: model = Proposal fields = [ 'id', 'proposal_description', 'duration', 'bid', ] APIVIEW class ProposalAPIView(generics.CreateAPIView): serializer_class = ProposalSerializer look_up = 'id', queryset = Proposal.objects.all() permissions_classes = [permissions.IsAuthenticated] 2nd APIView class CreateJobPost(generics.CreateAPIView): serializer_class = JobSerializer permissions_classes = [permissions.IsAuthenticated] def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data ) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) res = { 'message': 'Job Post Successfully Created', 'status': status.HTTP_201_CREATED, 'serializer': serializer.data } return Response(res) err msg django.db.utils.IntegrityError: null value in column "task_id" violates not-null constraint DETAIL: Failing row contains (3cc5ac3f-f1ef-4833-b775-a18ffa1b471b, 4 days, ahhdgdg, 10000, 2022-01-31 15:01:25.753828+00, null, null). can anyone pls help -
How do I import Django models into python file?
I have a Django model which stores inputs from a form, now that I have the data stored in Django I need to import those models to a python file. -
Django Formset Posting but formset is never valid
I have created a Formset based on modelformset_factory and an existing Form in my view and pass it a queryset of objects to edit. These render correctly on the view but whenever I try and confirm, it does not save. Printing the statement (print(formset.is_valid()) I see that this is what is stopping the formset saving. How does one correctly pass existing queryset to a formset to edit? Forms.py class RSVPForm(forms.ModelForm): class Meta: model = Invite fields = ['guest_name', 'plus_one', 'dietry_requirements', 'rsvp_attendance'] Views.py def view_rsvp_create(request, event_id, guest_id): event = get_object_or_404(Event, id=event_id) guest = get_object_or_404(Guest, id=guest_id) invites = Invite.objects.filter(event=event, guest=guest) RSVPFormset = modelformset_factory(Invite, form=RSVPForm, extra=0) formset = RSVPFormset(queryset=invites) if request.method == 'POST': if formset.is_valid(): print('okey') formset.save() return redirect('view_rsvp_overview', name = guest.wedding.subdomain, code = guest.code) data = {'formset': formset, 'guest': guest, 'wedding': event.wedding, 'invites':invites} template='experience/rsvp-create.html' return render(request, template, data) update.html ... <form method="post"> {% csrf_token %} {{ formset | crispy }} <button type="submit" class="btn">{% trans "Confirm RSVP" %}</button> </form> ... -
Celery inspecting workers in Django Management Command results in inconsistent behavior
I have a simple piece of code that I use to determine the number of active Celery tasks, using the Inspect API, inspired from this part of the documentation: from myapp.celery import app app.control.inspect().active() Running this from the Django shell gives me the right output every time, so no problem there. However, I am trying to write a very simple Django Management Command that runs the same code. The file structure looks like this: myapp └── celery.py └── settings.py | __init__.py secondapp └── management │ └── commands │ └── __init__.py │ └── celery_workers.py │ __init__.py | __init__.py manage.py Keeping it as simple as possible, the command would look like this: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): from myapp.celery import app print(app.control.inspect().active()) Running this command as python manage.py celery_workers occasionally gives the expected output (same as running from the shell), but more often than not it says that there are no running tasks (knowing there are running tasks): {'app@project': []} I am wondering what could be the cause of this discrepancy. -
pdf link for search result
i want display a simple link for my pdf folder (static/media) in my search result , i try some things but not work. thank for watching :) view.py class SearchResultsList(ListView): model = Actes model= Pdflink context_object_name = "actes_context" template_name = "search_result.html" def get_queryset(self): query = self.request.GET.get("q") vector_column = SearchVector("contenue", weight="B") + SearchVector( "contenue", weight="A")+ SearchVector ("title", weight="C") file_path = os.path.join(settings.MEDIA_ROOT) if os.path.exists(file_path): with open(file_path, 'rb') as fh: link = Actes.title == Pdflink.title if link is True: link= Pdflink.title + '.pdf' return link response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response, link search_query = SearchQuery(query) search_headline = SearchHeadline("contenue", search_query) return ( Actes.objects.annotate(rank=SearchRank(vector_column, search_query)).annotate(headline=search_headline) .filter(rank__gte=0.8) .order_by("-rank") ) and i don't know how to write the "<a href =..." for display the result for the pdf link in my template -
Problem displaying admin in Django project
I ran the Django project on the C panel, but it looks like this in the admin section. -
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'), …