Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Create Form in the backend? [closed]
I work on Django app, I need to create form which contain fields such as f_name, l_name, ..., etc. and send this form to user through email. there is way to create this form in backend? or which best practice to do that? I tried to create this form in the backend, but I'm not sure if that best practice or not. -
How the login, authentication, tokens works? if a user login to any application and till he logout how the requests know that the user is logged in
I'm just trying to make a small ecommerce web application by using Django, Django Rest Framework, I completed registration and login views(not used Django inbuilt authentication) just saving the users information in database and validating those details when the user login, now I'm confused that how actually login works, how the user stay connected till he log out, how the server knows that the user is still logged in, how each request knows that the user is already logged in, Once I tried login by using Django OAuth token, also simple JWT tokens, but when I used to login along with the username and password I also send the token from the postman, but users doesn't login through postman in real world, then how the tokens are handled, who passes the tokens along with the parameters while login, how tokens are passed along with the credentials in real projects, how all these handled in real projects, also what happens when user clicks on logout, what will happen in the backend when user clicks on logout, can anyone please clear this question Thanks. Please help me understanding of this concept -
How I can use one js code of a django template for different content
I am working on a web application using Django I have faced one problem in that and that's I wrote one html template in Django and in that template I also has been written the code of js for that template. I want to use that js code for all the different kinds of content that is represented using that template in the front of the user.but that js code is not working for all kinds of content similarly. Problem in brief I am making a commerical web application for a Project like amazon.in and flipkart.com and I have writen a template for a product view page for all kinds of Product that is shown using that template. I has been made a button in that product view page template. Button is Add to Cart and I have written JavaScript code in that template for add to Cart button to store the product in the cart when the user click the button. I made my cart using LocalStorage and i will store the products in it. but the problem is when I initialzed my site and click on the product and goes to the product view page and click to … -
How to add a model instance (not from db) to queryset
Let's say I have a model called Schools. And also I have a Schools instance that I don't want to store in my database. temp_school = Schools(school_id='temp_1') Also I have all schools schools = Schools.objects.all() Now, how can I add my temp_school to the schools, so that I can use it as my new queryset in my view? -
How to add an extra field in auth user model in django admin?
I want to customize my existing auth user model. I need the command or code for executing the solution? -
in vuejs styling ag-grid's cell data
what am I doing is combine some key value pairs and bold the value in that pair and put it in ag-grid rowData , my problem is bold() method adds the tag to that value it is not getting bold -
Saving a toogle switch value in Django
Hi I am just trying to save a toggle switch value onclick to save to a Boolean field in Django home.html <style> .home-container{ display:grid; grid-template-columns: 1fr 4fr; } .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } </style> <div> <label class="switch"> ** <input type="checkbox" checked>** <span class="slider round"></span> </label> </div> models.py is_active = models.BooleanField(default=False) urls.py path('engine/', views.engine, name="engine"), I tried several suggestions on the web but could not make it work as I am new to development. I know I need to use javascript. Please help write my views.py and javascript in home.html. -
How to search whether a value is present in a list of values in Django
In my model a list of values is stored. Now a user can enter a list of values and if any of the values is present in the table then that record should be fetched. For e.g. a user enters [3, 63, 2, 5]. Now suppose the list that is present in the table has values [65, 5, 8, 48]. Since the input list which is [3, 63, 2, 5] has got a common value which is 5 in this case I should get this record. This is the column which is present in my model. The model name is Room. room_number = models.CharField(validators=[validate_comma_separated_integer_list], max_length=4000) I don't understand how I can do this. Can someone please help me with this? I can get an individual value and run a for loop for every value present in the input list. but I don't understand how I can search whether a given value is present in the list. -
How i can split a Email in Django
Good morning I've been sitting for 5 hours on what should be a simple problem. I would be grateful if you could end my suffering. It is about a dashboard page. I want the user to be greeted with his name (Hello, ....) after he has registered with his email address. When registering, the email address is always the same, name.example@hotmail.de. I want to split the email address and display only the name, but I can only manage to display the whole email address. view.py @login_required(login_url='login') def Example_dashboard(request): form = MembersForm() current_user = request.user #current_user.split is not working! context = {'form': form, "cunrrent_user": current_user} return render(request, 'example_dashboard.html', context) html <p>Welcome, {{ current_user}} </p> <form action='' method='POST'> {%csrf_token%} {{ form }} models.py class Members(models.Model): email = models.CharField(max_length=200, null=True) passwort = models.CharField(max_length=200, null=True) forms.py class MembersForm(ModelForm): class Meta: model = Members fields = ["studiengang", "kategorien"] -
Passing value from a form to get method in django
I want to pass the value in the comment text area when the a tag is clicked.Is there any other methods to pass both the comment and rating into the get method.I saw some similar questions but the answers where suggesting to use hidden input field to pass the value.But in my case i want the rating number in the clicked tag too.so i won't be able to use the hidden input method. <form method='post'> <div class="container-fluid py-4"> <div class="row"> <div class="col-lg-6 mx-auto mb-lg-0 mb-4"> <div class="card"> <div class="card-body p-4"> <h4 class="font-weight-bolder">Review</h4><br> <div > <textarea class="textarea p-3 w-100" placeholder="Write a review" cols = "40" rows="5"></textarea> {{form.comment}} </div> </div> </div> </div> </div> <div class="container-fluid py-4"> <div class="row"> <div class="col-lg-6 mx-auto mb-lg-0 mb-4"> <div class="card"> <div class="card-body p-4"> <h4 class="font-weight-bolder">Rating</h4><br> <div class="rating rating2"> <a href="{% url 'ratings' 5 id %}" title="Give 5 stars" data-value="5" type="submit">★</a> <a href="{% url 'ratings' 4 id %}" title="Give 4 stars" data-value="4" type="submit">★</a> <a href="{% url 'ratings' 3 id %}" title="Give 3 stars" data-value="3" type="submit">★</a> <a href="{% url 'ratings' 2 id %}" title="Give 2 stars" data-value="2" type="submit">★</a> <a href="{% url 'ratings' 1 id %}" title="Give 1 star" data-value="1" type="submit">★ </a> </div> </div> </div> </div> </div> </div> </form> -
Django models with key and multiple value choices
im trying to work my way into making an api oriented webapp with Django and i wanted to create a model where i can choose a day and a time for that day. So my first thought was to make a model with an atttibute that can stored set day with a set time, this last one being of multiple choice, like a dictionary or something. My motive is to save those values as attributes in my DB but i dont really know if thats possible! Thx a lot beforehand. Something like this came to my mind: class Reservation(models.Model): reservation = ({'monday':[10,11,12,13,14,15,16,17], 'tusday':[10,11,12,13,14,15,16,17], 'friday':[10,11,12,13,14,15,16,17]}) -
DRF Swagger - Endpoint parameter doesn't match the Serializer
So I'm trying to create at REST API using DRF and Swagger for API Documentation, But I notice that Swagger UI Parameter doesn't match the given Serializer. MailSerializer.py ` from main.BusinessLayer.Model.Mails import Mails from rest_framework import serializers class MailSerializer(serializers.Serializer): class Meta: model = Mails fields = '__all__' # Mail Properties Subject = serializers.CharField(max_length = 30, allow_blank = False) Sender = serializers.CharField(max_length = 30, allow_blank = False) Recipients = serializers.CharField(allow_blank = False) ReplyToAddress = serializers.CharField(max_length = 30) Importance = serializers.CharField(max_length = 30, allow_blank = False) ApplicationId = serializers.CharField(max_length = 30, allow_blank = False) # Mail Content Body = serializers.CharField(allow_blank = False) Attachments = serializers.CharField(allow_blank = False) # Other Parameters UseDefaultHeader = serializers.IntegerField(default = 0) UseDefaultFooter = serializers.IntegerField(default = 0) def create(self, validated_data): return Mails.objects.create(**validated_data) ` @swagger_auto_schema( operation_description="", operation_summary="create a mail", request_body=MailSerializer ) def create(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response({ 'code': 200, 'success': True, 'message': '%s successfully created.' % (OBJECT_NAME), 'data': [] }, status= status.HTTP_200_OK) I tried to use @swagger_auto_schema and a request_body parameters, but still not working -
old_field = model_state.fields.pop(self.name) KeyError: when migrations
I got this error $python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/<int:pk>/edit' [name='line-bot-edit'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. shared_models.ScenarioTemplate.user_types: (fields.W340) null has no effect on ManyToManyField. Traceback (most recent call last): File "/Users/whitebear/MyCode/httproot/nice_cdk/cinema-admin/manage.py", line 29, in <module> main() File "/Users/whitebear/MyCode/httproot/nice_cdk/cinema-admin/manage.py", line 25, in main execute_from_command_line(sys.argv) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 149, in handle loader.project_state(), File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 162, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'is_year_set' even $python manage.py migrate shows the same error. The checks I have done. $python manage.py showmigrations Every migrations are applied, but I have done python manage.py migrate --fake before error happens. in models.py is_year_set is … -
Im trying to download a file and i need to send option to my Django view from js script . Please advice
My HTML page looks something like below: The post function used is for upload the file with edited data..! Im trying to get the option value from HTML page to my Django view. <div><h3 style="text-align: center">Bulk Upload</h3></div> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="col-md-4"> <select class="form-select form-control" style="padding: 3px; border-radius: 1px;" id="option" name="option"> <option selected value="0"> Please select operation</option> <option value="1">Insert New Source Client</option> <option value="2">Update Volcker Attribute</option> </select> </div> <div class="col-md-2"> {% csrf_token %} <button id="downloadBtn" type="submit" title="Download CSV Template" onclick="export_template()" class="btn btn-primary" style="height: 34px; width: 100px" > Download </button> </div> My javascript function is defined as below: function export_template(){ let option = document.getElementById('option').value; console.log(option) if (option!=""){ window.location.href="export_template/option="+option; } } The view defined is as below where im trying to fetch "option" from JS script please advice def export_template(request, post): #option = int(request.POST.get("option")) option = int(request.POST.get("option")) if option == 2: file = open('C:/Users/Desktop/New Project (2) (1)/New Project/uploadcsv/media/bulk_upload/Update_Client_YYYYMMDD.csv', 'r') response = HttpResponse(file, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=Update__YYYYMMDD.csv' return response How to pass JS script value as parameter to my Django view..!` -
Django User Registration Form not working, no error
Trying to create a simple user registration form in django. Here is my views.py- def registerPage(request): form=UserCreationForm() if request.method == 'POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'newapp/register.html', context) And my html template- <h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> </form> In the views I imported UserCreationForm like this and following is the url which is working fine- from django.contrib.auth.forms import UserCreationForm url- path('register/', views.registerPage, name="register"), When I try to create a user the form seems to work fine but the user is never created in the admin. It doesn't show up.I refreshed the page and all. There is no error. I created a user from the admin panel just to make sure and it works. Earlier same form was giving me a CSRF token failure. Rebooting the computer that error went away. Now no error, but also no user. Curious with no error in sight, when can be reason for this to happen? Here is how the CMD looks like after few attempts of user creation, see if that gives you any clue- -
How to add SVG as background image in Django template
Pls how can I add SVG as background image in Django I have tried and it's not working I added the svg in this format url("image.svg") but nothing is showing. -
Django raise custom error if invalid API parameters
I am writing an API endpoint that queries for an Event in the time window given. The Event model has a start and end time, and the query accepts a search start time and an search end time. Any Event that overlaps between these two windows is returned. This works well. However, if the user asks to search using a search_time_start that is after the search_time_end, it returns no results (obviously), with no indication why. Instead I would like to return an Error message indicating what is wrong. I have a rough idea of how to do this, but not how to plug it into my existing code. Model class Event(models.Model): name = model.CharField(max_length=64) start_time = models.DateTimeField(null=False) end_time = models.DateTimeField(null=False) Serializer class EventSerializer(serializers.ModelSerializer): start_time = serializers.DateTimeField() end_time = serializers.DateTimeField() class Meta: model = Event fields = ("start_time", "end_time") Filter and View class EventFilterSet(GeoFilterSet): search_time_start = DateTimeFilter( field_name="end_time", lookup_expr="gte", help_text=( "The time for the start of the search. Limits events to those that end after the start time." ), ) search_time_end = DateTimeFilter( field_name="start_time", lookup_expr="lte", help_text=( "The time for the end of the search. Limits events to those that start before the end time." ), ) class Meta: model = Event … -
Saving a record along with the logged in users group in Django
I am new to Django. I want to save the logged in users Group in the groups field upon adding a new record. models.py from django.contrib.auth.models import User, Group, Permission class Infringement (models.Model): name = models.CharField(max_length=200) link = models.CharField(null=True, blank=True, max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True) player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) views.py @login_required(login_url='login') def createInfringement(request): form = InfringementForm() if request.method == 'POST': form = InfringementForm(request.POST) if form.is_valid(): form.instance.groups = 'request.user.group' form.save() return redirect('home') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringementForm(ModelForm): class Meta: model = Infringement fields = ['name', 'link', 'infringer', 'player'] Based on my research, I tried adding this in the view but it doesn't work. form.instance.groups = 'request.user.group' -
Updating environmental variables in Django while running
I have an app that makes some API calls, I store my API secret in an .env file which is loaded into the Django settings file which works fine. Once a month I have to update the API secret, I have the code to check for expiry and get the new key, my question is how to handle that within my running Django app. As it stands I can load the .env file in and do a find a replace on the key but that feels like a bad way to go about it in addition to not taking effect until the next time the app is restarted. When you have secrets that change over time whats best practice on updating and storing them? -
username and log out not appeared while logging in with google
I have made my models for customer, merchant. models.py class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone_number = models.CharField(max_length=12) address = models.CharField(max_length=255) profile_pic=models.FileField(default="") created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.username When a customer log in to the app they see their username in navbar and the "log in" button turns out to "log out". Now I want to give customers the functionality to log in with google too. settings.py ALLOWED_HOSTS = ['localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'projectapp.apps.ProjectappConfig', 'django_extensions', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ] SITE_ID=1 LOGIN_REDIRECT_URL = '/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'reward_database', 'USER': 'postgres', 'PASSWORD': 'ReVerSe@05', 'HOST': 'localhost', 'PORT': '5432' } } AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } For that purposes I have a signal.py. @receiver(post_save, sender = CustomUser) … -
Django - display value of an @property field in a filter
Good evening guys, I have the following model structure in my project: ` class Foo(models.Model): foo_name = models.TextField() foo_city = models.TextField() foo_actions = models.ManyToManyField(Action, through="FooActions") @property def bar(self): response = True if FooAction.objects.filter( foo_id=self.pk, foo__action=Action.ACTION_NAME_PK).first() else False return response ` I need to bring the 'bar' field in a filter, but I'm not getting it. I tried as follows: Foo.objects.filter(nome="João").values("foo_city","bar") Is it possible to bring this information this way? PS.: Sorry for my bad english -
Run python script at the click of an html button (Flask/Django)
I have a very simple python code that retrieves the share price of some stocks. I have managed to include that in Django/Flask so I can see this in a html page. I would like to create an html button that when I click on it it runs the python script and the share prices refresh (and remain on the same html page e.g. index.html) however I can't make it work. Can you please help with the html code for the button and the piece of code that I need to add to the app to make it work? -
Django - How to add a comment limit of 1
I currently have a comment functionality and I want to add a limit of one comment for each user but don't know how to do that. I tought on making a 'posted' field in the user model which would be true when the user posted a comment but I don't know how to do that and most importantly if that is the better way of doing that... class Comment(models.Model): service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=False, blank=True) def get_absolute_url(self): return reverse('product-feedback', kwargs={'pk': self.pk}) class ProductFeedbackView(DetailView): model = Product template_name = 'services/product-feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(service=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] new_comment = Comment(content=content, author=self.request.user , service=self.get_object()) new_comment.save() return redirect(self.request.path_info) <form action="" method="POST" id="main_form" class="comment_form"> <div> <label for="comment">Type Comment here</label> {{ comment_form.content }} {% csrf_token %} <input type="submit" value="Post"></div> </div> </form> -
How to deal with users when they are authenticated externally via openid recieving only an access or id token?
How do you for example create a model with a foreignkey to a user when the user is authenticated via openid connect externally recieving access token and id token after login or signup? How is authorization (roles, groups, permissions) done when we are not using standard Django authentication or user models but where these tokens (containing a sub or object id) exists in the session? Thanks for your time and help. -
Getting graphQl to work with django mongoengine and graphene
When trying to connect to graphQl, i am met with this error. AssertionError at /graphql/ You need to pass a valid Django Model in ProductType.Meta, received "<class 'inventory.models.Product'>". I am using Django, mongoengine and graphene. my models: from django.db import models from mongoengine import * # Create your models here. class Product(Document): name = StringField(required=True) pCode = StringField(required=True) sku = StringField() cost = StringField() price = StringField() category = StringField() meta = { "indexes":["name","pCode"] } my schema: import graphene from graphene_django import DjangoObjectType from .models import Store, Vendor, Product class ProductType(DjangoObjectType): class Meta: model = Product fields = ("name","pCode","price") class Query(graphene.ObjectType): all_products = graphene.List(ProductType) def resolve_all_products(root, info): return Product.objects.all() schema = graphene.Schema(query=Query) It is almost as if the document class doesnt pass something correctly...please help