Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How works User model with one2one relationship? Django
Я часто вижу, что люди используют поле пользователя с подключением one2one к пользовательской модели. Но к какой модели мне следует обратиться сейчас, чтобы создать форму, войти в систему, выйти из системы, подтвердить доступ и все, что связано с пользователем? Как работает пользовательская модель в целом? class Profile(models.Model): GENDER_CHOICES = { ('M', 'Male'), ('F', 'Female') } user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(150)], null=True, blank=True) about_me = models.TextField(max_length=500, null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, blank=True) photo = models.ImageField(upload_to='profile_photos/', null=True, blank=True) I tried to find answer in google, but couldn't find decision -
Authorise apis of other application using django authentication system
I have a requirement to build an application say A. The application A is an authentication system, and i'm planning to build it in django using django oauth toolkit library. Then there will be some external applications say B and C, and they will be using the auth system A. How can I implement the authorisation for the applications A and B? Application B and C will be built on other languages like php or java. django oauth toolkit documentation describes an api for authentication where the client_id, client_secret, username and password is being sent to an api and the token is being generated. I need to use that token to authorise the APIs in application B and C Need your insight on this one. Thanks in advance. -
Django-reversion manually create version
Let's say I want to create a version of an object only in certain conditions, for example when 'status' field of object of class 'mymodel' is being changed to 'submitted'. How can I do this? class MyModel(AbstractModel): number = models.CharField(max_length=255) status = models.CharField(max_length=32) def save(self, *args, **kwargs) -> bool: if self.status == 'submitted': #TODO: create version. HOW?????? return super().save(*args, **kwargs) Also how can I suppress automatic version creation on every save? -
Debugging does not start [closed]
I am trying to start debugging django project with the command "manage.py runserver" and I get an error in the debug menu: the execution "error Python must be set". IDE - Pycharm, Python 3.11 -
Getting unauthorized_client response when creating social login with Microsoft using python package drf-msal-jwt
When trying to create social login with django and python package drf-msal-jwt using Azure I get the following error Error message on login I tried many ways. This is my apps manifest page is there anything i need to change. { "id": "1234567-1234-12l3-afe5-b01aa8cea588", "acceptMappedClaims": null, "accessTokenAcceptedVersion": 2, "addIns": [], "allowPublicClient": null, "appId": "de345rft-iok8-42hy-86bb-3124ahhgfts4d", "appRoles": [], "oauth2AllowUrlPathMatching": false, "createdDateTime": "2020-12-14T12:06:13Z", "description": null, "certification": null, "disabledByMicrosoftStatus": null, "groupMembershipClaims": null, "identifierUris": [], "informationalUrls": { "termsOfService": null, "support": null, "privacy": null, "marketing": null }, "keyCredentials": [], "knownClientApplications": [], "logoUrl": null, "logoutUrl": null, "name": "app", "notes": null, "oauth2AllowIdTokenImplicitFlow": false, "oauth2AllowImplicitFlow": false, "oauth2Permissions": [], "oauth2RequirePostResponse": false, "optionalClaims": null, "orgRestrictions": [], "parentalControlSettings": { "countriesBlockedForMinors": [], "legalAgeGroupRule": "Allow" }, "passwordCredentials": [ { "customKeyIdentifier": null, "endDate": "2024-12-14T12:09:51.944Z", "keyId": "e1fe6rrr-ba31-4d61-89e7-12345iy5697j", "startDate": "2022-12-14T12:09:51.944Z", "value": null, "createdOn": "2022-12-14T12:10:32.7193321Z", "hint": "T9w", "displayName": "secret" } ], "preAuthorizedApplications": [], "publisherDomain": "testemail@outlook.com", "replyUrlsWithType": [ { "url": "http://localhost:8000/", "type": "Web" }, { "url": "http://localhost:5000/getAToken", "type": "Web" } ], "requiredResourceAccess": [ { "resourceAppId": "00000003-0000-0000-c000-000000000000", "resourceAccess": [ { "id": "e1fe6dd8-ba31-4d61-89e7-88639iy5697j", "type": "Scope" } ] } ], "samlMetadataUrl": null, "signInUrl": null, "signInAudience": "AzureADandPersonalMicrosoftAccount", "tags": [], "tokenEncryptionKeyId": null } What i needed was when a new user visits our website we will be get a registration page with a button with … -
Change default datagbase in django constance
I have a django app with multiple databases and i have begun to use django-constance to use 'live' settings in mi project. I have seen in documentation, it seems possible change the default database to save the settings models. But it's always save the model in default. Is it really possible? If you have multiple databases you can set what databases will be used with CONSTANCE_DBS CONSTANCE_DBS = “default” DATABASES = {"default": {}, "config": {}} CONSTANCE_DBS = "config" -
Why is adding 'form-control' bootstrap class in Django form not working?
I am creating a login page without an inbuilt model form. I am using FormAPI of Django and followed all the steps to add a class attribute to the input fields of my form. But it still looks like a basic form without bootstrap. forms.py: #Login Form class LoginForm(forms.Form): username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) Base template file to be inherited: <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static 'account/images/logo.ico' type='image/x-icon' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'account/css/style.css' %}"> <title>{% block title %}{% endblock title %}</title> </head> <body class="forbody"> <div class="container trp" style="margin-top: 2%; display: inline-block;"> <div class="row"> <div class="col-md-4"> <img src="{% static 'account/images/Logo.png' %}" alt="Logo" style="height: 60%; width: auto;"> </div> </div> </div> <div class="container" style="width: 40%; margin-top: 10%;"> <div class="container" style="width: auto; margin-top: 8%;"> <div class="container" style="background-color: #696969; height: auto; width: auto; margin-top: 8%;"> <div class="row"> <div class="col-lg-6" style="padding-top: 25px; padding-bottom: 20px; padding-left: 20px;"> <form action="" method="post" novalidate> {% csrf_token %} {% block formcontent %} {% endblock formcontent %} <div class="row text-center"> <div class="col-lg-12"> {% block loginbtn %} {% endblock loginbtn %} </div> </div> <div class="row text-center"> <div class="col-lg-12" style="padding-top: 10px; padding-bottom: 12px;"> {% block outerlink %} … -
how can i use django filter with multiple value select
I want to filter my data based on city , how can i filter my data if the user choose more than one city using django filter class games(generics.ListAPIView): queryset = Game.objects.filter(start_date__gte=datetime.today()) serializer_class=GameSerializers filter_backends = [DjangoFilterBackend,filters.OrderingFilter] filterset_fields = ['id','city','level'] game model class Game(models.Model): city = models.CharField(max_length=255) gender = models.ForeignKey(Gender,on_delete=models.CASCADE) level = models.ForeignKey(Level,on_delete=models.CASCADE) host = models.ForeignKey(Host,on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() fees = models.IntegerField() indoor = models.BooleanField() capacity = models.IntegerField() age_from = models.IntegerField() age_to = models.IntegerField() description = models.CharField(max_length=255) earned_points = models.IntegerField() created_at = models.DateTimeField(default=django.utils.timezone.now) image = models.ImageField(upload_to="GameImage",null=True) history = HistoricalRecords() -
Django + Celery task never done
I'm trying to run the example app Django+Celery from official celery repository: https://github.com/celery/celery/tree/master/examples/django I cloned the repo, ran RabbitMQ in my docker container: docker run -d --hostname localhost -p 15672:15672 --name rabbit-test rabbitmq:3 ran celery worker like this: celery -A proj worker -l INFO When I try to execute a task: python ./manage.py shell >>> from demoapp.tasks import add, mul, xsum >>> res = add.delay(2,3) >>> res.ready() False I always get res.ready() is False. The output from worker notify that task is recieved: [2022-12-14 14:43:20,283: INFO/MainProcess] Task demoapp.tasks.add[29743cee-744b-4fa6-ba68-36d17e4ac806] received but it's never done. What might be wrong? How to catch the problem? -
Pythonanywhere - Error code: Unhandled Exception Django
it's my leaveitcafe_pythonanywhere_com_wsgi.py # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/leaveitcafe/Leave-it-Cafe/Leave_it_cafe' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Leave_it_cafe.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() enter image description here how to solve this error -
How to make a copy of Django FileField without reapplying upload_to directory path?
My Django Model contains the following: def photo_directory_path(instance, filename): return 'photos/{0}/foo-{1}'.format(instance.id, filename) photo = models.FileField(null=True, blank=True, editable=True, upload_to=photo_directory_path, max_length=500) Let's say I have an instance of this Model as oldModel, and I would to create a new instance and use the same photo. I don't want to store the photo again but have a reference to the same file: newModel = Model() newModel.photo = oldModel.photo newModel.save() However, this does not work as photo_directory_path will be applied again to the file name. How can I copy the FileField as "raw"? -
I have a datefield field in mysql and how do I know if it is null
using djangoenter image description here I want to create an if else block and make this data in mysql so that if it is empty, the button will not appear, but if it is not empty button will appear, I tried this, but it counts as full. -
How do I filter query objects by time range in Django
I've got a field in one model like: class Sample(models.Model): created_at = models.DateTimeField(auto_now_add=True, blank=True) this is what it's looks like if saved: 2022-12-13 13:00:29.84166+08 2022-12-13 14:00:29.84166+08 2022-12-13 15:00:29.84166+08 Is it possible to filter that by range of time? maybe similar to this? Sample.objects.filter(created_at __range=["13:00", "15:00"]) -
Django select2 with autocomplete_fields to have a dynamic default value
I have a Product model and a HeadFlowDataset model. These two models are connected with a foreinkey relationship, in which one product can have many headflowdataset pairs. Their model codes are as below: class Product(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) ... # other fields in the model, not exactly related to this problem class HeadFlowDataSet(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) product = models.ForeignKey( Product, on_delete=models.CASCADE, ) head = models.FloatField() flow = models.FloatField() def __str__(self): return self.product.pump_name Every product can have up to 10-15 head-flow sets. And currently I'm using Django admin panel to populate my product database. On the other hand, there may be up to 1000 products in total. So when the admin is trying to add head-flow datasets, the process was a bit challenging to find the product name from the select menu that Django admin provides. So I used Django autocomplete_fields in the ModelAdmin as below so that the admin can at least search for the product name: class HeadFlowDatasetAdmin(admin.ModelAdmin): list_display = ( "product", "head", "flow", ) fields = ( "product", "head", "flow", ) autocomplete_fields = ["product"] def get_ordering(self, request): return [Lower("product__pump_name"), "head"] But this approach too is a bit frustrating to search … -
How to transmit Django variables to a Js file
As you can see in the code below, I have imported a <script type="text/javascript" src="{% static 'js/posts_lazy_loading.js' %}"></script> to my Index.html. But there are Django variables in that JS file. like: {{ sizes }} and {{ urlsPosts }}, they go from Views.py to the Index.html. Unfortunately Django doesn't see these variables in the JS file if I keep the JS as a separate file. If I copy paste the JS right to the HTML without separating - everything works well. How can I include these Django variables into the separate Js file? Index.html: <html> {% load static %} {% include 'head.html' %} <body> <header> </header> </body> <footer> <script type="text/javascript" src="{% static 'js/posts_lazy_loading.js' %}"></script> </footer> </html> Views.py: def index(request): posts = Post.objects.all() sizes = '' urlsPosts = '' for i in range(0, len(posts)): if i == len(posts): sizes = sizes + str(posts[i].thumbnail.width) + 'x' sizes = sizes + str(posts[i].thumbnail.height) urlsPosts = urlsPosts + posts[i].thumbnail.url else: sizes = sizes + str(posts[i].thumbnail.width) + 'x' sizes = sizes + str(posts[i].thumbnail.height) + ' ' urlsPosts = urlsPosts + posts[i].thumbnail.url + ' ' return render(request,'index.html',{'posts':posts, 'sizes':sizes, 'urlsPosts':urlsPosts) posts_lazy_loading.js: var images = document.getElementsByClassName('cover_main_page'), posts = document.getElementsByClassName('post'), descriptions = document.getElementsByClassName('description'), description_height = descriptions[0].clientHeight; post_content = document.getElementsByClassName('post_content'), loading = … -
Multi-Step form with every step depends on the data filled in previous step / first step in Django
I am struck on this for hours, I have a multi-step form, the structure of the form is like <form> <fieldset> <input>source airport</input> <input>destination airport</input> </fieldset> <fieldset> <!--Here I want to show airlines according to the data filled in the 1st fieldset, from the DATABASE--> </fieldset> <fieldset> <!--something here, which will depend on 1st fieldset filled data--> </fieldset> <fieldset> <!--something here, which will depend on 1st fieldset filled data--> </fieldset> </form> what I have done, Used JS to get the fields in the first fieldset by id and then send the data in Django view using AJAX and I was able to save data in DB. But, now the problem is that when next button is clicked to move to next fieldset, then page doesn't send the GET request And 2nd fieldset doesnt get populated according to the data filled in the 1st fieldset I am looking to get any help I can get and get this thing done. I am implementing this in Django. I am very much okay to provide more details regarding this to get help. -
Calling MPTTModel model that is child
I have 2 models, Lucrare and Deviz. Deviz is a MPTTModel and has ForeignKey reference to Lucrare. Deviz models will have this form: Chapter 1 -Subchapter 1 --SubSubchapter 1 ---Article 1 ---Article 2 ---Article 3 Chapter 2 -Subsubchapter1 --Article 1 --Article 2 And only the Chapter will have the foreignkey reference to Lucrare. models.py: class Lucrare(models.Model): name = models.CharField(default='',max_length=100,verbose_name="Name") class Deviz(MPTTModel): lucrare = models.ForeignKey(Lucrare, on_delete=models.CASCADE,default='',null=True) parent = TreeForeignKey('self', on_delete=models.CASCADE,null=True,blank=True) Name = models.TextField(default='',verbose_name="Name") Created a class based view for Lucrare views.py: class LucrareDetail(LoginRequiredMixin, DetailView): template_name = "proiecte/lucrare_detail.html" context_object_name = "lucrari" model = Lucrare def get_queryset(self, **kwargs): context = super().get_queryset(**kwargs) return context I do not understand how to use this part in the template so that I create a table with Deviz data referenced to my Lucrare model: {% load mptt_tags %} <ul> {% recursetree genres %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
why is the pip install django Why does it take so long? ''Installing collected packages" step?
I'm trying to pip install django but installation takes a long time "Installing collected packages" step? like 40 min $ python -m pip install django Collecting django Using cached Django-4.1.4-py3-none-any.whl (8.1 MB) Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB) Installing collected packages: sqlparse, asgiref, django -
How to execute django query from string and get output
I want to run a django query from a string and put the output into a variable i tried using exec('model.objects.all()') but i can't assign the output to a variable, i also tried using subprocess.run([sys.executable, "-c", 'model.objects.all()'], capture_output=True, text=True) but subrocess doesn't find the model -
how to reverse page after deleting any data in django?
i wanted to redirect my page to index after deleting row so i use ` return HttpResponseRedirect(reverse('index')) to reverse . i wanted thishttp://127.0.0.1:8000/indexbut it is showinghttp://127.0.0.1:8000/index/index` what is the proble please help me. this is my view.py ` def index(request): return render(request, "card/index.html") def delete(request, id): dishes = dish.objects.get(id=id) dishes.delete() return HttpResponseRedirect(reverse('index')) this is urls.py path('index', views.index, name="index"), path('check', views.check, name="check"), path('delete/<int:id>', views.delete, name='delete'), ` -
counter with date information from django with javascript
I have a project in django, I have a field called delivery_time in the database, this is a datetimefield. I want to take this value and use it in javascript to make a counter. The date I'm talking about comes as text in html, I can use it too. I don't know how to use a text written in html.  my code ss -
Ajax call for form
What is django-ajax-selects and how to use it? an example. I want to create a filter app that show filtered data as soon as possible when selected option from form selector. -
Django - Failed to load resource: the server responded with a status of 404 (Not Found)
I'm trying to deploy a Django app that works locally, but doesn't on my website. The Django index.html (template) is shown but the errors below are shown and no css / js is loaded. Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/js/main Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/css/style.css Lines I think are relevant in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'src.pages' ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] How I include the files in index.html template {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> </head> <body> <script src="{% static 'js/main.js' %}"></script> </body> </html> App structure is as follows web_app/ ├── src/ │ ├── config/ │ │ └── settings.py │ ├── pages/ │ │ ├── static/ │ │ │ ├── css/ │ │ │ │ └── style.css │ │ │ ├── js/ │ │ │ │ └── main.js │ │ │ └── fonts/ │ │ ├── templates/ │ │ │ └── pages/ │ │ │ └── index.html │ │ ├── urls.py │ … -
Django template == condition on string doesn't work
I want to display in an email template some conditional informations but even if the {{ error }} confirms the value of my error is list index out of range , the condition is not applied and else is taken in account. I send to my (email) template this: views.py try: [...] except Exception as e: error_product_import_alert( {'order_increment_id': order_increment_id, 'product': item['sku'], 'error': e, 'request': request}) error_product_import_alert() def error_product_import_alert(context): product = context['product'] order_id = context['order_increment_id'] error = context['error'] sujet = f' Anomalie : Import SKU {product} ({order_id}) impossible ({error})!' contenu = render_to_string('gsm2/alerts/product_import_ko.html', context) [...] email template <p>--{{ error }}--</p> {% if error == 'list index out of range' %} <p><strong>Le produit est introuvable dans la base.</strong></p> {% else %} <p><strong>Erreur inconnue : veuillez contacter l'administrateur.</strong></p> {% endif %} Maybe my error is so big that I even can't see it. Is there one ? -
How do I visualize NetCDF files in Python using the Django framework?
How to visualize the netCDF files in python using Django Framework? I tried using Folium map, but it doesn't support JavaScript. JavaScript is required to interact with map, like on-click function, pagination, etc. While using JavaScript, I need to go with conversion of netCDF File to GEOJSON file. But, it takes lots of storage space. Is there any alternate method to proceed with my requirement?