Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django set record in custom order
how to set custom order of record in queryset? ex: Queryset has this values <QuerySet [{'id': 5, 'order_number': 1}, {'id': 3, 'order_number': 2}, {'id': 2, 'order_number': 3}, {'id': 1, 'order_number': 4}, {'id': 7, 'order_number': 5}, {'id': 4, 'order_number': 6}]> the request set the order of item of id=5 to be 3rd record of the queryset so the queryset should be: <QuerySet [{'id': 3, 'order_number': 1}, {'id': 2, 'order_number': 2}, {'id': 5, 'order_number': 3}, {'id': 1, 'order_number': 4}, {'id': 7, 'order_number': 5}, {'id': 4, 'order_number': 6}]> I Could loop over all the queryset items and set the order every time, but I am asking if there is any better solution. -
How to run again that cronjob when the same job finished
I have a cron job that runs every 20 minutes from 9-5. Here is the code: */20 09-05 * * * I want it set so that if the job ends in 10 minutes, it starts again automatically. When the scheduled time exceeds 20 minutes, the next job runs when the first is finished. It is a python server running on an Ubuntu operating system. According to crontab.guru: // * * * * * // It runs after every minute So, if anyone have any solution, please reply me. -
Django Modelviewset try to create custom route
@action(detail=False, methods=['GET'], name='Get Vesting Locaitons') def get_vesting_locations(self, request, pk=None, *args, **kwargs): I'm trying to return json response and get 404 error this is the the route regiser router.register(r'vesting', VestingViewSet, basename='vesting') and those are the urls im trying to get http://localhost:8000/vesting/get_vesting_locations/617b8bd8-6fdd-43eb-948a-4b17d1a0a089/ http://localhost:8000/vesting/617b8bd8-6fdd-43eb-948a-4b17d1a0a089/get_vesting_locations/ -
How Can I Deploy Django with Apache and Gunicorn on CentOs7?
I have been trying to deploy django on my CentOs 7 server (release 7.9.2009) for a bit now, and I have tried the nginx + gunicorn route as well as the Apache + mod_wsgi route. However, both of them hit roadblocks, namely that Apache was blocking nginx, and that my version of CentOs7 is not compatible with mod_wsgi. So, I tried mod_proxy_uswgi but there is not much in the way of tutorials or information on how to using that module with Apache. Then, I finally settled on attempting to use gunicorn to serve my files, and using an Apache config. Still, nothing of any use. The structure of my django project is . ├── manage.py ├── static │ └── admin ├── testproject │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── venv Here is the relevant code django.conf <VirtualHost *:80> ServerName mydomainname.com ProxyPreserveHost On ProxyPass /static/ ! ProxyPass / http://0.0.0.0:8000/ ProxyPassReverse / http://0.0.0.0:8000/ ProxyTimeout 300 Alias /static/ /home/user/django_test/static/ <Directory /home/user/django_test/testproject> <Files wsgi.py> Require all granted </Files> </Directory> <Directory "/home/user/django_test/static/"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> </VirtualHost> Relevant portion of settings.py ALLOWED_HOSTS = ['*'] ... STATIC_URL = '/static/' … -
How to set default values into an Array Field Django?
I would like to know how to set default values into a Django Array Field Model. I have a TextChoices model named "GameType" : class GameType(models.TextChoices): ''' Enumeration of all different game types ''' EVIL = 'evil', 'evil' SOLOCOOP = 'solo', 'solo' MULTI = 'multi', 'multi' And in my Item model, I can choose in each mode my item is available. Then I have these lines : game_types = ArrayField( models.CharField( default=GameType.SOLOCOOP, max_length=40, choices=GameType.choices ), default=default_item_game_types, null=False, blank=False) Two things : The first default key "GameType.SOLOCOOP" doesn't work The default list doesn't work too Here is my "default_item_game_types" function : def default_item_game_types(): '''Default callable to avoid errors ''' return list(GameType) And in my CMS, I don't have my default values : Screenshot of my Game types field I tried many things and searched many solutions but nothing matched in my case. Is there any response to fix my issues ? Thanks for your time Regards, Steven -
Django query - how to filter sum by date?
I am struggling with a queryset in a Django view. Basically, I have three models: User, ActivityLog, & ActivityCategory. User is the built-in. ActivityLog looks like this: class ActivityLog(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user') activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat') activity_description = models.CharField(max_length=100, default="Misc Activity") Activity Category: class ActivityCategory(models.Model): activity_name = models.CharField(max_length=40) activity_description = models.CharField(max_length=150) pts = models.IntegerField() My goal is to return an aggregate by user of all the points they have accumulated by participating in activities in the log. Each log references an ActivityType, different types are worth different points. I accomplished this with the following query in the view: class UserScoresAPIView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserScoresSerializer def get_queryset(self): queryset = User.objects.annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts') return queryset So now I need to add to this query and restrict it based on date of the activity. I want to basically add a filter: .filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)') How can I add this into my current query to accomplish this? I tried to do so here: queryset = User.objects.annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts').filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)') , 0)).order_by('-total_pts') But that would happen after the Sum and wouldn't be helpful (or work...) so I tried to chain it where it is pulling the User objects User.objects.filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)').annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts') … -
How to create api for this including put,get,post method using serializer?
class normal(models.Model): active = models.BooleanField(default=True) created_on = models.DateTimeField(auto_now_add=True,null=True) created_by_id = models.IntegerField(null=True) updated_on = models.DateTimeField(auto_now=True,null=True) updated_by_id = models.IntegerField(null=True) class Meta: abstract=True class Role(normal): name = models.CharField(max_length=100) description = models.TextField(null=True) class Meta: db_table = 'environment_role' -
Save data type JSONField from celery
model.py: from django.db import models from datetime import datetime from django.db.models import TextField, JSONField, Model # Create your models here. class reservation(models.Model): res=models.JSONField() da = models.DateTimeField(default=datetime.now, blank=True) tasks.py: @shared_task def ress(): content={ "customer": 48, "reservation_id_pms": str(id), "reservation_channel_number": None, "reservation_group_id_pms": "ed2b9d55-46d9-4471-a1e9-ad6c00e30661", "extra_reservation_code": "550ca1c1", } reservations=reservation.objects.create(res=content) reservations.save() res.append(content) return None ereur: from django.db.models import TextField, JSONField, Model ImportError: cannot import name 'JSONField' from 'django.db.models' (/usr/lib/python3/dist-packages/django/db/models/init.py) -
Django RadioButton in HTML
in my custom form I've radiobutton to select my user gender. When I try to submit the form it gives me back this error 'UserInfo' object has no attribute 'is_valid' Since this error started after I've edited my html template using only html and not {{ form.as_p }} I waas wondering if the problem could it be the way I write the radiobutton input since I'm not sure this is the way to use it. Thank you all for your help! model.py class UserInfo(models.Model): gender_choice = (('Male', 'Male'),('Female', 'Female')) user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) gender = models.CharField(max_length=120, choices=gender_choice) forms.py class UserInfo(ModelForm): class Meta: model = UserInfo fields = ('first_name', 'last_name', 'gender') views.py def add_information(request): submitted = False if request.method == "POST": form = UserInfo(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('add_information?submitted=True') else: form = UserInfo if 'submitted' in request.GET: submitted = True return render(request, 'accounts/profile/tempplate.html', {'form': form, 'submitted':submitted}) template.html <form action="" method=POST> {% csrf_token %} <label>First Name:</label> <div class="input-group mb-2"> <div class="input-group-append"> </div> <input type="text" name="first_name" placeholder=""> </div> <label>Last Name:</label> <div class="input-group mb-2"> <div class="input-group-append"> </div> <input type="text" name="last_name" placeholder=""> </div> <label>Gender:</label> <div class="input-group mb-2"> <div class="input-group-append"> </div> <input type="radio" id="male" name="gender" value="male"> <label for="male">Male</label> … -
Angular css does not fully load when built with prod. Served from django
I'm using angular with django. I set up a docker container that builds the app, then collects the static info. Most of the css works, but the css in the src/styles.css seems Here are my angular versions: Angular CLI: 9.0.1 Node: 16.10.0 my build command is: RUN yarn install && yarn build --prod --output-hashing none my angular.json "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/occtool", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": true, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css" ], "scripts": [] }, I'm not sure what else might be relevant but feel free to comment and I will edit my post. My component css files seem to mostly load fine. I use the material theme for a mat tab group. One works with my css, the other uses the deep purple css only. ng serve --prod does load the css as expected. Network traffic doesn't show any failed requests to get css from django. -
Multiple Foreign Keys entry in Django Admin
I am having an issue with a projectapp in Django. Basically, what I need to do is creating a page where I display the item contained in a certain flight mission (I am developing the software for a flight school). The models code should be something like this: models.py class FlightMissionItem(models.Model): flight_item = models.CharField(max_length=800) class FlightMission(models.Model): title = models.CharField(max_length=300) pre_flight_comment = models.TextField(blank=True, null=True) flight_item = models.ForeignKey( FlightMissionItem, on_delete=models.CASCADE) grading = models.CharField( max_length=1, choices=GRADING_CHOICES, null=True, blank=True) flight_comment = models.TextField(blank=True, null=True) debriefing_comment = models.TextField(blank=True, null=True) What I am trying to do, is to have multiple flight_item inside the FlightMission model. I post also the admin models: admin.py class FlightMissionItemAdmin(admin.StackedInline): model = FlightMission class FlightMissionAdmin(admin.ModelAdmin): inlines = [FlightMissionItemAdmin] The problem is that, anytime I try to modify the admin.py, I receive an error like this: <class 'flight.admin.FlightMissionItemAdmin'>: (admin.E202) 'flight.FlightMission' has no ForeignKey to 'flight.FlightMission'. The only way I was able to find a loophole in the error was to add another ForeignKey to the FlightMissionItem model. The problem was that basically I was able to loop over just 1 item in the FlightMission later on, so I wasn't able to display anything useful in the HTML. I hope that is clear, otherwise I'll … -
Get prefix from Netherlands names
I have a social network with users from the Netherlands on Django. With my site I can get the Netherlands name, for example, Jap van der Stael, and I need to get only van der part. For this name it's not a problem, but how to get infix from a name like Jap van der Vulpen - Odijk? For now i have next code: ' '.join(last_name.split()[:-1] But if last name is Jap van der Vulpen - Odijk, its return 'van der Vulpen -' -
How to show the profile of the post author from post detail Django
I want to show the author profile to the visitors, who visit the post details. My views.py is: def usercv(request): post = Post.objects.filter(id=id) postusercv = post.author.profile context={ 'posts':postusercv } return render(request,'arcmap/usercv.html',context) My urls.py is: path('post/usercv/',views.usercv,name='user-cv'), my user_cv.html is: {% extends 'arcmap/base.html'%} {% block content%} {% for post in posts %} {{post.username}} {% endfor %} {% endblock %} Inside of the post_detail, I use the link which is: <h4> Our Profile:</h4><a href="{% url 'user-cv'%}">Our profile</a> And the error is: TypeError at /post/usercv/ Field 'id' expected a number but got <built-in function id>. -
remove an element from select once added to the db (filtering)
post code and photos because I don't know how to explain the problem. I have this green button that opens a modal which allows me to create a group and save it in the db once clicked on add group. After adding the object in the db I reload the page with the data entered via modal, if I click again on the green button I have the possibility to add another object. The problem that I can always add the same object in the select, I wish that once added there is no longer the possibility to add it. form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] html {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">CREA</h1> <a href="{% url 'lista-gruppi' %}" class="btn btn-outline-primary">LISTA</a> </div> <hr> <div class="scheda mb-4"> <div class="d-flex justify-content-between align-items-center"> <h4 style="margin-bottom: 0;">Nome: {{ scheda.nome_scheda }}</h4> <div> <p style="margin-bottom: 0;"> <span><strong>Inizio: {{ scheda.data_inizio }}</strong></span> | <span><strong>Fine: {{ scheda.data_fine }}</strong></span> </p> </div> </div> </div> <div class="box"> {% for gruppo in scheda.gruppi_scheda.all %} <div class="gruppo mb-3"> <div class="d-flex justify-content-between align-items-center"> <p style="margin-bottom: 0;">{{ … -
(Django) Delete function does not remove data from database
Currently I'm having a table that shows the list of drugs. This table has a delete button in every data row. When I click it, the row does not go away. I tried the same delete syntax (in the function called 'destroy') in Django shell and it worked. I just don't understand why when I clicked on the Remove button inside the template, nothing happened, even after refreshing. drugs/views.py from django.shortcuts import render, redirect from django.views.generic import ListView from .models import ( Drug, ) from .forms import ( DrugForm, ) def add_drug(request): forms = DrugForm() if request.method == 'POST': forms = DrugForm(request.POST) if forms.is_valid(): drug_id = forms.cleaned_data['drug_id'] name = forms.cleaned_data['name'] drug_type = forms.cleaned_data['drug_type'] Drug.objects.create(drug_id=drug_id, name=name, drug_type=drug_type) return redirect('drug-list') context = { 'form': forms } return render(request, 'drugs/add_drug.html', context) def destroy(request, drug_id): d = Drug.objects.get(drug_id=drug_id) d.delete() d.save() return redirect("/") class DrugListView(ListView): model = Drug template_name = 'drugs/drug_list.html' context_object_name = 'drug' ddms/urls.py from django.contrib import admin from django.urls import path, include # local from .views import base, dashboard from drugs.views import destroy urlpatterns = [ path('admin/', admin.site.urls), path('', dashboard, name='dashboard'), path('drugs/', include('drugs.urls')), path('delete/<int:drug_id>', destroy), ] templates/drugs/drug_list.html <div class="card-body--"> <div class="table-stats order-table ov-h"> <table id="bootstrapdatatable" class="table"> <thead> <tr> {% comment %} <th class="serial">#</th> … -
Django multiple user roles in many organisations
I am trying to design a multiple user model where a user can have different roles for different organisations, for example; User A can be an admin for organisation_1 User A can be an employee for organisation_2 User A can be a manager for organisation_3 User B is an employee for organisation_1 What I have found is to use the abstract user; class User(AbstractUser): is_user = models.BooleanField('student status', default=False) is_admin = models.BooleanField('student status', default=False) is_manager = models.BooleanField('student status', default=False) is_employee = models.BooleanField('teacher status', default=False) The way I see it is that it can work if you have one or many roles but under one organisation. How can I connect this to an organisation model? -
App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz at deploying project on heroku server
Django project deploy on heroku server, at the time fetch an error at push a project on heroku. Enumerating objects: 63, done. Counting objects: 100% (63/63), done. Delta compression using up to 4 threads Compressing objects: 100% (60/60), done. Writing objects: 100% (63/63), 335.77 KiB | 11.19 MiB/s, done. Total 63 (delta 3), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to youtube-to-mp3converter. remote: To https://git.heroku.com/youtube-to-mp3converter.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/youtube-to-mp3converter.git' How can solve it. -
Update django without pip [duplicate]
I have to install django, but when I installed it, it was one of the oldest version (1.10). I would like to update the package but without pip because I do not have internet connection in this computer. Anyone have a solution ? -
How to convert a django model field to different dimension on save?
I'd like to convert dollars to cents on save for the Django model. How can I do it by using the Django Model environment? -
Django static style.css styling
I want to share this problem that I got, I made 2 apps in my Django project and one of the apps has a static folder with the file style.css. Everything works but when I try to add a new style let's say I am adding some styling to a div it does not work apparently. Only some of the styles work(older styles) then new ones I try to add it just does not work in templates. -
Mock a const in python
I have in view filterset_class = main_app.api.filters.TestClassFilter and there field id__in class TestClassFilter(FilterSet): id__in = BaseInLimitFilter( field_name="id", label='Id in', limit=LIMIT ) with custom filter class api.filters.BaseInLimitFilter class BaseInLimitFilter(BaseInFilter): message = _("At most {} values are allowed.") limit = 10 def __init__(self, *args, **kwargs): if 'limit' in kwargs: self.limit = kwargs.pop('limit') super(BaseInLimitFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if len(value) >= self.limit: raise ValidationError({ "id__in": self.message.format(self.limit) }) return super(BaseInLimitFilter, self).filter(qs, value) I try mock const api.const.LIMIT and set value as 1 in my test but I have problem with it. I tried something like that: @mock.patch('main_app.api.filters.LIMIT', 1) Does anyone have any ideas what am I doing wrong? -
Django Form validation error (Select a valid choice) when use "queryset=Product.objects.none()"
I use formset_factory when I get an order for products product_formset = formset_factory(OrderProductsForm,extra=5) It works when I use “qeryset=Product.objects.all()” in “OrderProductsForm(forms.ModelForm):“ self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),empty_label="Ürün Seciniz", widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'})) but it gets all products so page load time increase. I would like to use “queryset=Product.objects.none() “ But at that point when I check the form in my view.py if request.method == "POST": formset = product_formset(request.POST) if formset.is_valid(): get an error as “Select a valid choice. That choice is not one of the available choices.” Do you have any suggestion ? thanks Forms.py class OrderProductsForm(forms.ModelForm): class Meta: model = OrderProducts fields = ['amount'] def __init__(self, *args, **kwargs): super(OrderProductsForm, self).__init__(*args, **kwargs) self.fields['product_category'] = ModelChoiceField(queryset=ProductCategory.objects.all(),empty_label="Ürün Grubunu seciniz", widget=forms.Select(attrs={"onChange":'myFunction(this.value,this.id)'})) #self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),empty_label="Ürün Seciniz", widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'})) self.fields['product'] = ModelChoiceField(queryset=Product.objects.none() ,empty_label="Ürün Seciniz",required=False,widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'})) self.fields['stok'] = forms.CharField(required=False,disabled=True,max_length=5) -
Django: Cannot update foreign key values in a model
When I create this model, the values are nulls. class TestRequest(models.Model): class Meta: verbose_name_plural = "TestRequest" title = models.CharField(max_length=256, null=True, blank=True) testConfiguration = models.ForeignKey( TestConfiguration, on_delete=models.PROTECT, null=True, blank=True) testDescription = models.ForeignKey( TestDescription, on_delete=models.PROTECT, null=True, blank=True) The serializer: class TestRequestSerializer(serializers.ModelSerializer): class Meta: model = TestRequest fields = [ 'id', 'title', 'testConfiguration', 'testDescription', ] depth = 2 The view: @api_view(['PUT']) def TestRequestUpdate(request, pk): testRequest = TestRequest.objects.get(id=pk) serializer = TestRequestSerializer(instance=testRequest, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And when I want to update them later from the front-end with this state: id: 98 title: "title" testConfiguration: 31 testDescription: 32 I get this response: { "id": 98, "title": "title", "testConfiguration": null, "testDescription": null } Why can't I update it? -
Django ElasticSearch DSL partial matching using nGram analyzer
I'm quite new to the ElasticSearch topic and I'm trying to implement simple e-commerce search in my Django application using ElasticSearch with library django-elasticsearch-dsl Github repo . The thing I'm trying (extremely simplified) to achieve is that, considering these Django model instances: Red T-shirts Blue T-Shirts Nice T-Shirts for search term T-Sh I'll obtain all these three results: Red T-shirts Blue T-Shirts Nice T-Shirts So I have this model in shop/models.py (again very simplified) class Category(models.Model): title = models.CharField(max_length=150, blank=False) description = models.CharField(max_length=150, blank=False) # In reality here I have more fields def __str__(self): return self.title With shop/documents.py from elasticsearch_dsl import analyzer, tokenizer autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20), filter=['lowercase'] )from elasticsearch_dsl import analyzer, tokenizer @registry.register_document class CategoryDocument(Document): title: fields.TextField(analyzer=autocomplete_analyzer, search_analyzer='standard') # Here I'm trying to use the analyzer specified above class Index: name = 'categories' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'max_ngram_diff': 20 # This seems to be important due to the constraint for max_ngram_diff beeing 1 } class Django: model = Category fields = [ 'title', # In reality here I have more fields ] And finally, my shop/views.py class CategoryElasticSearch(ListView): def get(self, request, lang): search_term = request.GET.get('search_term', '') q = Q( "multi_match", query=search_term, fields=[ 'title', … -
Login to Django Admin page with UUID username
I have created a DRF api with a Account model identified by an UUID. I also use this UUID as the username and thus have to log in to the admin page by providing the UUID and password. However if I try this I get the error “6c3fe924-1848-483a-8685-c5b095f1” is not a valid UUID. Which is very strange since this is created using UUID.uuid4. My Account model is as follows class Account(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'id' objects = AccountManager() def __str__(self): return str(self.id) The AccountManager() referenced is a custom manager since this Account model is coupled with different types of user models. I do not think this code makes a difference but if anyone want me to upload this as well, let me know.