Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a statefull Django API server?
I'm creating an API using Django, which receives an image, analyzes it using some AI models, and returns the result. The models are pretty heavy, so I want to load them only once on the application start and keep them in the memory. The models are encapsulated in a class, so my idea is to create a global object being an instance of this class and use it inside of the view. Is it the way to go? If so, where to keep this object? The only possibility that comes to my mind is the views.py file. What is the best way to achieve this? Thanks in advance! -
Embedding real-time Grafana dashboards in Django web application
I want to embed a real-time grafana dashboard into my django web application. Currently, I have embedded the individual panels of the dashboard in my django applications using the iframe link that is generated by grafana, but they are just a snapshot of the graph and the individual panels do not scroll automatically to the current time. -
Django Windows not working, how do I fix it?
I installed Python on Windows so I can install Python packages and Django was one of them. Installation command: pip install Django After installation, I decided to open up Django Django but I got an error saying: Django: The term 'Django' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. -
How to do web scraping with django
I am developing a backend in django and I want to make an api that retrieves data from a web. I scraped with selenium but I don't know how to import it into a django view. -
'psycopg2.errors.UndefinedTable: relation "table" does not exist' when makemigrations
I have a django app and I am trying to migrate from sqlite3 to postgres. I have been following multiples guides on how to do this, and they all do more or less the same and those are the steps I followed: Get a dumpdata with python manage.py dumpdata > whole.json Create db and user and connect to it Config settings.py to set everything to the new database Delete old migrations run python manage.py makemigrations or python manage.py migrate --run-syncdb There are more steps, but I am stuck in this 5th one getting 'psycopg2.errors.UndefinedTable: relation "table" does not exist' Looking for solutions I've come to this post which may help someone, though I might not doing it right or something but commenting models have done nothing for me. Thanks. -
how to render values from multiple methods vertically in template django
I have a django application. And I try to render the values from different methods vertical in the template. So I have this two methods combined in one method: class FilterText: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] def show_extracted_data_from_file(self): return self.total_cost_fruit() , self.total_cost_fruit2() and views.py: def test(request): content_pdf = "" content_pdf = filter_text.show_extracted_data_from_file() context = { "content_pdf": content_pdf, } and template: <div class="wishlist"> <ul class="nobull"> {% for value in content_pdf %} <span {% if value in diff_set %} style="color: red;" {% endif %}> <li>{{value}}</li> </span> {% endfor %} </ul> </div> But at the moment it displays: [3588.2, 5018.75, 3488.16] [3588.2, 5018.75, 3488.99] But I want to have them to display like: 3588.2 3588.2, 5018.75 5018.75 3488.16 3488.99 So next to ech other. Question: how to display the values next to each other? -
using register_converter() on all ModelViewSet viewsets
Is there a way to use path converters with ModelViewSet without explicitly writing the path urls ? For example I have this path converter: from .utils import REGEX from . import encode_id, decode_id class HashidsConverter(): regex = REGEX def to_python(self, value: str) -> int: return decode_id(value) def to_url(self, value: int) -> str: return encode_id(value) in urls.py file router = DefaultRouter() router.register("client", ClientModelViewSet) register_converter(HashidsConverter, "hashid") urlpatterns = [ path('admin/', admin.site.urls), #path('', include(router.urls)), path('client/<hashid:pk>', ClientModelViewSet.as_view({"get":"retrieve"}), name="client") ] -
get a dictionary variable to use it in the same dictionary to get the file extension django python
I am creating a folder tree to display it. For this I need to get the file extension. Before the folder we nedd to enter a pasword. my views.py ` def www_telechargements(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = CatalogueForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: context = { 'mdp': form.cleaned_data["response_mdp"] } good_answer = ("\n".join(context.values())) if good_answer == "Vitasolar1234": template = loader.get_template('telechargement-response.html') arborescence_path = os.path.join(BASE_DIR, "WWW/static/arborescence") arborescence_content = os.listdir(arborescence_path) response_gabarit = { 'answer': True, 'dossier': arborescence_content, 'type': pathlib.Path(os.listdir(response_gabarit('dossier')).suffix)#c'est ici que je veux récupérer le string de 'dossier' } print(os.listdir(arborescence_path)) return HttpResponse(template.render(response_gabarit, request)) else: response_gabarit = {'answer': False} template = loader.get_template('telechargement-response.html') return HttpResponse(template.render(response_gabarit, request)) # if a GET (or any other method) we'll create a blank form else: form = CatalogueForm() return render(request, 'telechargements.html', {'form': form}) this is my mistake : 'type': pathlib.Path(os.listdir(response_gabarit('dossier')).suffix) UnboundLocalError: local variable 'response_gabarit' referenced before assignment I would like to get the string 'dossier' but it is not possible I understand my mistake but I have no idea how to solve this problem I tried to use my … -
How to speed-up (avoid) django boot time when running tests?
When I write django tests, I frequently run then manage.py tests command. To increase test run performance I'm aware of --keepdb and --parallel options. I'm also aware of being able to run a specific test by targeting it. I usually run something like this : manage.py tests myapp.tests.test_file.MyTestCase.test_my_test --keepdb The problem is that each time I run the command, django took few seconds (around 10 seconds in the current project) just to boot-up and start processing the tests. So during a test development I have to wait 10 seconds each time whereas the test itself took 1 second. There is a way to enter a sort of "test mode" which keep django booted-up ? So that I can run tests without to wait for 10 seconds boot time after each code modification. -
Django sub-query in Case When
I have such query qty_used_annotation = Case( When(scope='ticket', then=BookedTicket.objects.filter( global_discount_code__code=F('code'), booking__status__in=['i', 'c', 'g', 'r', 's'] ).count()), When(scope='booking', then=Booking.objects.filter( bookedticket__global_discount_code__code=F('code'), status__in=['i', 'c', 'g', 'r', 's'] ).count()), output_field=IntegerField() ) And it is not working. The error is Cannot resolve keyword 'code' into field. Can somebody explain how to fix it or why it is not working. Thanks -
passing django variables as parameters into href url
On my home page i want to have 3 links that will redirect the user to a page ('127.0.0.1:8000/person/<str:name>') which will display the name that they clicked. I would like to use a for loop to create links for these names as i plan to have much more than 3 names. I have tested with the two methods (for loop / manually writing out all of the links) but can't get the for loop to work. I thought these two methods below would produce the same result. <h2>does not work</h2> {% for person in people %} <a href="{% url 'person' '{{person}}' %}">{{person}}</a> {% endfor %} <h2>works</h2> <a href="{% url 'person' 'logan' %}">logan</a> <a href="{% url 'person' 'paul' %}">paul</a> <a href="{% url 'person' 'nicola' %}">nicola</a> What the urls look like in page source: views.py def home(request): return render(request, "APP/home.html", context={"people":['logan', 'paul', 'nicola']}) def person(request, name): return render(request, 'APP/person.html', context={"name":name}) urls.py urlpatterns = [ path('home/', views.home, name='home'), path('person/<str:name>/', views.person, name='person'), ] -
Django Haystack update index only for 1 model
I am currently trying out Django haystack to update data from PostgreSQL to a solr collection. So, I have defined 2 models in search_indexes.py. So, when I run the command python manage.py update_index it indexes the data from both the models defined in search_indexes.py to my solr collection. HOW DO I PERFORM update_index OPERATION ONLY FOR A SPECIFIC MODEL THAT I NEED? Currently, when I run the command, the following 2 models ran. Indexing 2 model1 Indexing 12 model2 search_indexes.py from haystack import indexes from .models import table1, table2 class model1(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( document=True, use_template=True, template_name="search/indexes/tenants/table1_text.txt" ) ats_id = indexes.CharField(model_attr='ats_id') ats_name = indexes.CharField(model_attr='ats_name') added_by = indexes.CharField(model_attr='added_by') added_on = indexes.DateTimeField(model_attr='added_on') def get_model(self): return table1 def index_queryset(self, using=None): return self.get_model().objects.all() class model2(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( document=True, use_template=True, template_name="search/indexes/tenants/table2_text.txt" template_id = indexes.CharField(model_attr='template_id') template_name = indexes.CharField(model_attr='template_name') aspect = indexes.CharField(model_attr='aspect') version = indexes.CharField(model_attr='version') added_by = indexes.CharField(model_attr='added_by') added_on = indexes.DateTimeField(model_attr='added_on') ats_id = indexes.CharField(model_attr='ats_id') def get_model(self): return table2 def index_queryset(self, using=None): return self.get_model().objects.all() Please suggest a workaround. -
How to post manytomany field value in Postman for API
I have a field which is ManyToMany. I would like to enter the value in POSTMAN for API post operation. But everytime It says: "This field is required." even though I provided the value. Serializer: class DaySerializer(serializers.ModelSerializer): class Meta: model = Day fields = '__all__' class TutorProfileSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault(), source='user.username') image_url = serializers.SerializerMethodField('get_image_url') tutor_availablility = DaySerializer(many=True) class Meta: model = TutorProfile fields = '__all__' -
Best practice for testing a django project
I have a django project with 3 apps. Now, I want to test my project. So I was in dilemma that what should be the best practice for testing a Django project with pytest? Which approach is preferable ? Approach 1 : └── app_name └── tests ├── __init__.py ├── test_forms.py ├── test_models.py └── test_views.py Approach 2 : └── app_name └── tests ├── __init__.py ├── unit_tests ├── __init__.py ├── test_views.py ├── test_models.py ├── test_forms.py ├── integration_tests ├── __init__.py ├── test_views.py ├── test_models.py ├── test_forms.py ├── functional_tests ├── __init__.py ├── test_views.py ├── test_models.py ├── test_forms.py Note : We are using pytest here. What I am expecting is which approach should be followed while testing a django project -
How to aggregate annotated related objects
How to calculate quantity_released from OrderedProduct? I cant just self.product_reservation.aggregate(total=Sum('quantity_released')) because you cant aggregate functions or even properties. I have tried extra and subqueries with annottation, but cant make it. class OrderProduct(models.Model): ... quantity_ordered = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) # TODO def quantity_released(self): return self.product_reservations.all() class ProductReservation(models.Model): ... order_product = models.ForeignKey("documents.OrderProduct", related_name='product_reservations' ,on_delete=models.CASCADE, blank=True, null=True) product_release = models.ManyToManyField("documents.ProductRelease", related_name='products_reservation', blank=True) def quantity_released(self): return self.product_release.all().aggregate(total=Sum('quantity'))['total'] class ProductRelease(models.Model): ... quantity = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) PS: If I have typed too inaccurate title then please edit it as I don't know how to phrase it better. Thank you. -
java-script programmatically created with Django seems to abbreviate itself
i have a js function written with django below function make_selected_func() { console.log("1111") clear_capcode() clear_derivs() clear_models() var make_selected = document.getElementById('makes').value console.log("@@@@@@") console.log(make_selected) var models_sel = document.getElementById('models') var unique_models = [] while (models_sel.options.length > 0) { models_sel.remove(0); } {% for car in cars %} if (! unique_models.includes('{{car.model}}')){ if ('{{car.make}}' == make_selected) { unique_models.push('{{car.model}}') } } etc.... when i go to my page the results i actually get in the html are... function make_selected_func() { console.log("1111") clear_capcode() clear_derivs() clear_models() var make_selected = document.getElementById('makes').value console.log("@@@@@@") console.log(make_selected) var models_sel = document.getElementById('models') var unique_models = [] while (models_sel.options.length > 0) { models_sel.remove(0); } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { unique_models.push('3 Series G20 Saloon') } else{ } } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { unique_models.push('3 Series G20 Saloon') } else{ } } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { unique_models.push('3 Series G20 Saloon') } else{ } } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { ……… ….. skipping thousands of lines ….. ……….. if ... == $0 below is the error i get. im guessing the js is so long it cant complete writing the function. it appears to … -
Django-wiki hit error when trying to access
enter image description here at the beginning, I executed Django run server after that I go to http://127.0.0.1:8000/ to try to access this wiki page are hitting error >> global flags not at the start of the expression at position 7 when i remove that line, it's works, but problems is if that line is removed, the content will gone I just started Django 1 week, please help to to overcome this error expect able to overcome this issue and launch the page successfully -
DRF social authentication
Im implementing drf social oauth2 and while accessing the URL - localhost:8000/auth/login/facebook/ I get 'drf' is not a registered namespace, No ReverseMatch error and when I change my namespace to social, I get 'social' is not a registered namespace. #URLPatterns urlpatterns = [ path("admin/", admin.site.urls), path('auth/', include('drf_social_oauth2.urls', namespace='social')), path('api/', include("users.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #Installed Apps INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # rest "rest_framework", "corsheaders", "rest_framework_simplejwt", # Oauth "oauth2_provider", "social_django", "drf_social_oauth2", # apps "accounts", "inventory", "cart", "orders", "users", ] -
Get and insert bit in MySQL by input:radio
I need to insert a bit value in my MySQL, but I don't understand how. I use Django so I get the input value by employing = request.POST.get('employing') and I send by QuerySet(employing=employing) <input class="form-check-input" type="radio" name="employing" id="employingTrue" value="01" checked required /> I've tried value="1", value="b'1'", value="true", but I always got : (1406, "Data too long for column 'employing' at row 1") -
Django add constraint for foreign key fields to match
In Django I have a model that links a tenant to a facility (house). The tenant and the facility needs to be in the same site (city) for this link to be valid. To enforce this I want to add a constraint that checks if the tenant's site and the facility's site matches. I have tried to add a CheckConstraint to the model, but this compiles to a migration that is always false. Model: class TenantInFacility(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.DO_NOTHING) facility = models.ForeignKey(Facility, on_delete=models.DO_NOTHING) percentage_used = models.DecimalField(default=100, max_digits=6, decimal_places=3) start = models.DateTimeField(default=datetime.datetime.fromtimestamp(0)) end = models.DateTimeField(default=None, blank=True, null=True) class Meta: verbose_name_plural = "tenants in facilities" constraints = [ models.CheckConstraint(check=models.Q(models.F("tenant__site") == models.F("facility__site")), name='tenant_facility_sites_match') ] def __str__(self): return self.tenant.site.name + ": " + self.tenant.name + " in " + self.facility.name Migration: operations = [ migrations.AddConstraint( model_name='tenantinfacility', constraint=models.CheckConstraint(check=models.Q(False), name='tenant_facility_sites_match'), ), ] Is there a way in Django to require a foreign key's foreign key to match another foreign key's foreign key. In diagram form: +----------+ | Tenant | +----------+ / \ / \ +--------------------+ +------+ | Tenant in Facility | | Site | +--------------------+ +------+ \ / \ / +----------+ | Facility | +----------+ -
Django no access to certain methods AbstractUser using UserManager
I am new to Django I am trying to get access to form.save() using form = self.form_class(request.POST) but I have been having to use methods like self.get_form_class() to access form.is_valid() and form.save() but cannot get method set_password() from user = form.save(commit=False) I am not sure what the problem is. Why cant I access user.set_password()? Even when I try to create a BaseUserManager self.model() does not give me a definition for user.set_password() or user.save() why is this? # views.py class RegistrationView(CreateView): template_name = "AskQuestions/customuser_form.html" form_class = RegistrationForm model = CustomUser success_url = "questions/login" def get(self, request, *args, **kwargs): form = self.get_form_class() form = form(initial=self.initial) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.get_form_class() form = form(request.POST) if (form.is_valid()): user = form.save(commit=False) # user.set_password() no definition user.set_password() messages.add_message(request, messages.SUCCESS, "Your account has been successfully created.") return redirect("AskQuestions:login") else: return render(request, self.template_name, {"form": form}) # models.py class CustomUser(AbstractUser): phone_number = models.CharField(max_length=20) REQUIRED_FIELDS = ["first_name", "last_name", "phone_number"] # forms.py class RegistrationForm(forms.ModelForm): confirm_password = forms.CharField(label="Confirm password:", max_length=200, widget=forms.PasswordInput(attrs={"class": "form-control"})) class Meta: model = CustomUser fields = ["first_name", "last_name", "username", "phone_number", "password",] labels = { "first_name": "Name:", "last_name": "Last name:", "username": "Username", "phone_number": "Phone number:", "password": "Password", "confirm_password": "Confirm password:", } widgets = { … -
uwsgi error can't get attribute 'MyModel' on <module'__main__'(built-in), but Django python manage.py runserver is OK
I put my Django project in docker, When I use python manage.py runserver, everything is OK. But using 'uwsgi --ini uwsgi.ini' start my project, it will be AttributeError: can't get attribute 'MyModel' on <module'__main__'(built-in) when I sent post request. There is my project structure db.sqlite uwsgi.ini │ manage.py │ mysql_test.py │ plt_score.py │ request_test.py │ test.log │ ├─Ai_Web │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ _init_.py │ │ │ ├─testapp │ │ admin.py │ │ apps.py │ │ bert_finetuned.py │ │ models.py │ │ random_forest.py │ │ tests.py │ │ urls.py │ │ views.py │ │ _init_.py My uwsgi file is [uwsgi] http = 0.0.0.0:8000 processes = 2 threads = 4 chdir = root/project/API_simple wsgi-file = Ai_Web/wsgi.py master = true manage.py have import the model class 'MyModel', so runserver is OK;But uwsgi will be wrong -
how to avoid overlapping requests when creating new objects?
def artist(request): print("START") if request.method == "GET": try: if artist_id: artist = Artist.objects.get(pk=artist_id) else: artist = Artist.objects.get(user=request.user) print("artist exists") except Artist.DoesNotExist: print("artist doesn't exist") artist = Artist.objects.get_or_create(user=request.user)[0] print("a new artist object has been created") return HttpResponse(status=200) Console: START artist doesn't exist START artist doesn't exist a new artist object has been created [15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0 a new artist object has been created [15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0 on the client side, there is a button on the screen that sends a request that returns to the user their artist page, or if they don't have one, it will be created for them. And suppose he double clicks the button, then two objects will be created. The user field in the Artist is not unique, we ignore the fact that we can solve the problem on the client side with javascript and we assume that the server is a bit slow, so it doesn't have time to process two requests in such a short time. The Artist model has a field that at the time of creation must be populated with some information based on their profile picture, i.e. i extract the dominant color from … -
Input give in the form not saving to the database
This is the model i created make a form. Two more fields are added in the form by using abstract user. models.py from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): phone=models.CharField(max_length=20) profile_pic=models.ImageField(upload_to="dp",null=True,blank=True) Registration form is inherited from UserCreationForm. forms.py from django.contrib.auth.forms import UserCreationForm from socialapp.models import MyUser from django import forms class RegistrationForm(UserCreationForm): widgets={ "password1":forms.PasswordInput(attrs={"class":"form-control"}), "password2":forms.PasswordInput(attrs={"class":"form-control"}) } class Meta: model=MyUser fields=["first_name","last_name", "username","email", "phone","profile_pic", "password1","password2"] widgets={ "first_name":forms.TextInput(attrs={"class":"form-control"}), "last_name":forms.TextInput(attrs={"class":"form-control"}), "username":forms.TextInput(attrs={"class":"form-control"}), "email":forms.TextInput(attrs={"class":"form-control"}), "phone":forms.TextInput(attrs={"class":"form-control"}), "profile_pic":forms.FileInput(attrs={"class":"form-control"}), } Here is the view to map to the template views.py from django.shortcuts import render from socialapp.forms import RegistrationForm from socialapp.models import MyUser from django.views.generic import CreateView from django.urls import reverse_lazy class SignupView(CreateView): model=MyUser form_class=RegistrationForm template_name="register.html" success_url=reverse_lazy("register") -
How to raise an exception in a serializer when the request.user belong to a different model?
I use a custom User model in my application and created two other models inherited from it, called Manager and Client, each one with specific fields. With DRF I'm trying to create two endpoints /manager and /client so that both types of user can get their profile data. However, when a manager GET /client his own data are returned because the view ClientDetailsView returns self.request.user, and this Manager object can be serialized with ClientSerializer because the two models are inherited from User. My question is it possible to check the model's class in the serializer so that ClientSerializer raise an exception when a manager visit the endpoint ? or more globally, what is the best way to address the issue ? models.py class User(AbstractBaseUser, PermissionsMixin): ... class Manager(User): ... class Client(User): ... view.py @permission_classes([IsManager]) class ManagerDetailsView(RetrieveAPIView): queryset = Manager.objects.all() serializer_class = ManagerSerializer def get_object(self): return self.request.user @permission_classes([IsManager | IsClient]) class ClientDetailsView(RetrieveAPIView): queryset = Client.objects.all() serializer_class = ClientSerializer def get_object(self): return self.request.user serializer.py class ManagerSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) fields = serializers.JSONField(write_only=True) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if …