Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have created school record system but when i m creating button for delete it is showing error
****views.py file from django.shortcuts import render from django.urls import reverse_lazy from django.http import HttpResponse from django.views.generic import (View,TemplateView, ListView,DetailView, CreateView,DeleteView, UpdateView) from . import models # Create your views here. # Original Function View: # # def index(request): # return render(request,'index.html') # # # Pretty simple right? class IndexView(TemplateView): # Just set this Class Object Attribute to the template page. # template_name = 'app_name/site.html' template_name = 'index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['injectme'] = "Basic Injection!" return context class SchoolListView(ListView): # If you don't pass in this attribute, # Django will auto create a context name # for you with object_list! # Default would be 'school_list' # Example of making your own: # context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_details' model = models.School template_name = 'basic_app/school_detail.html' class SchoolCreateView(CreateView): fields = ("name","principal","location") model = models.School class SchoolUpdateView(UpdateView): fields = ("name","principal") model = models.School class SchoolDeleteView(DeleteView): model = models.School success_url = reverse_lazy("basic_app:list") def delete(pk): class CBView(View): def get(self,request): return HttpResponse('Class Based Views are Cool!') models.py from django.db import models from django.urls import reverse class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("basic_app:detail",kwargs={'pk':self.pk}) class Student(models.Model): name = models.CharField(max_length=256) age … -
Should sign in with Microsoft be done on frontend or backend?
I plan to write a Django REST backend and React SPA frontend. I want to authenticate exclusively with Microsoft. I setup the application in azure active directory. Do I want use the frontend or backend to authenticate? Do I want to use react-microsoft-login or django_microsoft_auth? -
Django: How to read question mark (?) in the django URL
I am developing a Django app that stores the user input in the database. Now the problem is that when the user writes the ? in the input field, Django treats it as the part of querystring so it doesn't save it. I am using the following JavaScript code: $("#submit").on("click",function(){ text = $("#input").val(); $.get('/add/'+text); } And here is my urls.py file: urlpatterns = [ path('add/<str:text>',views.add, name='add'), .............. ] And in views.py, I have: def add(request,text): field = Text(text=text) field.save() return HttpResponse('') -
pagination of a specific context in multiple context in ListView not working in django?
in django, i am trying to list some queries of several objects like user lists, categoies and Post list. the homepage will be contained couple of blocks or boxes. each box will have different query list like Post list, User List, category list. But only one context will have pagination and other won't and ofcourse the pagination will be working on Post list. here is the views.py: class BlogappListView(ListView): model = Category,CustomUser template_name = 'home.html' context_object_name='category_list' queryset=Category.objects.all() paginate_by = 2 def get_context_data(self, **kwargs): context = super(BlogappListView, self).get_context_data(**kwargs) context['user_list']= CustomUser.objects.all() context['post_list']=Post.objects.all() activities=context['post_list'] return context def get_related_activities(self,activities): queryset=self.objects.activity_rel.all() paginator=Paginator(queryset,2) page=self.request.GET.get('page') activities=paginator.get_page(page) return(activities) in urls.py: urlpatterns = [ path('',BlogappListView.as_view(),name='home'), ] in base.html, the paginate portion code: <ul class="pagination justify-content-center mb-4"> {% if is_paginated %} {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item"> <a class="page-link" href="?page={{ num }}">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a class="page-link" href="?page={{ num }}">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number … -
How return image url and prepopulate a form at the same time? Error in image url inside the template
I am having a problem to prepopulate a form and also return the image url of the account: My view: class DadosProfissionaisViewUpdate(LoginRequiredMixin, FormView): template_name = 'accounts/udadosprofissionais.html' form_class = DadosProfissionaisForm model = DadosProfissionais def get_initial(self): obj = DadosProfissionais.objects.get(user = self.request.user) initial = super(DadosProfissionaisViewUpdate, self).get_initial() initial = model_to_dict(obj) return initial def form_valid(self, form): obj = DadosProfissionais.objects.get(user = self.request.user) obj.user = self.request.user obj.nome_publico = form.cleaned_data['nome_publico'] obj.nome_consult = form.cleaned_data['nome_consult'] obj.cep_atend = form.cleaned_data['cep_atend'] obj.endereco_atend = form.cleaned_data['endereco_atend'] obj.bairro_atend = form.cleaned_data['bairro_atend'] obj.save() messages.success(self.request, _('Seus dados foram atualizados com sucesso.')) return redirect('home') My template: {% block content %} <div class="text-center"> <img src="{{ profile_pic.url }}" class="rounded" alt="img"> </div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-primary">Enviar</button> </form> {% endblock %} My urls - added MEDIA_URL: urlpatterns = [ path('admin/', admin.site.urls), ........ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), path('accounts/', include('accounts.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My form: class DadosProfissionaisForm(forms.ModelForm): nome_publico = forms.CharField(label='Nome Público') nome_consult = forms.CharField(label='Nome do Consultório') cep_atend = forms.CharField(label='CEP') endereco_atend = forms.CharField(label='Rua') bairro_atend = forms.CharField(label='Bairro') profile_pic = forms.ImageField(label='Foto') class Meta: model = DadosProfissionais fields = ['nome_publico', 'nome_consult', 'cep_atend', 'endereco_satend', 'bairro_atend', 'profile_pic'] I do not know how the correct way to prepolute the form and also load this image profile url in this template. … -
Connecting Django and Postgres: FATAL authentication error
I'm trying to use PostgreSQL in my Django project. When I run sudo su - postgres I received the following output: (venv) jacquelinewong@Jacquelines-MBP spiderdjango % sudo su - postgres Password: /etc/zshrc:source:76: no such file or directory: /Library/PostgreSQL/12/.bash_profile postgres@Jacquelines-MBP ~ % psql Password for user postgres: psql (12.3) Type "help" for help. I'm on Mac. So it seems the psqlshell does work, but there's an issue with .bash_profile. And when I exit the shell and type in python manage.py makemirgations, here's what I got (venv) jacquelinewong@Jacquelines-MBP spiderdjango % python manage.py makemigrations Traceback (most recent call last): File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "spiders" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/jacquelinewong/Downloads/orbit/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute … -
How to dynamically load data in django
I've been learning django for the last couple of days and I'm trying to build a very simple app that consists on the following: models.py class Stock(models.Model): date = models.DateField() price = models.IntegerField() views.py def index(request): list_dates = Stock.objects.order_by('date').values_list('date', flat = True).distinct() my_dict = {'list_dates' : list_dates} return render(request, 'stocks/index.html', context = my_dict) index.html <body> <select name="date" id="date"> <option value="select">Select Data</option> {% for date in list_dates %} <option value="{{date}}">{{date}}</option> {% endfor %} </select> <h1>{{price here}}</h1> </body> This is a very simplified version of the final concept, which will have many more fields other than price What I want to do is: Get the date the user selected on the select tag Use it to access the django database and then only load the price that matches the selected date Insert it inside the h1 tag Refreshing this when the date is changed on the select tag What's the easiest way to do this? Thanks! -
Static files not loading
url inside main 'mySite' directory urlpatterns = [ path('admin/', admin.site.urls), path('coming-soon/', include('comingSoon.urls')), ] url inside comingSoon app directory urlpatterns = [ path("", views.index, name="coming-Soon") ] views.index inside comingSoon app def index(request): return render(request, 'comingSoon/coming-soon.html') inside template "coming-soon.html' <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>Pitnik Social Network Toolkit</title> <link rel="icon" href="images/fav.png" type="image/png" sizes="16x16"> {% load static %} {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/main.min.css'}"> <link rel="stylesheet" href="{% static 'css/style.css'}"> <link rel="stylesheet" href="{% static 'css/color.css'}"> <link rel="stylesheet" href="{% static 'css/responsive.css'}"> </head> <body> <div class="theme-layout"> <div class="gap2 mate-black medium-opacity vh100"> <div class="bg-image" style="background-image:url(images/resources/coming-soon-bg.jpg);"></div> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="coming-head"> <div class="logo"> <a href="index.html" title=""><img src="images/logo.png" alt=""></a> </div> <ul class="social-circle "> <li><a class="facebook-color" href="#" title=""><i class="fa fa-facebook"></i></a></li> <li><a class="twitter-color" href="#" title=""><i class="fa fa-twitter"></i></a></li> <li><a class="google-color" href="#" title=""><i class="fa fa-google-plus"></i></a></li> <li><a class="vk-color" href="#" title=""><i class="fa fa-vk"></i></a></li> </ul> </div> <div class="coming-meta"> <h1>We're Coming!</h1> <p>We are working hard to bring you new experience</p> <ul class="countdown"> <li><span class="days">00</span><p class="days_ref"></p></li> <li> <span class="hours">00</span><p class="hours_ref"></p></li> <li> <span class="minutes">00</span><p class="minutes_ref"></p></li> <li> <span class="seconds">00</span><p class="seconds_ref"></p></li> </ul> <form method="post"> <input type="text" placeholder="Submit inquiry..."> <button type="submit"><i class="fa fa-arrow-right"></i></button> </form> </div> </div> </div> </div> </div> … -
Download data as Excel file in Django with ajax
on the page with ajax code, there is a form that I filter. I am sending the filtered data to download_excel method with ajax, but the download is unsuccessful. What is the reason? view.py def download_excel(request): jsdata = request.GET.get('listed_data') objdata = eval(jsdata) #objdata = [{"id":"123123123","location":"test_location_1","device":"test_device_1","datetime":"12/12/2020","name":"asdas asdas","age":"21","gender":"male","temp":"37.6","mask":"0",risk":"1"},{"id":"123123123","location":"test_location_1","device":"test_device_1","datetime":"12/12/2020","name":"asdas asdas","age":"21","gender":"male","temp":"37.6","mask":"0",risk":"1"}...] response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = "attachment; filename='Report.xls'" wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("Report") row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ["ID","Location","Device","Datetime","Full Name","Age Range","Gender","Body Temp","Mask","Risk"] for col_num in range(len(columns)): ws.write(row_num,col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() for row in objdata: row_num += 1 ws.write(row_num, 0, str(row["id"]), font_style) ws.write(row_num, 1, row["location"], font_style) ws.write(row_num, 2, row["device"], font_style) ws.write(row_num, 3, row["datetime"], font_style) ws.write(row_num, 4, row["name"], font_style) ws.write(row_num, 5, row["age"], font_style) ws.write(row_num, 6, row["gender"], font_style) ws.write(row_num, 7, row["temp"], font_style) ws.write(row_num, 8, row["mask"], font_style) ws.write(row_num, 9, row["risk"], font_style) wb.save(response) return response urls.py path('ajax/download_excel/', views.download_excel, name="download_excel") template html function download_excel(){ $.ajax({ url: "/events/ajax/download_excel/", data:{ 'listed_data': "{{data|safe}}" } }) } -
Render a Multipage Excel File
There is a library called templated-docs that allowes render templates to different file formats. My goal is to render multipage Excel file: I have an .ods template which looks like this: Also have a list of dicts each for a page: context = [ {"number": 1}, {"number": 2}, ] Rendering of context happens here https://github.com/alexmorozov/templated-docs/blob/master/templated_docs/init.py#L128. As far as I can see context should be a dictionary. And there is no built-in way to render a multipage excel, right? Well, for now everything I could figure out is to render data dicts by one (template.render({"number": 1}), template.render({"number": 2})) and then combine them into a single entity. But I'm not sure this to be a proper way. Could you say please if there is some another ways to solve this problem? P.S. The real file have 15 pages. -
virtualenvwrapper on Mac (using terminal) : Error while finding module specification for 'virtualenvwrapper.hook_loader'
Trying to finish installing virtualenvwrapper. I have already installed Python 3.8.3 and virtualenv/virtualenvwrapper but when I am exporting to setup a virtual environment location using: export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 ' export PROJECT_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh It says there is no directory. So I have changed my source to be /Library/Frameworks/Python.framework/Versions/3.8/bin/virtualenvwrapper.sh because after using which virtualenvwrapper.sh, that is where it is. once I have done this though i get the error virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 and that PATH is set properly. What exactly do I need to change for this environment to work? -
Django Query In Views.py Overriding Another Query In Views.py
I have an issue where the max_views_query if statement qs is overriding the min_views_query if statement qs. How would I prevent the max_views_query if statement qs from overriding the min_views_query qs and keep them separate from each other but still work with the rest of the code? Courses Forms.py: class CourseForm(forms.Form): min_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'min_views', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) max_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_views', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['min_views'].label = "Min Views:" self.fields['max_views'].label = "Max Views:" Courses Views.py: class CourseListView(ListView): model = Course def get_queryset(self): qs = super().get_queryset() self.form = form = CourseForm(self.request.GET) if form.is_valid(): min_views_query = self.request.GET.get('min_views') max_views_query = self.request.GET.get('max_views') if min_views_query: qs = Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__gte=min_views_query) if max_views_query: qs = Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__lte=max_views_query) return qs Courses Models.py: class Course(models.Model): views = models.PositiveIntegerField(default=0) @property def total_lesson_views(self): lessons_dictionary = Lesson.objects.filter(course=self).aggregate(Sum('views')) return lessons_dictionary['views__sum'] class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views = models.PositiveIntegerField(default=0) -
in django template unable to show content inside if block
when i write if statement nothing show in html but when i remove the if statement the code show all items what is wrong {% for catagory in catagory_list %} {% for item in product_list %} {% if item.catagory == "Fruits" %} <p>{{item.catagory}}</p> <p>{{item.name}}</p> <p>{{item.price}}</p> <img src="{{item.image.url}}" alt=""> {% endif %} {% endfor %} {% endfor %} <!-- <p>{{item -
How to get a pk from Django URL into ajax
I have a django url that uses a primary key in it, and I want to be able to reference it in my javascript/ajax snippet. I can't find any examples online though, is this possible or do I need to do something like remove all letters from the url? urls.py path('survey/<int:pk>/record_question/', QuestionRecordView.as_view(), name='survey-question-record'), -
Why is my smooth scrolling function not working?
I'm creating a website using Django, and I want the link in the navbar (when clicked) to smoothscroll to the element that I want. This is what I have: base.html <li> <a class="nav-item nav-link" href = '' class='scroll-about'>About</a> </li> //unrelated elements <script> // scroll into view document.querySelector('.scroll-about').addEventListener('click', function(e) { e.preventDefault(); document.querySelector('.about').scrollIntoView({ behavior: 'smooth' }); }); home.html <div class="about col-12 col-md-6"> <div class="d-flex flex-column align-items-center py-5 text-uppercase"> <h3 class="h3-responsive bg-primary text-center text-white rounded font-weight-bold w-50 px-4 py-2 shadow">About</h3> <h1 data-easy-reveal = "" class = " h1-reponsive font-weight-bold my-5 ml-3">Our vision is for every business to leave its mark on the digital world</h1> <h1 data-easy-reveal = "" class = "down h1-reponsive font-weight-bold ml-3">Our vision is to bring them to the next level </h1> </div> </div> The rest of the code works fine, the Django templating is all fine. I just can't seem to get this scroll function to work. I've tried moving the script around the bottom of the html file, and as well as putting it in the head element of the html file. I've also tried using jQuery smooth scroll and it doesn't work either. Hope someone can help me with this! the jQuery code I tried (in this case … -
models.DoesNotExist [...] matching query does not exist. Result is being found in the DB
I 've found just a few questions about that without any answer. I have this error message when running my django app: Cellar.models.DoesNotExist: LotModel matching query does not exist. What bother me, is that when I try this in the console while debugging (when the program stop at this error message in PyCharm), I do find a correct answer so the matching query does exist! If I change return self.lots.get(birth=self.dt, death=self.dt) by return self.lots.filter(birth=self.dt, death=self.dt).first() this error is not raised... I can't figure why. This error comes from here: class PrimaryItem(Item): is_primary = True class Meta: proxy = True @property def lot(self) -> PrimaryLot: return self.lots.get(birth=self.dt, death=self.dt) # <- line producing the error, note that this is not a multiple results problem I can't find why django is throwing me this, since there is no "real" error. If I change this line by return self.lots.filter(birth=self.dt, death=self.dt).first(), the error is not raised as I said, but after that I will have this line: transfer.starting_lot.children.add(new_lot) giving me this error: AttributeError: 'NoneType' object has no attribute 'children' and guess what? transfer.starting_lot is not None if I manually check that. It seems to be the same problem here. Can it be django-polymorphic (seems to … -
How to name a audio file when saving into server with POST
I've being developing a solution for my webpage with Django and javascript, it's a record button so that the user can send feedback and I can store it into the server. The plan is putting a text input where the user can introduce its name and a file is created with that name. This is my code by now. Can anyone help me with this? Python views.py def voice_request(request): f = open('./Grabaciones/file.wav', 'wb') f.write(request.body) f.close() return HttpResponse('audio received') Javascript part function sendData(data) { let csrftoken = getCookie('csrftoken'); let response=fetch("/salud/voice_request/", { method: "post", body: data, headers: { "X-CSRFToken": csrftoken }, }) } -
I am new in django, I have written function to display latest entered record,But got problem that no output of function is displayed
I have created models in models.py as under: class Student(models.Model): gen_choices = ( ("Male", "Male"), ("Female", "Female"), ("Third", "Third"), ) enrollNo = models.IntegerField(default=add_one) fname = models.CharField(validators=[max_len_check], max_length=26) lname = models.CharField(validators=[max_len_check], max_length=26) gender = models.CharField(max_length=6, choices=gen_choices) dob= models.DateField() address = models.CharField(max_length=256) email = models.EmailField() mobile = models.BigIntegerField() status = models.BooleanField() userID = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField(upload_to="stdimages/", null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return str(self.enrollNo) My views.py contains to display the latest entered data from database as under: def std_info(request): if request.user.is_authenticated: result = Student.objects.latest('created_at') pars = {'result': result} return render(request, 'std_info.html', pars, {'title': 'Student registration Success'}) else: messages.info(request, 'You need to Login first.') return redirect('/user/logout') My urls.py contains as under details: path('std_info/', std_info, name='std_info'), My templates contains details as under: {% extends 'user/layout1.html' %} {% block content %} <table width="100%"> <tr> <td align="left" width="80%"><a href="/user/add/"><h1>Congratulation! Entrance Exam Form Registered Successfully.</h1></a></td> <td align="right" width="30%"><a href="/user/home">CLOSE</a></td> </tr> </table> <hr> <br> <font color="blue" size="4" face="times newroman"><u><b>To Generate 'Entrance Exam Hall Ticket' Enter Enroll No. and click on [GENERATE HALL TICKET]:</b></u></font><br> <form action="/user/hall_ticket1" method="GET"> {% csrf_token %} <!--<div class="form-row"><label for="enrollno1">Enroll No.</label></div>--> <div class="form-row"><input type="enrollno1" id="enrollno1" name="enrollno1" placeholder="Enter Enroll No."> <input … -
Check for string in queryset within a Django template
I know this should be straight-forward, but for some reasons I'm not getting the results I want. This instruction: {{user.profile.role.all}} in my Django template outputs this: <QuerySet [<Role: Creator>, <Role: Performer>, <Role: Venue>]> I'd like to check if a role is within this queryset; so, for instance, if I want to check if a role 'venue' is present, according to what the documentation tells me, I should do: {% if "Venue" in user.profile.role.all %} Right? The above-mentioned if, though, returns false. Why is that? -
Selecting only non null fields from the filter rows django
I have this query which are getting the required rows which i want but the problem is most fields/columns have null values I just want to get only those fields from these rows which have non null values queryset = User.objects.filter(email__exact=email) Here, is my model class User(models.Model): email = models.CharField(max_length=50, null=True, blank=True) password = models.CharField(db_index=True, max_length=40, null=True) source = models.CharField(default='unknown', max_length=150, null=True) domain = models.CharField(max_length=50, null=True, blank=True) before_at = models.CharField(max_length=255, null=True, blank=True) username = models.CharField(db_index=True, max_length=150, null=True, blank=True) hash = models.CharField(max_length=255, null=True, blank=True) ipaddress = models.CharField(max_length=50, null=True, blank=True) phonenumber = models.CharField(max_length=100, null=True, blank=True) def __str__(self): if self.email != None: return self.email elif self.username != None: return self.username -
File upload field doesn't display (Django)
I have a django form, but it's not showing the "upload file" field when I render it on my website. What am I doing wrong? Ideally, the form has a question ID associated with it that's submitted automatically (e.g. it doesn't have to be manually put in by the user when uploading the file) models.py class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) response_file = models.FileField(upload_to='audio_responses') forms.py class PostAudio(forms.ModelForm): class Meta: model = Choice fields = ('response_file',) views.py def QuestionRecordSubmitView(request, pk): model = Question if request.method == 'POST': form = PostAudio(request.POST, request.FILES) if form.is_valid(): form.instance.question_id = pk form.save() # get survey pk question_instance = Question.objects.get(pk=pk) survey_pk = question_instance.survey.pk return redirect('survey-share',pk=survey_pk) else: form = PostAudio() return render(request, 'survey/question_audio_submit.html') html {% extends "landing/base.html" %} {% block content %} <h2>New Submission</h2> <form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock content %} -
How to set default group group for users in Django Rest Framework?
I would like to automatically assign the newly registered user to the "User" group. So the group "User" should be the default group for all users. Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'groups') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): groups_data = validated_data.pop('User') user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) for group_data in groups_data: user.groups.add(group_data) return user Register API # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) [1] }) When i run the code i get an error: Bad Request: /api/auth/register. I can not really trace back where my mistake is? Im happy for any clarification. -
django docker-compose failed can't find static
So this is my backend Dockerfile it can't find backend/static what is wrong here? FROM python:3.8.0-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip ADD requirements.txt /app/ RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt -r requirements.txt COPY scripts/start*.sh / ADD . /app/ CMD ["python3", "backend/manage.py", "collectstatic", "--no-input"] CMD ["python3", "backend/manage.py", "makemigrations"] CMD ["python3", "backend/manage.py", "migrate", "--no-input"] CMD ["gunicorn", "backend.wsgi", "-b", "0.0.0.0:7000"] and this is my frontend Dockerfile # build stage FROM node:14.3.0-alpine3.10 as build-stage WORKDIR /app/ COPY frontend/package.json /app/ RUN npm cache verify RUN npm install COPY frontend /app/ RUN npm run build # production stage FROM nginx:1.17.10-alpine as production-stage COPY nginx/prod/prod.conf /etc/nginx/nginx.conf COPY backend/static /usr/src/app/static/ COPY --from=build-stage /app/dist /dist/ EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] if you need more info(docker-compose file): https://github.com/Kenan7/djangorf-vue-ecommerce/tree/gcloud ALSO, does GCP support docker-compose.yml file? if not what do I convert it into? -
How do I resolve a non-interactive object in Django
error_template Some answers that I have seen here mention that it has to do with the dictionary and the keywords of the same that interact with the template, ** but ** the error is that you cannot interact with Downloads, I do not understand that it has to do something with the other one. Models class Repositories(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) url = models.TextField(blank=True, null=True) class Downloads(models.Model): category_name = models.CharField(max_length=125, null=False, blank=False) category_url = models.TextField(null=False, blank=False) download = models.BooleanField(default=False) register_date = models.DateField(auto_now=True) harvest_date = models.DateField(null=True, blank=False) number = models.IntegerField(null=True, blank=False) repository = models.ForeignKey(Repositories, models.CASCADE, db_column='repository') class Raw(models.Model): raw_html = models.TextField() process = models.BooleanField(default=False) identifier = models.ForeignKey(Identifiers, models.DO_NOTHING, db_column='identifier') download = models.ForeignKey(Downloads, models.DO_NOTHING, db_column='download') View def rawPendientes(request): cntxtRaw = {} metaDataPendiente = [] rawPendientes = Raw.objects.filter(process=0) for raw in rawPendientes: # Con la FK se busca la categoria categoria = Downloads.objects.get(id = raw.download.id) # print(categoria.__str__) # Con la FK de la Categoria se busca el Repo repo = Repositories.objects.get(id = categoria.repository.id) totalProcesadoCategoria = Raw.objects.filter(process=1, download= categoria.id).count() totalPendienteCategoria = Raw.objects.filter(process=0, download= categoria.id).count() metaDataPendiente.append((repo, categoria, totalProcesadoCategoria, totalPendienteCategoria)) cntxtRaw = { 'metaDataPendiente': metaDataPendiente, } return render(request, "home_process.html", cntxtRaw) The queries I do with the foreign keys FK in case suddenly there … -
How I can upload file in django, and access to the file content?
I tried this code but it doesn't work, I tried to add files from admin panel it works but when I create a new form it doesn't submitted this is my code, any help: views: class PostCreateView(LoginRequiredMixin, CreateView): model = Post #fields = ['title', 'content', 'XMLcontent'] template_name = 'blog/new_post.html' form_class = PostCreateForm success_url = reverse_lazy('new_post') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() XMLcontent = models.FileField() post_date = models.DateTimeField(default=timezone.now) rate = models.FloatField(null=True, blank=True) post_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def display_text_file(self): with open(self.XMLcontent.path) as fp: return fp.read().replace('\n', '<br>') def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', args=[self.pk]) forms: class PostCreateForm(forms.ModelForm): title = forms.CharField(label='title ') content = forms.CharField(label='content ', widget=forms.Textarea) XMLcontent = forms.FileField(label='structured content ') class Meta: model = Post fields = ['title', 'content', 'XMLcontent']