Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to handle namespace API versioning with DRF-YASG
In my project we want to have multiple versions of same api so as to support backward compatibility. Right now we are using drf-yasg's swagger url at /api/doc/ While our apis are /api/vehicle/$ /api/warehouse/ And then each of the app vehicle and ware house have their own endpoints.. Now we want to do versioning as /api/v1/doc /api/v2/doc /api/v1/vehicle /api/v2/vehicle /api/v1/warehouse Goal is that /v1/doc should show v1 of both vehicle and ware house while/v2/doc should show only v2 of vehicle since only vehicle app has some apis with v2.... How to achieve this I tried adding default version v1 initially in drf settings. But that resulted in no listing being shown in swagger view -
Order queryset by the number of foreign key instances in a Django field
I am trying to return the objects relating to a through table which counts the number of reactions on a blog post. I have an Article model, Sentiment model and Reactions model. The sentiment is simply a 1 or 2, 1 representing like and 2 for dislike. On the frontend users can react to an article and their reactions are stored in a Reactions table. Reactions model class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_id', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) I'd like to find the 2 most liked articles so I have written a view to handle the GET request views.py class MostPopularView(generics.RetrieveAPIView): queryset = Reaction.objects.annotate(num_likes = Count('sentiment_id')).order_by('num_likes') serializer_class = MostPopularSerializer and a serializer to transform the data serializers.py class MostPopularSerializer(serializers.Serializer): class Meta: fields = ( 'id', 'title', ) model = Article As the code stands now, I'm getting a response <QuerySet [<Reaction: d745e09b-5685-4592-ab43-766f47c73bef San Francisco Bay 1>, <Reaction: d745e09b-5685-4592-ab43-766f47c73bef The Golden Gate Bridge 1>, <Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 San Francisco Bay 1>, <Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 The Golden Gate Bridge 2>]> Showing San Francisco Bay has 2 likes and The Golden Gate Bridge has 1 like and 1 dislike. I've tried multiple methods to get the correct response including … -
Safest way to send base64 encoded Image in a post api request
I have a post request where I am sending a base64 encoded image. I wanted to know is there any encryption method that I can use to encrypt this base64 string. In frontend I am using Javascript and for backend Django is being used. So far I have not been able to find any resource or anything that can point me right direction. Any help will be appreciated. -
Django form is not saving when I have action = to desired url
If I use action="" in my django form, the form works properly but sends the user to the wrong page. I want the user to go back to the macro/ page upon form submission, but when I add that url to action (like action="{% url 'macro' %}", it goes to the page but the form doesn't save. Any suggestion on how to handle this? Code below: (Option 1) macro_update.html -> the form here works properly, but takes the user to the wrong page <ul> <form action="" method="post"> {% csrf_token %} {{ macro_form.as_ul }} <input type="submit" value="Submit"> </form> </ul> (Option 2) macro_update.html -> the user is redirected to the right page upon submission, but the form data doesn't update/save <ul> <form action="{% url 'macro' %}" method="post"> {% csrf_token %} {{ macro_form.as_ul }} <input type="submit" value="Submit"> </form> </ul> views.py @login_required(login_url='login') def macroUpdate(request): if request.method == "POST": macro_form = MacroForm(request.POST, instance=request.user.profile) if macro_form.is_valid(): macro_form.save() messages.success(request,('Your macros were successfully updated!')) else: messages.error(request,('Unable to complete request')) return redirect("profile") macro_form = MacroForm(instance=request.user.profile) context = {"user":request.user, "macro_form":macro_form } return render(request, 'macro_update.html', context) urls.py urlpatterns = [ path('', views.loginPage, name='login'), path('register/', views.registerPage, name='register'), path('profile/', views.profilePage, name='profile'), path('profile/update/', views.profileUpdate, name='profile-update'), path('logout/', views.logoutUser, name='logout-user'), path('macro/', views.macroPage, name='macro'), path('macro/update/', views.macroUpdate, name='macro-update'), … -
populating form with data from session; django
I'm wondering how to fill my form with data that i have stored in my session. my model: models.py class Order(models.Model): order_by = ForeignKey(User, on_delete=DO_NOTHING) order_status = ForeignKey(OrderStatus, on_delete=DO_NOTHING) created = DateTimeField(default=datetime.now) address_street = CharField(max_length=256) address_postal_code = CharField(max_length=18) address_city = CharField(max_length=128) shipping = ForeignKey(ShippingMethod, on_delete=DO_NOTHING) payment = DecimalField(max_digits=12, decimal_places=2, null=False) payment_method = ForeignKey(PaymentMethod, on_delete=DO_NOTHING) def __str__(self): return self.id I have a view that stores my choices in 'cart' class AddProductToCartView(View): def get(self, request, pk): cart = request.session.get("cart") if cart: for item in cart: if item["id"] == pk: item["quantity"] += 1 break else: cart.append({"id": pk, "quantity": 1}) request.session["cart"] = cart else: request.session["cart"] = [{"id": pk, "quantity": 1}] return redirect("store:cart_view") class CartView(View): def get(self, request): in_cart = [] overall_price = 0 overall_tax = 0 if "cart" in request.session: overall_price = 0 for item in request.session["cart"]: product = Product.objects.select_related("category").get(id=item["id"]) total_price = product.price * item["quantity"] tax = (total_price * product.tax) in_cart.append({ "product": product, "quantity": item["quantity"], "total_price": total_price, "tax": tax }) overall_price += total_price overall_tax += tax return render( request, template_name="cart/cart_view.html", context={ "products": in_cart if len(in_cart) > 0 else None, "overall_price": overall_price, "overall_tax": overall_tax } ) and I want to populate my form with data (some of it not everything is in my 'cart' so … -
How do I solve this input problem? (DJANGO)
I'm trying to do an autocomplete with django. In the HTML, I'm using a <select> tag to get the IDs and connect to the API for the data, anyway, that's not the focus. The truth is that this part of the select doesn't work inside the modal it should, just outside. Could anyone help me with suggestions? I tried to put it outside the modal and it worked, but I need it to work inside the modal. The code below shows where it should work. <div class="row"> <div class="col"> <strong style="font-weight: 500;" class="d-block mb-1">Pessoas a serem adicionadas</strong> <select class='form-control' id="id_pessoas" name="pessoas" required="required" data-ajax--cache="true" data-ajax--delay="250" data-ajax--type="GET" data-ajax--url='{% url "api-list-pessoa" %}' data-theme="bootstrap4" data-allow-clear="true" data-maximum-selection-length="7" data-minimum-input-length="3" data-language="pt-BR" data-placeholder="Selecione uma pessoa"> </select> </div> -
How to import custom modules in Django
I have a module created with the name metrics.py . I want to use this module in my views.py file.The command i used to import is "import metrics" in views.py file. both views.py and metrics.py are in the same folder. i am getting this error "ModuleNotFoundError: No module named 'metrics'" How to use the custom module i created in views.py -
Django JSONField is not able to encode smileys properly
I plan to store a dict in a Django JSONField. One key of this dict is a comment a user can enter. And users like a lot to add some smileys in their comments... The problem is that some smileys, are saved properly in DB. The database is MySQL 8.0.31, Django version is 4.0.8 : JSONField is supported for this environment as reported in documentation. The database default encoding is utf8mb4 and collation utf8mb4_general_ci. With that model : class TestJSONField(models.Model): data = models.JSONField() Here is the test case : comment=b'smiley : \xf0\x9f\x98\x8a'.decode() t=TestJSONField(pk=1, data={'comment':comment}) t.save() r=TestJSONField.objects.get(pk=1) print('BEFORE :', comment) print('AFTER :', r.data['comment'], '(str)') print('AFTER :', r.data['comment'].encode(), '(utf-8 encoded bytes)') which gives : BEFORE : smiley : 😊 AFTER : smiley : ? (str) AFTER : b'smiley : ?' (utf-8 encoded bytes) As you can see the smiley is not stored correctly. This smiley is 4 bytes encoded, this may be the source of the problem because with 2-bytes encoded chars I do not have any problem. With a TextField and using json dumps()/loads() I do not have any problem. Do you have an idea how to have 4 bytes encoded smileys to be saved in a JSONField ? -
logging with cookiecutter-django inside docker not displaying on console
I can't get logging to display. Am I doing something wrong? Other logging that is generated by cookiecutter-django works fine, but when I try to implement logging myself for debugging I am not able to get any display settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "verbose", }, "file": { "level": "INFO", "class": "logging.FileHandler", "formatter": "verbose", "filename": "debug.log", }, }, "root": {"level": "INFO", "handlers": ["console", "file"]}, } view.py: class run(viewsets.ModelViewSet): serializer_class = RunSerializer def list(self, request): return Response("Get") def create(self, request): logger = logging.getLogger("root") logger.info(request.data) logger.info(request.POST) return Response({200}) this logging does not display to console