Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is POST only way to send data in django?
So i am creating an application in which am showing university information to students. When the click on apply - i will be showing a modal and asking them to select "Month". So am using "id" from the main page to get the course students selected and now i want to know the month which they selected. If its just sending "id" means i can just do {% url 'application-save' data.id %} But i also need to Month from modal, so i tried that by making a form inside modal and collecting the selected ! And ya its working, i used the below request.POST['selected_month'] And its perfectly saved, now my concern is this the right way ? is this secure way to do ? How to send a data without post and passing to url ? -
how to create user login with roles, eg.is_staff,is_manager,is_teamlead (diffrent template)?
this is my models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) full_name =models.CharField(max_length=55) mobile = models.CharField(max_length=11) is_superuser = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) is_teamlead = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) login.py file def login(request, *args, **kwargs): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username, password=password) this is my login page, i need to login diffrent html pages as per role -
Trying to parse all information from Tempbooking model to Booking model if the admin changes is_active to 'true' in the tempbooking django
This is the model: class Booking(models.Model): booker = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() discount_code = models.CharField(max_length=50, null=True, blank=True) guest_no = models.PositiveIntegerField() arrival_date = models.DateTimeField(auto_now=False, auto_created=False, auto_now_add=False, null=True,blank=True) departure_date = models.DateTimeField(null=True,blank=True) is_active = models.BooleanField(default=False) class Meta: db_table = 'booking' managed = True verbose_name = 'Booking' verbose_name_plural = 'Bookings' class Tempbooking(models.Model): booker = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() discount_code = models.CharField(max_length=50, null=True, blank=True) guest_no = models.PositiveIntegerField() arrival_date = models.DateTimeField(auto_now=False, auto_created=False, auto_now_add=False, null=True,blank=True) departure_date = models.DateTimeField(null=True,blank=True) is_active = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.first_name class Meta: db_table = '' managed = True verbose_name = 'Tempbooking' verbose_name_plural = 'Tempbookings' This is the form: class BookingForm(forms.ModelForm): discount_code = forms.CharField(required=False) is_active = forms.HiddenInput() class Meta: model = Tempbooking fields = '__all__' widgets = { 'booker': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Your username'}), 'first_name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Your First Name'}), 'last_name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Your Last Name'}), 'email': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Your Email'}), 'guest_no': forms.NumberInput(attrs={'class':'form-control'}), 'arrival_date': forms.DateTimeInput(attrs={'class':'form-control','type':'date'}), 'departure_date': forms.DateTimeInput(attrs={'class':'form-control','type':'date'}), 'discount_code': forms.TextInput(attrs={'class':'form-control','placeholder':'If our discounted product'}) } This is the view: def booking(request): form = BookingForm() form2 = TempbookingForm() if request.method=='POST': form = BookingForm(request.POST) if form.is_valid() or form2.is_valid: form2 = TempbookingForm(form) form2.save() return redirect('booking') context = { 'form': form, } return render(request, … -
django allauth github authentication get 400 bad request
I'm trying to apply github authentication to my blog. I followed the tutorials but I got Social Network Login Failure. the detailed error is: {'provider': 'github', 'code': 'unknown', 'exception': HTTPError('400 Client Error: Bad Request for url: https://api.github.com/user?access_token=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')} I have confirmed the consistency of the url I set in github applications and my blog admin. I don't know what the problems are. -
How to iterate over a queryset in django template?
I am aware that this is very likely a duplicate but solutions provided in alike questions did not help. This is at first glance very straightforward issue, it should work by all means but for some reason, it does not. In a Django template, I am filtering a queryset of records based on the current user. Then I loop through it and want to display each result separately. Nothing complicated. The code goes: {% if user.is_authenticated %} {% if user.quick_links.all %} {{ user.quick_links.all }} <h2>Moje rychlé přístupy:</h2> {% for link in user.quick_liks.all %} <div class="col-md-2"> <a href="{{ link.link }}"><button class="btn btn-info">{{ link.link_name }</button></a> </div> {% endfor %} {% endif %} {% endif %} the {{ user.quick_links.all }} displays <QuerySet [<UserQuickAccessLink: Link uživatele david@email.eu: Google>, <UserQuickAccessLink: Link uživatele david@email.eu: Coding Music>]> but then the program never enters the for loop even though the iterable is clearly there. {% for link in user.quick_liks.all %} <div class="col-md-2"> <a href="{{ link.link }}"><button class="btn btn-info">{{ link.link_name }} </button></a> </div> {% endfor %} The above is never executed. What is the trick here? -
how to get the value of html element on the same page using django/jinja
i am writing code for django project and my html code is like, Course <select name="Courses" value="Courses" id="Courses"> <option value="MCA" selected>MCA</option> </select> Year/Pattern <select name="pattern" value="Courses" id="pattern"> <option value="newPattern" selected>New-Pattern</option> <option value="oldPattern" selected>Old-Pattern</option> </select> and here i wanted to get the value as MCA from the option element and then compare with the database value, on the same page, so how can I write jinja code for this...? -
Best way to manage file upload in a django-angular API Rest
I have a Django API Rest as backend and a Angular frontend interface for an app and I'm currently implementing a tool to upload specific files and save them in my server directory or in drive via its own API. My question is what is the best/most formal/correct way to handle this. Maybe angular can take the file and save it? Or should I pass the uploaded file via post request so Django do the necessary logic? I'll thank some example code for the post request if it is the second case. -
Adding Variables to SQL queries
I have the following code which returns a table from my MySql Database one_yrs_ago = datetime.now() - relativedelta(years=1) all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)'\ How would I add the one_yrs_ago variable to the SQL query in this situation , like so : one_yrs_ago = datetime.now() - relativedelta(years=1) all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)'\ ' AND WHERE genLedger.TxDate > ' one_yrs_ago'' -
icontains does not match any items in the database
This is my data: >>> print(MyModel.objects.get(id=1).Fruits) #Fruits is JSONField >>> print(favorites) {"Title": ["Fruits"], "Name": ["Banana", "Cherry", "Apple", "Peach"]} ['Apple', 'Banana'] I define a query as follows: >>> query = reduce(operator.or_, (Q(Fruits__Name__icontains=x) for x in favorites)) >>> print(query) (OR: ('Fruits__Name__icontains', 'Apple'), ('Fruits__Name__icontains', 'Banana')) When I run this query: MyModel.objects.filter(query_field) it doesn't match any item in the database. -
How to get currently logged-in user in signals.py file?
request.user isn't working because it raises a NameError: "name 'request' is not defined." I basically want to get the email address of the logged-in user to send him email that a certain task has been completed and I want to send an email to the user using @reciever decorator, like this: @receiver(delayed) def my_handler(sender, **kwargs): send_mail('Subject', 'Message', 'myemail@gmail.com', 'user_email@gmail.com', fail_silently=False ) -
Data output from the database
Closed. This question needs to be more focused. It is not currently accepting answers. Update the question so it focuses on one problem only. This will help others answer the question. You can edit the question or post a new one. Closed 49 mins ago. (Private feedback for you) I want: to make a website with a table-rating of students. Students and their scores will be taken from Google Sheets. My first implementation was the following algorithm: The user visited the page with the rating The program received data from Google Sheets The program compared the received data with the data in the Django database If there were duplicates, she deleted the copy. If the students ' scores were changed, the program updated the data The program outputs data to the website I understand that such an algorithm is disgusting. Because there are too many requests coming from the program and with a large number of records, the speed will drop significantly. Do you think it would be appropriate to abandon the Django database and immediately load data from Google Sheets. In this case, you can skip the data comparison and additional access to the database. If there are any … -
FileField / ImageField migration doesn't apply
I would really appreciate if someone could help me with this Django error, I have my models created like this : from django.db import models from django.utils.timezone import now # Create your models here. class Album(models.Model): album_title = models.CharField(max_length=200) creation_date = models.DateTimeField(default=now) def __str__(self): return self.album_title class Photo(models.Model): name = models.CharField(max_length=300, default="") album = models.ForeignKey(Album, on_delete=models.CASCADE) # file = models.ImageField(upload_to=Album.album_title, null=True, blank=True) description = models.CharField(max_length=1000, default="") file_url = models.CharField(max_length=1000) selected = models.BooleanField(default=False) date_uploaded = models.DateTimeField(default=now) file_type = models.Choices('Raw', 'JPEG') def __str__(self): return str(self.album) + "ID.{:0>3}".format(self.id) If I make the migrations like this, everything works fine, but whenever I uncommented the line : file = models.ImageField(upload_to=Album.album_title, null=True, blank=True) in my class Photo, I can't do migrations. When I run the python3 manage.py make migrations code I have this stack trace : Traceback (most recent call last): File "/Users/adamspierredavid/Documents/django/crueltouch/manage.py", line 22, in <module> main() File "/Users/adamspierredavid/Documents/django/crueltouch/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 190, in handle self.write_migration_files(changes) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", … -
Django form not rendering in the html page
I am learning Django and have created the form using ModelForms. First I wrote the views.py as function but once I tried to make it class the form is not rendering while rest of the tags are working. This is my views.py in function method def company(request): company = Company.objects.all() cform = CompanyForm() form = CompanyForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/company') return render(request,'company/company.html',{ 'company': company, 'cform':cform }) This is class based views.py class CompanyView(generic.TemplateView): model = 'Company' template_name = 'company/company.html' I have updated the urls.py like this urlpatterns = [ path('',views.IndexView.as_view(), name='index'), path('form/',views.CompanyView.as_view(),name='company'), ] Finally this is my html template <h1>{{ company.company_name }}</h1> <ul> {% for company in company.choice_set.all %} <li>{{ company.company_name }}</li> {% endfor %} </ul> <form method="post"> {% csrf_token %} <fieldset> <legend> <h2> Company Form </h2> </legend> {{ cform.as_p }} </fieldset> <input type="submit" value="Submit" /> </form> and forms.py from .models import Company # create a ModelForm class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ('company_name','location','email_id') I tried many changes to the template and all but I am not able to find the error here. -
How can I make pagination size changable from admin in Django Rest
Currently I use django-constance, which gives me a fields in admin with configurable values. And then I do this: from constance import config def get_page_pagination_with_custom_page_size(size): class CustomPagination(PageNumberPagination): page_size = size return CustomPagination class ArticleListViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleListSerializer filter_backends = [DjangoFilterBackend] filterset_class = ArticleListFilterSet permission_classes = [AllowAny] pagination_class = get_page_pagination_with_custom_page_size(config.article_pagination) With this I can change config.article_pagination from admin to alter pagination, but in order to apply all changes I need to restart server. How can I make my view class to be dynamic and catch all changes "on fly"? -
Is it possible to exectue a function on model delete?
I have a model Stock and DeltaStock. class Stock(models.Model): quantity = models.DecimalField() class DeltaStock(models.Model): delta_quantity = models.DecimalField() stock = models.ForeignKey(to=Stock, on_delete=models.CASCADE) Stock is the state of the warehouse with the current state. And everytime something is taken out of the stock, I subtract that from the quantity and create DeltaStock. But if something gets returned to the stock i want to delete DeltaStock and add that quantity back to the stock. So my question is: Is there a way to execute a function that adds delta_quantity when DeltaStock gets deleted? I should be executed no matter which way DeltaStock gets deleted. -
"unexpected end of input" when Jinja templating used to provide multiple parameters to onclick function
I'm trying to run a js function using parameters passed into the template via jinja, where item contains strings as follows: item.id = 'item1' item.indicator = 'yes' #or no Template code: {% for item in items %} <!--The error is thrown by the line directly below!--> <div class='qitem' id='{{item.id}}' onclick = change_background('{{item.indicator}}', '{{item.id}}')></div> {% endfor %} <script> function change_background(indicator, id){ if (indicator == 'yes'){ document.getElementById(id).style.background='lightgreen'; }else{ document.getElementById(id).style.background='pink'; </script> In the culpable line in my code, '{{item.indicator}}' is red, and the first ' is underlined in vscode. The code works despite this, if only ONE argument it used as follows: change_background('{{item.indicator}}') (with corresponding function adjusted accordingly), but does not work if I try to use two arguments. The order of the arguments doesn't seem to matter. Neither does using "{{}}" instead of '{{}}'. Additionally, if I attempt to run two functions onclick: <div class='qitem' id='{{item.id}}' onclick = make_green('{{item.id}}'); increment_click('{{item.indicator}}')> only the first executes, and the second is ignored without any errors being thrown! I've searched on here and elsewhere. I don't really want to jsonify the data I pass in to the template. I feel as though there's a nuance I'm missing when using jinja. -
Django Storage and Boto3 not retrieving Media from AWS S3
I am using a development server to test uploading and retrieving static files from AWS S3 using Django storages and Boto3. The file upload worked but I cannot retrieve the files. This is what I get: And when I check out the URL in another tab I get this **This XML file does not appear to have any style information associated with it. The document tree is shown below.** <Error> <Code>IllegalLocationConstraintException</Code> <Message>The me-south-1 location constraint is incompatible for the region specific endpoint this request was sent to.</Message> <RequestId></RequestId> <HostId></HostId> </Error> Also I configured the settings.py with my own credentials and IAM user AWS_ACCESS_KEY_ID = <key> AWS_SECRET_ACCESS_KEY = <secret-key> AWS_STORAGE_BUCKET_NAME = <bucket-name> AWS_DEFAULT_ACL = None AWS_S3_FILE_OVERWRITE = False AWS_S3_REGION_NAME = 'me-south-1' AWS_S3_USE_SSL = True AWS_S3_VERIFY = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
formats used by django in the data exchange between client and server?
could someone tell me what format django uses in the data exchange between client and server? Does he only use one, or are there more? do you believe they are valid or do they have disadvantages? -
Liked time of request.user is not showing
I just started learning Django. I am building a simple Blog App and I am trying to get the user liked time of post of request.user. I made a Post model and a Like model. And when user like show the like time of user. But it is not showing the liked time. models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') class Likepost(models.Model): by_user = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(Post, on_delete=models.CASCADE) date_liked = models.DateTimeField(auto_now_add=True) views.py def blog_post_detail(request, post_id): obj = get_object_or_404(Post, pk=post_id) accessLikes = obj.likepost_set.all() for All in accessLikes: if request.user == All.by_user All.request.user.date_liked context = {'obj':obj} return render(request, 'blog_post_detail.html', context} What i am trying to do :- I am trying to access liked time of request.user It is keep showing :- Likepost' object has no attribute 'request' I will really appreciate your help. Thank You -
Django Project on AWS EC2 Static files
I deployed my Django Project on an AWS EC2 instance with Windows Remote. Everything is running but the problem is that the project can't load the static files. Has anyone had the same issue? I have run python manage.py collectstatic but it didn't help. BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATIC_ROOT = '/Desktop/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
Django Database get data
I am trying to get all my data out of the database in a array or list format. Such that I can make an for loop in the html to loop through all the names in the database. I tried with: all_name = name.objects.all() the output will be shown as <QuerySet [<allName: name1>, < allName: name2>, < allName: name3>]> However I want to get something like: name1; name2; name3 What I did next is to use the .get function: all_name = name.objects.get(id=1) This gives me only one object with the given id. Is there a way to get what I am looking for and display my array/list with a forloop in a html file? -
Accessing the database [closed]
I want: to make a website with a table-rating of students. Students and their scores will be taken from Google Sheets. My first implementation was the following algorithm: The user visited the page with the rating The program received data from Google Sheets The program compared the received data with the data in the Django database If there were duplicates, she deleted the copy. If the students ' scores were changed, the program updated the data The program outputs data to the website I understand that such an algorithm is disgusting. Because there are too many requests coming from the program and with a large number of records, the speed will drop significantly. Do you think it would be appropriate to abandon the Django database and immediately load data from Google Sheets. In this case, you can skip the data comparison and additional access to the database. If there are any other solutions to my problem, then I will gladly accept your suggestions. Unfortunately, this is my first experience working with the web and the database. -
Reverse for 'cbvdetail' not found. 'cbvdetail' is not a valid view function or pattern name
i can't call my detail class using reverse_lazy from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from . models import Task from . forms import Taskform from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView class Tasklistview(ListView): model = Task template_name = 'home.html' context_object_name = 'task' class Detailview(DetailView): model=Task template_name = "details.html" context_object_name = 'task' class Updateview(UpdateView): model = Task template_name = "update.html" context_object_name = "task" fields = ('name', 'priority', 'date') def get_success_url(self): return reverse_lazy("cbvdetail",kwargs={'pk':self.object.id}) urls.py from django.urls import path from . import views app_name='todoapp' urlpatterns = [ path('',views.home,name='home'), # path('details', views.details,name='ere') path('delete/int:id/',views.delete,name='delete'), path('edit/int:id/',views.update,name='update'), path('cbvhome/',views.Tasklistview.as_view(),name='home'), path('cbvdetail/int:pk/',views.Detailview.as_view(),name='cbvdetail'), path('cbvupdate/int:pk/',views.Updateview.as_view(),name='edit'), ] -
django rest fraemwork. Filtering model according data in relation models
I have a some models like: class Model(TimeStampedModel): model_name = models.CharField(_("model_name"), max_length=240) model_price = models.models.DecimalField(_("model_price"), max_digits=8) class ModelAdditionalData_1(TimeStampedModel): model_id = models.OneToOneField( Model, verbose_name=_('related model'), on_delete=models.CASCADE, related_name='model_water_flow_data', related_query_name='model_water_flow_data' ) model_param_1 = models.models.DecimalField(_("model_param_1"), max_digits=8) class ModelAdditionalData_2(TimeStampedModel): model_id = models.OneToOneField( Model, verbose_name=_('related model'), on_delete=models.CASCADE, related_name='model_water_flow_data', related_query_name='model_water_flow_data' ) model_param_2 = models.models.DecimalField(_("model_param_2"), max_digits=8) urls.py details_router = SimpleRouter() details_router.register('models', DetailViewSet, 'models') urlpatterns = details_router.urls views.py DETAIL_FILTER_PARAMETERS = [ openapi.Parameter( 'model_param_1', openapi.IN_QUERY, type=openapi.TYPE_STRING, format=openapi.FORMAT_DECIMAL ), openapi.Parameter( 'model_param_2', openapi.IN_QUERY, type=openapi.TYPE_STRING, format=openapi.FORMAT_DECIMAL ) ] @method_decorator(name='list', decorator=swagger_auto_schema( manual_parameters=DETAIL_FILTER_PARAMETERS)) class ModelsViewSet(ReadOnlyModelViewSet, GenericViewSet): serializer_class = ModelsSerializer def list(self, request, *args, **kwargs): .... Here is request with params to filter: curl -X GET "http://localhost:8000/api/v1/models/?model_param_1=1&model_param_2=2" -H "accept: application/json" How i can filter model Model according to data in relation models ModelAdditionalData_1 and ModelAdditionalData_2 with query params and return json only with records which corespond to filter? -
How can I use CLOSESPIDER_ITEMCOUNT with scrapyd?
I'm using scrapy & scrapyd in django framework. I want to limit my number of url crawls. I have found this CLOSESPIDER_ITEMCOUNT option on scrapy doc. for counting and stopping my spider but I'm having trouble with using it. Is there someone who has knowledge on that? Or know any source of (clear) example-explanation for that? (Yes, I checked the doc. No, there is not much info there about this topic). Any information would be appreciated