Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to put my form in line orientation (horizontal). django forms
I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized MY HTML: <div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel" aria-labelledby="profile-tab"> <h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6> <div class="row mt-4"> <div class="col"> {{ form_funcionarioadicional.management_form }} {% for fa in form_funcionarioadicional %} <div class="faform row"> <div class="col"> {{fa}} </div> </div> {% endfor %} </div> </div> </div> currently it is like this, I wanted to leave it horizontal How can I fix this in html, or in forms.py? -
What is the difference between request.POST.get and request.POST
usually I use POST or GET requests except for GET.get paginations, but I don't understand the concept there are only two possibilities POST or GET . example even if there is the same effect I do not understand the difference between request.GET.get('page') and request.GET["page"] request.POST['rate'] and request.POST.get('rate') -
Reverse for 'admin_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_update/(?P<lesson_id>[^/]+)$']
I'm trying to pass arguments to edit table values. Would be grateful if anyone could breakdown the solution. views.py ` #@login_required(login_url='/admin_login/') def AdminManageRequests(request): lessons = Lesson.objects.all() return render(request,'admin/manage_requests.html',{'lessons':lessons}) def AdminUpdateRequests(request, lesson_id): lesson = Lesson.objects.get(pk=lesson_id) form = StudentRequestForm(request.POST or None, instance=lesson) context = { 'lesson':lesson, 'form':form } return render(request, 'admin/update_requests.html',context) ` urls.py ` path('admin_update/<lesson_id>', views.AdminUpdateRequests, name='admin_update'), ` manage_requests.html ` {% extends 'admin/admin_home_base.html' %} {% block admin_content %} <div> <h3 class="display-8" style="text-align:center"> Admin Lesson Request Management </h3> <hr class="my-4"> <p style="text-align:center"> You can view fulfilled and unfulfilled lesson requests. </p> <p class="lead" style="text-align:center"> {% include 'admin/partials/fulfilled_lessons.html' %} <br> {% include 'admin/partials/unfulfilled_lessons.html' %} </p> </div> {% endblock %} ` lessons_table_base.html ` <div class="card"> <div class="card-header"> <h5 class="card-title">{% block card_title %}{% endblock %}</h5> <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap"> <thead> <tr> <th>Lesson ID</th> <th>Lesson Name</th> <th>Student</th> <th>Teacher</th> <th>Interval (Days)</th> <th>Duration (Minutes)</th> <th></th> </tr> </thead> <tbody> {% for lesson in lessons %} {% block lessons_content %} {% endblock %} {% endfor %} </tbody> </table> </div> </div> </div> ` fulfilled_lessons.html ` {% extends 'admin/partials/lessons_table_base.html' %} {% load widget_tweaks %} {% block card_title %} Fulfilled Requests&nbsp;&nbsp;<i class="bi-send-check-fill"></i> {% endblock %} {% block lessons_content %} {% if not lesson.is_request %} <tr> <td>{{ lesson.lesson_id }}</td> <td>{{ lesson.lesson_name … -
Cannot import 'Questions'. Check that 'questions.apps.QuestionsConfig.name' is correct
hi everybody i have a message django.core.exceptions.ImproperlyConfigured: Cannot import 'Questions'. Check that 'questions.apps.QuestionsConfig.name' is correct. apps.py in application questions dirctory from django.apps import AppConfig class OrdersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'Questions' settings.py INSTALLED_APPS = [ 'questions.apps.QuestionsConfig', who can i solve this problem -
Specific model not visible for staff account in Django admin. Other models displaying as expected
I have several models in my project. All models are visible from the staff account if I add permissions for them, but one particular model is not displayed and I can't figure out why. This model is not displayed even if I add direct permissions to the user or add to a certain group with the necessary permissions, however, if I check the "Superuser status" box in the user settings, then this model appears. What could be the matter? -
TypeError at /admin/login/ 'NoneType' object is not iterable
TypeError at /admin/login/ 'NoneType' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.1.3 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable Exception Location: E:\mohammad\Dijongo\myprojects\Greany\lib\site-packages\debug_toolbar\panels\templates\panel.py, line 47, in _request_context_bind_template Raised during: django.contrib.admin.sites.login Python Executable: E:\mohammad\Dijongo\myprojects\Greany\Scripts\python.exe Python Version: 3.10.1 Python Path: ['E:\mohammad\Dijongo\myprojects\Greany\src', 'C:\Program Files\Python310\python310.zip', 'C:\Program Files\Python310\DLLs', 'C:\Program Files\Python310\lib', 'C:\Program Files\Python310', 'E:\mohammad\Dijongo\myprojects\Greany', 'E:\mohammad\Dijongo\myprojects\Greany\lib\site-packages'] Server time: Tue, 22 Nov 2022 17:41:41 +0000 project repo: https://github.com/pythone-developer/Ecomerce-greany project repo: https://github.com/pythone-developer/Ecomerce-greany -
pywhatkit how to close youtube after song ends?
is it possible to close the youtube tab after the song ends? I want to implement python code into raspberry so I can manually close the tab each time -
full link for media in django-rest
I wrote this view: api_view(["GET"]) def article_grid_list(request): # fetched data from database data = Articles.objects.all().order_by("-created_date")[:11] pinned_article = Articles.objects.get(pinned=True) # serialized data pinned_data = ArticlesSerializer(pinned_article) horizontal_data = ArticlesSerializer(data[:3], many=True) small_data = ArticlesSerializer(data[3:8], many=True) card_data = ArticlesSerializer(data[8:], many=True) final_data = { "pinned":pinned_data.data, "horizontal": horizontal_data.data, "small": small_data.data, "card": card_data.data } when I print result of this route, I'm getting 'cover' field like this : "cover": "/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg", but when I write this function like ModelViewSet I'm getting full url of cover field and I want to get full url in every reqeust modelViewSet Example : class ArticleGridList(viewsets.ModelViewSet): queryset = Articles.objects.all().order_by("-created_date") serializer_class = ArticlesSerializer I except like this : "cover": "http://localhost:8000/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg", my app urls.py file : router = routers.SimpleRouter() router.register('articles', ArticlesViewSet) urlpatterns = [ path("article-grid-list/", article_grid_list) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += router.urls``` -
My localhost:8000 just stopped to work. How can I get it back?
I am using ubuntu 20.04 I do not know if it matters, but I tried to see if the 8000 PORT was being used before I tried to run, and it was not. I was working on my Django project, running my localhost:8000 last night, but it stopped. Everything I have is a infinite loading. So, I returned today and I could not run my project. I do not know what happened. So, I started a new branch from the working code to check if it stopped because of me, but nothing changed. I've tried to restart and turn off my computer, I've erased my cache, I've tried in 4 different browsers (chrome, firefox, opera, brave), I've tried to re-run, and I've tried to use my local IP, but nothing happened. I am expecting to run again my project and I do not know if is related to my computer. -
Default value can be assigned for forms.DecimalField? Is it has to be already assigned in model declaration?
Wherever I try to give a default value to this field, which is supposed to be outside of my model gives error saying "default" or "attr" argument is unexpected. log_duration_minute = forms.DecimalField( help_text=_("log_duration_helper_text_minute"), default="0.00", ) The error message: __init__() got an unexpected keyword argument 'default' -
DRF Api-Key missing Attribute
I am trying to use the DRF Api Key mechanism for authentication, after following the guide here: https://florimondmanca.github.io/djangorestframework-api-key/guide/ I receive nothing but errors, does someone have a working example or see what i am doing wrong here? Global Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey' ] } Tested in a class view also class TestingApiKey(APIView): permission_classes = [IsAuthenticated | HasAPIKey] def post(self, request):``` 3 sample curl requests: Example 1 curl --location --request POST 'http://127.0.0.1:8000/api/test' \ --header 'Authorization: Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "Testing", "Password" : "Testing123" }' Example 2: curl --location --request POST 'http://127.0.0.1:8000/api/test' \ --header 'Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "Testing", "Password" : "Testing123" }' Example 3 curl --location --request POST 'http://127.0.0.1:8000/api/test' \ --header 'X-Api-Key: Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "Testing", "Password" : "Testing123" }' Each test I carry out returns a 500 server error with the response: 'HasAPIKey' object has no attribute 'authenticate' Anyone had this issue or understand why I would get this? -
What is the difference between response.COOKIES and request.session to handle cookies in DJango?
Disclaimer: I am a beginner, following the Django for everybody course on Coursera and I've looked around for explanations on Google but I can't wrap my head around this. I'm confused; request.COOKIES.get('foo', 0) and response.set_cookie('foo', 'bar') seems to be a long way round of getting and setting cookies when one can simply do: request.session.get('foo', 0) or request.session['foo'] = 'bar'. It seems like a long way around because with the response.set_cookie method I need to start a HttpResponse but with request.session. It seems that if i stick to just request.session i don't need to switch inbetween request.COOKIES and starting HttpResponses to use response.set_cookie to handle cookies. Can someone please explain what is the difference between these approaches to handling cookies and when you would/should use one or the other? -
Get sql executed by django in json format in django console without any \ and with single internal quates
I'm trying to get all the sql commands executed by django json format in django console. I'm getting some sql commands like this when I try to change them into json: "SELECT \"django_migrations\".\"id\", \"django_migrations\".\"app\", \"django_migrations\".\"name\", \"django_migrations\".\"applied\" FROM \"django_migrations\"" I want only external double quates and all the internal quates should be single without any \ in between. I tried using replace function and what not, but could'nt do it. I am expecting my sql command in like: "SELECT 'django_migrations'.'id', 'django_migrations'.'app', 'django_migrations'.'name', 'django_migrations'.'applied' FROM 'django_migrations'" -
Logging in Python Django: INFO not logging onto file
I have setup a logger in my Django project for 4 different cases: info messages, debug messages, error messages, ad gunicorn logging. Here is the content of my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "main_formatter": { "format": "{asctime}-{levelname}-{module}-{funcName}-{message}", "style": "{", }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "main_formatter", }, "dfile": { "class": "logging.FileHandler", "filename": "logs/debug.log", "formatter": "main_formatter", }, "file": { "class": "logging.FileHandler", "filename": "logs/info.log", "formatter": "main_formatter", }, "efile": { "class": "logging.FileHandler", "filename": "logs/error.log", "formatter": "main_formatter", }, "gfile": { "class": "logging.FileHandler", "filename": "logs/gunicorn.log", "formatter": "main_formatter", }, }, "loggers": { "main": { "handlers": ["dfile", "console"], "propagate": True, "level": "DEBUG", }, "main": { "handlers": ["file", "console"], "propagate": True, "level": "INFO", }, "main": { "handlers": ["efile", "console"], "propagate": True, "level": "ERROR", }, "gunicorn.access": { "handlers": ["gfile", "console"], "propagate": False, "level": "DEBUG", }, }, } And here is an example: import logging [...] logger = logging.getLogger(__name__) [...] logger.error(f"{request.user}: Erreur interne. Code [LI.001]") # THIS WORKS logger.info(f"Password Generated and Sent to {email}") # THIS DOESNT WORK In my logs/ folder, I have 4 files: info.log, error.log, debug.log and gunicorn.log The only output I see is in error.log and gunicorn.log, the other 2 files are always empty. -
Cannot import settings module in django
I am building a user interface with the help of Django's authentication infrastructure. However, when i try to import any module (such as the 'User' model or the 'authenticate' function) that needs access to the settings module, i get such error: c:/Users/Lorenzo/Desktop/progetto_mondodb_di_lorenzo_giaretta/Bit4All/BitEx/main.py Traceback (most recent call last): File "c:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\Bit4All\BitEx\main.py", line 4, in <module> from views import mainWindow File "c:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\Bit4All\BitEx\views.py", line 3, in <module> from models import Profile File "c:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\Bit4All\BitEx\models.py", line 2, in <module> from django.contrib.auth.models import User File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\conf\__init__.py", line 144, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File **"C:\Users\Lorenzo\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'Bit4All'** It looks like in the _init_.py file, inside django/conf, which currently resides inside my virtual environment, something wrong happens while trying to import the setting module (with importlib.import_module). The snippet of code responsible for the problem: class Settings: def __init__(self, settings_module): … -
How to view all Feature Flags in views.py
I have added feature flags in my django. I defined a switch in django admin panel. The default Switch model provides all the necessary functionality.To list all the switches using manage.py, we use this command: ./manage.py waffle_switch -l How to list all the switches in views.py? -
Automatic documentation of api roles and permissions (django rest framework)
I have a Django project with various REST APIs. The permission to access those APIs are defined throught rest_framework permission classes and django.contrib.auth.models Permission model. The documentation of those apis is automatically generated using drf_yasg library, i need to find a way to inlcude in the schema generated from drf-yasg the needed permission to access every api without the need to write id down manually. Anyone can give me an hint? -
Django save form with foreign key
I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database. models.py class User(AbstractUser): pass def __str__(self): return self.username class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, default="") first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Detail" def __str__(self): return self.first_name+ " "+self.last_name forms.py class Details(forms.ModelForm): class Meta: model = Detail fields = "__all__" widgets={ "user": forms.TextInput() } views.py def details(request): if request.method =="POST": form = Details(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.user = request.user detail.first_name = detail.first_name.lower() detail.last_name = detail.last_name.lower() detail.save() return redirect("admin:index") else: form = Details(initial={"user":request.user.username}) return render(request, "details.html", {"form":form}) -
Set default author to logged in user
I have already tried this, this and this to no avail. When submitting a comment I want to default the author field to be the currently logged in user. I am using class based views and haven't found many questions and answers besides trying to implement the above. views.py class CommentPost(SingleObjectMixin, FormView): model = Article form_class = CommentForm template_name = "article_detail.html" def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def form_valid(self, form): comment = form.save(commit=False) form.instance.author = self.request.user comment.article = self.object comment.save() return super().form_valid(form) def get_success_url(self): article = self.get_object() return reverse("article_detail", kwargs={"pk": article.pk}) models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) comment = models.CharField(max_length=140) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse("article_list") article_detail.html <!-- templates/article_detail.html --> {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <body class="d-flex h-100"> <div class="container"> <div class="col-8 mx-auto"> <h3 class="pb-4 mb-4 fst-italic border-bottom">Article detail</h3> <div class="article-entry"> <h2>{{object.title}}</h2> <p class="text-black-50 fst-italic">by {{object.author}} | {{object.date}}</p> <p>{{object.body}}</p> </div> {% if user.is_authenticated and user == article.author or user.is_superuser %} <p> <button class="btn"> <a class="text-decoration-none text-white" href="{% url 'article_edit' article.pk %}">edit</a> </button> <button class="btn"> <a class="text-decoration-none text-white" href="{% url 'article_delete' article.pk %}">delete</a> </button> </p> {% endif %} <br/> … -
Use a form in Django running locally to get folder/file path
Task: I am running a python Django web app locally. I would like to use an input form to get the path of a folder or file for use in further programming. Problem: I don't want to have users need to copy/paste the full path string; which is inconvenient, slow and clunky. The files are large and so I do not want to upload and store a copy. Is this possible given that the app is run on the same machine as the files? -
Django DRF Api Key Override Length expiry
I can see the following on the DRF page stating the key length can be overridden but being new at Django I really dont know how to use this? https://florimondmanca.github.io/djangorestframework-api-key/guide/#creating-and-managing-api-keys This package ships with a key generation algorithm based on Django's password hashing infrastructure (see also Security). The .key_generator attribute on BaseAPIKeyManager allows you to customize key generation. For example, you can customize the length of the prefix and secret key using: from rest_framework_api_key.models import BaseAPIKeyManager from rest_framework_api_key.crypto import KeyGenerator class OrganizationAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=8, secret_key_length=32) # Default values class OrganizationAPIKey(AbstractAPIKey): objects = OrganizationAPIKeyManager() # ... I dont understand where this would go, how it would link to the admin view, or what comes after # ... Any help would be most appreciated -
How to send Files to Another Site from a Django App?
I recently developed a django site where it is possible to upload some files. When these files are uploaded, I would like them to be send to another website. Is it possible to do this? Does it have anything to do with the FTP protocol? Thanks for your help! -
Django - Filter on ManyToManyField
I have two models: class Student(models.Model): first_name = models.CharField() last_name = models.CharField() class Group(models.Model): name = models.CharField() students = models.ManyToManyField(Student) Some data (first_name and last_name concatenated): Group #1 | Blak Coleman Group #1 | Miguel Scott Group #2 | Jordan Barnes Group #2 | Jordan Gustman Group #2 | Jekson Barnes Group #3 | Jordan Smith As you can see theres three students by name Jordan. So I need to return groups which in students queryset has only students by name Jordan. I tried this: groups = Group.objects.filter(students__first_name='Jordan') But group.first().students.all() contains all the students not only Jordan. Expected result: Group #2 | Jordan Barnes Group #2 | Jordan Gustman Group #3 | Jordan Smith How could I do this? -
ManyToMany field to same model without allowing the same object
I am using Django with a model that has a ManyToMany field to the same model. class Job(models.Model): name = models.CharField(_('Name'),max_length=80, blank=True, default="") related_jobs = models.ManyToManyField('self') this works fine. I can create Job objects and add jobs to related_jobs. The problem is that I can associate the same object to himself like this: job1 = Job.objects.create(name='Java') job2 = Job.objects.create(name='Python') job1.related_jobs.add(job2) job1.related_jobs.add(job1) #I don't want this to be possible Is there anyway to restrict this on the models? -
django-rest-framework days-of-week representation in model
I want to create a schedule model to schedule media on days of the week class Schedule(models.Model): name = models.CharField(max_length=100) start_date = models.DateTimeField() end_date = models.DateTimeField() week_days = ??? date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True) def __str__(self): return self.name but the problem is with week_days it can have multiple days how do I design the week_days field in the Django rest framework?