Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Authentication Form not authenticating and redirecting
After I put the correct password, it should redirect to "/articles" , BUT IT'S REFRESHING THE LOGIN PAGE ONLY. def login(request): if request.method == 'POST': form = a_form(data=request.POST) if form.is_valid(): return redirect('/articles') else: form = a_form() context = {'form': form} return render(request, 'accounts/login.html', context) This is what my html looks like: {% extends 'articles/base.html' %} {% block content %} <div class="container"> <form class="login" action="{%url 'login'%}"> {%csrf_token%} {{form}} <input type="submit" value="login"> </form> </div> {% endblock %} I wonder what is that I'm missing here. -
django display the id of data in html
Good day everyone, I hope the title is enough to understand what my problem is, it is complicated to me because i create tables through views.py, this is my views.py students = studentsEnrolledSubjectsGrade.objects.filter(Subjects__in = student_subject.values_list('id')).filter(grading_Period=period).filter(Grading_Categories=category).order_by( 'Students_Enrollment_Records', '_dates' ).values('id','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname' ,'_dates','Grade').distinct() dates = list(students.values_list('_dates', flat=True).distinct().order_by('_dates')) table = [] student_name = None table_row = None columns = len(dates) + 1 table_header = ['Student Names'] table_header.extend(dates) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name table_row[dates.index(student['_dates']) + 1] = student['Grade'] table.append(table_row) this is my html <tr> {% for v in table.0 %} {% if forloop.first %} <th id="thupdate">{{v}}</th> {% else %} <th ><input type="text" name="updatedate" value="{{ v }}"></th> {% endif %} {% endfor %} <th hidden></th> <th data-id='headerss' id='headerave'>Average</th> </tr> <tbody> {% for row in table|slice:"1:" %} <tr class="tr2update"> <td>{{ row.0 }}{{row.id}}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for c in row|slice:"1:" %} <td><input type="text" id="oldgrade" class="oldgrade" name="gradeupdate" value="{{c}}">{{c.id}}</td> {% endfor %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="totalaverage" readonly/></td> </tr> {% endfor %} </tbody> I just want … -
How to pass a value to a search query
I am working with two pages and I would like to click on a tag on one page, which would insert a value to a search query on another page. So here's my views.py: def bikes_all(request): item_list = Bike.objects.all() category_q = request.GET.get('cat') if category_q: item_list = item_list.filter(category__pk=category_q) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, } return render(request, "bikes_all.html", context) and my template: <form method="GET" action="{% url 'core:bikes_all' %}"> <div class="form-row "> <div class="form-group col-5"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" {% if not request.GET.cat %} selected {% endif %}>Choose...</option> {% for cat in category_list %} <option value="{{ cat.pk }}" {% if request.GET.cat == cat.pk|slugify %} selected {% endif %}> {{ cat }}</option> {% endfor %} </select> </div> </div> <div class="form-row"> <button type="submit" class="btn btn-outline-primary btn-md">Search</button> </div> </form> and here's the a tag from another page: <div class="col-md-4 overlay zoom"> <a href="{% url 'core:bikes_all' %}"> <div style="position:relative;"> <img src="{% static '/img/category_choice/bike33.png' %}" class="img-fluid"> <div class="card-img-overlay"> <h2 class="card-title" style="text-align: center; color: aliceblue; position: absolute; bottom:5px;"> Road Bikes </h2> </div> </div> </a> </div> So I have {% url 'core:bikes_all' %} in my … -
Django selecting top n records per group using ORM
Following this question, I'm trying to get top 10 records per each group_by critera, but Django return this error: from django.db.models import F, Window from django.db.models.functions import RowNumber Purchases.objects.annotate(row_number=Window( expression=RowNumber(), partition_by=F('customer'), order_by=F('field_of_interest').desc() ) ).filter(row_number=10) raise NotSupportedError( django.db.utils.NotSupportedError: Window is disallowed in the filter clause. If I remove .dsc(), error message changes to: ValueError: order_by must be either an Expression or a sequence of expressions. I'm using PostgreSql. Is it a bug or am I wrong somewhere in my query? -
Build a Django elegant filter with dynamic number of fields
I have a Django model which I'm doing a view for it, which filters results. models.py: Ingredient(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=100, null=False, blank=False) cost = models.DecimalField(max_digits=14, decimal_places=2, null=False) Now the point is that the search form (which has every field except account of course), none of its fields are required, you can filter either for just a single field or two or the three of them. The problem is that I can't do: Ingredient.objects.filter(account=account, brand=brand, name=name, cost=cost) ...because brand, name, and cost could be sent empty/null How can I resolve this without making a filter line code for each filtering possibility? -
Django how to download a document that was inputted in a form
django 3.0 python 3.8 Here's a slightly odd question. How do you immediately download a document that was been uploaded. It may seem silly, but I'm trying to do it and can't seem to. Most of the things I'm looking at it want you to download a file that is saved somewhere, but the trick in my instances is that the file has never been saved (and shoudln't be). It's completely in memory. I want to give the downloaded for the same name as the inputted form. I currently download a file, but it is empty and has an odd name. So far I have this: Views.py class UpandDownloadFileView(TemplateView): form_class = UpandDownloadFileForm def post(self,request,*args,**kwargs): print('hi we posting files') print(self.request.POST) print(self.request.FILES) response = HttpResponse() response.write(self.request.FILES) response['Content-Disposition'] = 'attachment; filename={0}'.format(str(self.request.FILES)) return response forms.py class PopulateDocumentCreateForm(forms.Form): pass html <form method="post" action="{% url 'inputs:create' %}" enctype="multipart/form-data">{% csrf_token %} <div class='row'> <div class='col'> <p><input name="file" id="id_file" type="file"></p> </div> </div> <div class='row'> <div class='col'> <button class="btn btn-primary" type="submit">Submit</button> </div> </div> </form> (validation to come later) -
JQUERY replace default select atrribute data-empty_label
I tried to change the default empty "" options with a friendly labels however i was not successful for subcategory and name selects since data is coming dynamically from django. category works fine since there is an empty option when page loads however subcategory and name load on select data-empty_label "----------" instead and no options are visible. <div class="form-row"> <input type="hidden" name="csrfmiddlewaretoken" value="xxxxx"> <div class="form-group custom-control col-md-3"> <select name="category" class="custom-select custom-select-lg" required id="id_category"><option value="" selected>---------</option> <option value="1">One</option> <option value="2">Two</option> </select> </div> <div class="form-group custom-control col-md-3"> <select name="subcategory" disabled class="custom-select custom-select-lg chained-fk" required id="id_subcategory" data-chainfield="category" data-url="/chaining/filter/xxxxx" data-value="null" data-auto_choose="false" data-empty_label="--------" name="subcategory"> </select> </div> <div class="form-group custom-control col-md-3"> <select name="name" disabled class="custom-select custom-select-lg chained-fk" required id="id_name" data-chainfield="subcategory" data-url="/chaining/filter/xxxxx" data-value="null" data-auto_choose="false" data-empty_label="--------" name="name"> </select> </div> <div class="form-group col-md-3"> <input type="submit" value="Submit" class="btn-lg btn-success btn-block"> </div> </div> <script> $(document).ready(function() { $("select").on("change", function() { if($("select[name='category']").val() == "") { $("select[name='category'] > option:first-child").text('Category'); $("select[name='subcategory']").prop('disabled', 'disabled'); $("select[name='subcategory'] > option:first-child").text('Subcategory'); $("select[name='name']").prop('disabled', 'disabled'); $("select[name='name'] > option:first-child").text('Recipe'); } else { $("select[name='subcategory']").removeAttr("disabled"); $("select[name='subcategory'] > option:first-child").text('Subcategory'); } }).trigger('change'); $("select[name='subcategory']").on("change", function() { $("select[name='subcategory'] > option:first-child").text('Subcategory'); if($(this).val() == "") { $("select[name='name']").prop('disabled', 'disabled'); $("select[name='recipename'] > option:first-child").text('Recipe'); } else { $("select[name='name']").removeAttr("disabled"); $("select[name='ename'] > option:first-child").text('Recipe'); } }).trigger('change'); }); </script> -
UpdateView creating new object instead of altering original
I will start this with I know this has been asked but I looked through those answers and not of them were the solution here. views.py: class JobUpdateView(UpdateView): model = Job form_class = JobForm template_name = 'job/edit_job.html' urls.py: path('edit/<int:pk>/', job_views.JobUpdateView.as_view(), name='edit_job'), template (included the <form> I use to delete objects just in case that was having some effect): {% for job in jobs %} <button ><a href="{% url 'edit_job' job.id %}" >Edit</a></button> <!-- edit--> <form class="" action="{% url 'delete_job' pk=job.id %}" method="post"> <!--delete--> {% csrf_token %} <input type ='hidden' name ='job_id' value='{{ job.id }}'/> <button type="submit">Delete</button> </form> </div> {% endfor %} This will display a list of the user's posts, if the users clicks 'edit' on a specific post it will display the proper object and its contents in a form to be edited. But, when the user saves that form, instead of editing the original object there are now two objects, the original and whatever was changed. Not sure why this happening? -
How to display Django input data on second page
i have easy Django view which displays text which user will type in input. Now this text is displaying on this same page without changing address (scraping.html), but i would like to display it on new page (scrapingscore.html). How am i able to do that? I read about HttpResponseRedirect and tried do it, but it didn't work and i am confused. views.py class HomeView(TemplateView): template_name = 'scraping.html' def get(self, request): form = HomeForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): text = form.cleaned_data.get('post') form = HomeForm() args = {'form': form, 'text': text} return render(request, self.template_name, args) forms.py class HomeForm(forms.Form): search = forms.CharField(label='search', max_length=100) scraping.html {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload text</button> </form> {{ text }} {% endblock %} -
Django - interact Bokeh scripts with Heroku
I deployed app to Heroku. Everything works, except creating plots with Bokeh. Plots are created based on user's input, but plots are not displayed. After inspecting network I can see: in my base.html I have: <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.js"></script> The full code you can see on my github: https://github.com/f4lco0n/git-efforts. Is there any way to get this scripts to heroku? -
class Product(models.Model): ^ IndentationError: unexpected indent
I got this error, I just added a model in model.py under shop app in Django and got this error. from django.db import models Create your models here. class Product(models.Model): p_id = models.AutoField p_name = models.CharField(max_Length=50) dsc = models.CharField(max_Length=300) P_date = models.DateTimeField('date published') This code of models.py file. -
how to write a raw sql request of feild between two dates in django?
hello friends i write this code for chartit and i put a part of my code , i want write this sql raw query def weather_chart_day_view(request): patient=request.POST['patient'] id=patient_complete.objects.get(complite=patient).id date=request.POST['date'] date1=request.POST['date1'] fsuivie_horraire.objects.raw('SELECT id,date_sh, avg(temp)as temp, patient FROM public.fsuivie_horraire where patient='+str(id)+' and date_sh > '+date+' group by id,date_sh, patient;')} ''' i got this error when i execute ProgrammingError at /graphe/temperature_jour/ operator does not exist: date > integer LINE 1: ...lic.fsuivie_horraire where patient=3 and date_sh > 2020-03-... tahnk you for your help -
Updating dictionary value after using dictionary comprehension
I can update a nested dictionary after initialising it using a for loop but not after using dictionary comprehension . Why is that ? This works: def calendar_init(year, month, habits): date_list = dates_in_month(year, month) calendar_init = dict() for mydate in date_list: calendar_init[mydate] = {'mood': None} for habit in habits: calendar_init[mydate][habit] = None return calendar_init def create_calendar(year, month, habits, entries, moods): new_calendar = calendar_init(year, month, habits) for entry in entries: new_calendar[entry.day][entry.habit] = entry for mood in moods: new_calendar[mood.day]['mood'] = mood return new_calendar but this doesn't: def calendar_init(year, month, habits): date_list = dates_in_month(year, month) merged_dict = {**dict.fromkeys(habits, None), **{'mood': None}} calendar_init = {mydate: merged_dict for mydate in date_list} return calendar_init def create_calendar(year, month, habits, entries, moods): new_calendar = calendar_init(year, month, habits) for entry in entries: new_calendar[entry.day][entry.habit] = entry for mood in moods: new_calendar[mood.day]['mood'] = mood return new_calendar -
How can I get data from specific user django python
I am trying to get data from a specific user, but instead I am getting all data from all users in data base. template: {% for media in media_images %} <div class="profile-single-div"> <p class='profile-paragraph-image paragraph-image-name'>{{media.image_name}}</p> <p class='profile-paragraph-image paragraph-image-description'>{{media.image_description}}</p> <img height="97px" class='profile-image' src='{{media.image_image.url}}'> </div> {% endfor % views.py @login_required def profile(request): if request.method == 'GET': media_images = Media.objects.all() context = { 'media_images':media_images, } return render(request, 'users/profile.html', context) models.py class Media(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) image_name = models.CharField(max_length=50) image_description = models.CharField(max_length=80) image_image = models.ImageField(upload_to='media', default='default.jpg') def __str__(self): return f'{self.user.username} Media' -
Django How to combine different contexts and pass it to template
I am creating a small ToDo App. I don't know how to combine different contexts in one context. Below You can see that I created three contexts that return different values. The first context counts the number of Plans by date of the Day model. The second context counts the number of completed plans by Day and the third context counts Plans status=deferred class DayStatsListView(ListView): model = Day queryset = Day.objects.all() context_object_name = 'all_plan_stats' template_name = 'project/stats.html' def get_context_data(self, **kwargs): context = super(DayStatsListView, self).get_context_data(**kwargs) # Counting Total Number of Plans by Day context['total_plans_count'] = Day.objects.annotate(num_of_plans=Count('plan')) \ .values('num_of_plans', 'date', 'id') # Counting is_completed=True Plans by Day context['num_of_completed_plans'] = Day.objects \ .filter(plan__is_completed=True) \ .annotate(num_of_completed_plans=Count('plan__is_completed')) \ .values('num_of_completed_plans', 'id', 'date') # Counting status=deferred Plans by Day context['num_of_deferred_plans'] = Day.objects \ .filter(plan__status='deferred') \ .annotate(num_of_deferred_plans=Count('plan__is_completed')) \ .values('num_of_deferred_plans', 'id', 'date') return context models class Day(models.Model): date = models.DateField(default=datetime.date.today, unique=True) class Plan(models.Model): title = models.CharField(max_length=255) status = models.CharField(max_length=255, choices=PLAN_STATUSES, null=True, default='upcoming') is_completed = models.BooleanField(default=False, null=True) day = models.ForeignKey(Day, CASCADE, null=True) The question is how can I combine that 3 contexts in one context and pass it to the template so I can easily forloop over it. I need my these queries should be in one context -
Unable to serve my Django site on port 80
I have successfully hosted my Django website on xyz.com:8000 which runs behind nginx & gunicorn. Currently my config file at /etc/nginx/sites-available/xyz.com looks like :- server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject/myproject.sock; } } I am able to access my website at xyz.com:8000 using this. Now I want to show my website at xyz.com (right now it shows "welcome to nginx" page). So I modified above file and replaced line 2 with "listen 80". Then proceeded usual steps, of creating a symlink which produces another config file in /etc/nginx/sites-enabled/xyz.com But when I visit xyz.com, it is still showing me default "welcome to nginx" page! I tried changing "/etc/nginx/sites-enabled/default" and replaced 80 with 8000 everywhere, so now at xyz.com:8000 it shows default "welcome to nginx" page. But at xyz.com I am being shown 502 bad gateway. I searched over net but nothing seems to fix my situation, I have spent whole day trying them out. I am hosting on Google cloud, ubuntu. -
Is there a way to use Chart.js on Django without using API like rest?
I'm creating a project that has IoT on it, some arduino sensors etc. And I'm going to use MQTT not HTTP to transfer data from IoT to my web, after I transferred the data from the IoT, I need to graph it using Chart.js but on tutorials I found about chart.js they're using API to get Json Format to display it on graph. That I'm going to use MQTT not HTTP. is this possible? or is there any good graphs visualization that does not use APIs and compatible with Django? Thanks! -
How to display Dynamic nested JSON directly without a Model in Django Rest Framework?
I have the JSON data that need's to be displayed in the REST Framework's Response. The JSON data is fetched dynamically from another source. So, it'll keep changing but it's in the following standard format. JSON Format (Can range from 0 to 50): { 1: { 'Title': 'A1: Accused No. 1', 'Category': 'Movies', 'Size': '1.38GB', 'Date': 'Feb 29, 2020, 5:13:25 PM' }, 2: { 'Title': 'Sivappu Manjal Pachai', 'Category': 'Movies', 'Size': '744.26MB', 'Date': 'Feb 29, 2020, 5:13:25 PM' } } The above data is stored in a dictionary variable. The data is dynamic and I want the Django REST framework to display the contents exactly as displayed above in Nested Format. -
How can I change a status of user profile by missed call on an toll-free number.?
Actually I am creating a project in which I want an specific user is active or not can be changed by missed call service -
object has no attribute 'cleaned_data' Django form
I have a form which when I pass as context to contact.html only shows the button and I get the error: 'ContactForm' object has no attribute 'cleaned_data'. forms.py: from django import forms from phone_field import PhoneField from django.utils import timezone from .models import Contact class ContactForm(forms.Form): name = forms.CharField(max_length=20) phone = PhoneField() subject = forms.CharField(max_length=300) message = forms.CharField(max_length=300, widget=forms.Textarea()) dateContact = forms.DateTimeField(required=False) class Meta: model = Contact fields = ('name', 'phone', 'subject', 'message') def save(self, commit=True): form = super(ContactForm, self).save(commit=False) ContactForm.name = self.cleaned_data['name'] ContactForm.phone = self.cleaned_data['phone'] ContactForm.message = self.cleaned_data['message'] if commit: form.save() return form models.py: from django.db import models from phone_field import PhoneField from django.utils import timezone class Contact(models.Model): name = models.CharField(max_length=50) phone = PhoneField() subject = models.CharField(max_length=50, default="נושא") message = models.CharField(max_length=300, editable=True) dateContact = models.DateTimeField(default=timezone.now()) def __str__(self): return self.name views.py: def contact(request): if request.method == "POST": form = ContactForm(request.POST) if(form.is_valid): name = form.cleaned_data.get['name'] phone = form.cleaned_data.get['phone'] subject = form.cleaned_data.get['subject'] message = form.cleaned_data.get['message'] form.save() return render(request=request,template_name= "tevel/contact.html", context ={"form" : form}) else: return render(request=request,template_name= "tevel/contact.html") and the form doesn't even appear in the html page, only in the admin page -
django display the id of data in html
I hope the title is enough to understand what my problem is, it is complicated to me because in my views i create table, this is my views.py students = studentsEnrolledSubjectsGrade.objects.filter(Subjects__in = student_subject.values_list('id')).filter(grading_Period=period).filter(Grading_Categories=category).order_by( 'Students_Enrollment_Records', '_dates' ).values('id','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname' ,'_dates','Grade').distinct() dates = list(students.values_list('_dates', flat=True).distinct().order_by('_dates')) table = [] student_name = None table_row = None columns = len(dates) + 1 table_header = ['Student Names'] table_header.extend(dates) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name table_row[dates.index(student['_dates']) + 1] = student['Grade'] table.append(table_row) this is my html <tr> {% for v in table.0 %} {% if forloop.first %} <th id="thupdate">{{v}}</th> {% else %} <th ><input type="text" name="updatedate" value="{{ v }}"></th> {% endif %} {% endfor %} <th hidden></th> <th data-id='headerss' id='headerave'>Average</th> </tr> <tbody> {% for row in table|slice:"1:" %} <tr class="tr2update"> <td>{{ row.0 }}{{row.id}}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for c in row|slice:"1:" %} <td><input type="text" id="oldgrade" class="oldgrade" name="gradeupdate" value="{{c}}">{{c.id}}</td> {% endfor %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="totalaverage" readonly/></td> </tr> {% endfor %} </tbody> I just want to display … -
Django search function that calls other views return ValueError
I created a view function to capture all search queries and then treat each depending on the type of search. In first step, I tried to pass all queries to another view function to see if this approach works: in main app urls.py from searchapp.views import search urlpatterns += [ path('search', search) ] in views.py for searchapp def search(request): if request.method == 'GET': return other_view_function(request, query=request.GET.get('q')) else: return HttpResponseNotFound('Search query is not provided.') However, I get value error no matter I include q in the call or not: The view searchapp.views.search didn't return an HttpResponse object. It returned None instead. It's probably an obvious syntax error that I can't see! -
Keeping value selected after another form search
I am having a problem with keeping last selected value in my form. On my page I have got 2 forms, one is made for filtering results that are inside a specific category and the other one is having a function of changing the category. My template looks like that: <form method="GET" action="{% url 'core:category_search' category.id %}"> <h5>Search</h5> <div class="form-row"> <div class="form-group col-8"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand.." value="{{request.GET.q}}"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <h5>Price from</h5> <div class="form-row"> <div class="form-group col-5"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="price_from" placeholder="Price from" value="{{request.GET.price_from}}"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <h5>Price to</h5> <div class="form-row"> <div class="form-group col-5"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="price_to" placeholder="Price to" value="{{request.GET.price_to}}"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <div class="form-row "> <div class="form-group col-5"> <label for="category">Brand</label> <select id="bra" class="form-control" name="bra"> <option value="" {% if not request.GET.bra %} selected {% endif %}>Choose...</option> {% for bra in brand %} <option value="{{ bra.pk }}" {% if request.GET.bra == bra.pk|slugify %} selected {% endif %}> {{ bra }}</option> {% endfor %} … -
how to print images in html from python(Django)
hi please anyone to help me out with this, the code i have here is taking screenshots and saving it in my media folder so i want to print the pictures out in my html page but it's giving me issues, i think i'm missing a lot this is my python code that is taking the screenshots from django.http import HttpResponse import time,random,pyautogui from django.db import models import sys,os from shots.models import pictures from shots.forms.forms import DocumentForm from django.conf import settings def button(request): return render(request,'index.html') def output(request): while True: myScreenshot = pyautogui.screenshot() name = random.randrange(1,1000) full_name = str(name) + ".jpg" filepath = settings.MEDIA_ROOT + '\shots' full_path = filepath + full_name saver = myScreenshot.save(full_path) # generate a random time between 120 and 300 sec random_time = random.randrange(3,6) # wait between 120 and 300 seconds (or between 2 and 5 minutes) time.sleep(random_time) myScreenshots2 = [] myScreenshots2.append(saver) # return (myScreenshots2) return HttpResponse(request,'task.html',saver) def stopshot(request): os.system("pause")``` -
TypeError: __init__() missing 1 required positional argument: 'on_delete' how can i solve this
Python 3.8.1 django version 3.0.3 when i am run this code i am getting this error TypeError: __init__() missing 1 required positional argument: 'on_delete' Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) #additional profile_site = models.URLField(blank = True) profile_pic = models.ImageField(upload_to = 'profile_pics', blank = True) def __str__(self): return self.user.username forms.py from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) class meta(): model = User fields = ('username', 'email', 'password') class UserProfileInfo(forms.ModelForm): class meta(): model = UserProfileInfo fields = ('profile_site', 'profile_pic')