Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve the error target script cannot be loaded as python module when django app deploy without port number
enter code hereWhen i deploy django app on aws ec2 instance using ubuntu 16.04 server then it gives an error: Sun May 05 16:13:25.466264 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] mod_wsgi (pid=5649): Target WSGI script '/var/www/html/simple_django_project/django_project/django_project/wsgi.py' cannot be loaded as Python module. [Sun May 05 16:13:25.466312 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] mod_wsgi (pid=5649): Exception occurred processing WSGI script '/var/www/html/simple_django_project/django_project/django_project/wsgi.py'. [Sun May 05 16:13:25.466388 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] Traceback (most recent call last): [Sun May 05 16:13:25.466409 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] File "/var/www/html/simple_django_project/django_project/django_project/wsgi.py", line 12, in [Sun May 05 16:13:25.466413 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] from django.core.wsgi import get_wsgi_application [Sun May 05 16:13:25.466429 2019] [wsgi:error] [pid 5649:tid 140262036731648] [remote 157.50.50.61:56646] ImportError: No module named 'django' 000-default.conf <VirtualHost *:80> ServerName pythontestdjangoapp.tk ServerAlias www.pythontestdjangoapp.tk DocumentRoot /var/www/html/simple_django_project ErrorLog/var/www/html/simple_django_project/django_project/logs/error.log CustomLog /var/www/html/simple_django_project/django_project/logs/debug.log combined <Directory /> #Options FollowSymLinks Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> <Directory /var/www/html/simple_django_project/django_project/django_project/> <Files wsgi.py> AllowOverride All Require all granted </Files> </Directory> WSGIDaemonProcess django_project python- path=/var/www/html/simple_djnago_project/django_project python- home=/var/www/html/simple_django_project/myvenv WSGIProcessGroup django_project WSGIScriptAlias / /var/www/html/simple_django_project/django_project/django_project/wsgi.py </VirtualHost> When i start apache server then it gives me an internal server error -
IntegrityError: duplicate key value violates unique constraint in Model.objects.create(...)
I'm not sure what is happening but create method started raising IntegrityError: duplicate key value violates unique constraint "clients_client_pkey" When trying to create a Client. I'm not putting id nor pk attribute to the create method. I've recently loaded some fixtures from CSV, there were clients with their id values so maybe it has some causality. Client.name was unique but I made it not unique and migrated the DB. snippet IntegrityError: duplicate key value violates unique constraint "clients_client_pkey" DETAIL: Key (id)=(25) already exists. The above exception was the direct cause of the following exception: IntegrityError Traceback (most recent call last) ~/PycharmProjects/project2/project2/apps/internals/stats/fixtures/stats.py in <module> ----> 1 load_realestates(delete_old=True) ~/PycharmProjects/project2/project2/fixtures/alex1_csv_loader.py in load_realestates(delete_old) 43 c = Client.objects.get(name=line['majitel_meno'],broker_id=line['makler']) 44 except: ---> 45 c = Client.objects.create(name=line['majitel_meno'],broker_id=line['makler']) Where can be the thing? -
Django - Unique upload filenames regardless of file extension
I want to create unique filenames for each uploaded file (Similar to this), but regardless of the extension (ie, name.txt and name.dxf is a clash) I'm converting files on my server (ie, ogg, wav, etc) to a particular filetype extension, ie. mp3, and then removing the original file. This issue is if someone uploads a file with different extension but the same base name, then the conversion will override the original file. I can obviously do a check if the target file already exists. I know Django will also generate some sort of unique identifier (appended to the uploaded filename) such as "_HVk3AIt" if there is a conflict with an exact filename match. Is this a UUID? I originally though adding a randomly generated UUID would be a bad solution because even though 2^128 is like 4*10^38 (little chance of clash) you could technically override something eventually, but I guess you just keep checking the new proposed filename, and add secondary UUID if you've got a second collision etc. Is this a good solution, or what is standard practise for such a problem? -
What is the easiest method to search in ModelChoiceField or ModelMultipleChoiceField?
I m beginner in django and i m working to a project wich contains manytomany fields and foreignkey fields. Right now i m search a method in template to search in ModelMultipleChoiceField and ModelChoiceField then select that value then submit Can anyone help me with an advice? Thanks! -
django filter not working with date range
Here i am trying to filter students with joined month and year. But when i select year only it throws an error: int() argument must be a string, a bytes-like object or a number, not 'NoneType' and when I select month only then all the students data displays. And when i select both month and year it displays no data. models.py class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) teacher = models.ManyToManyField(Teacher) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateTimeField(auto_now_add=True) views.py def filterstudent(request): year = request.GET.get('year') month = request.GET.get('month') if not year and not month: return redirect('students:view_student') if year and month: month_selected = calendar.month_name[int(month)] year_now = datetime.datetime.today().year students = Student.objects.filter(Q(joined_date__year=year) & Q(joined_date__month=month)) return render(request, "students/view_students.html", {'students': students,'year_selected':year, 'month_selected':month_selected, 'year_list':range(2016,year_now+1)}) elif year or month: month_selected = calendar.month_name[int(month)] year_now = datetime.datetime.today().year students = Student.objects.filter(Q(joined_date__year=year) | Q(joined_date__month=month)) return render(request, "students/view_students.html", {'students': students, 'year_selected':year, 'month_selected':month_selected, 'year_list':range(2016,year_now+1)}) template <form action="{% url 'students:filter_student' %}" class='form-inline'> <!--<label for="month"></label>--> <select name="year" > <option disabled selected>{% if year_selected %}{{year_selected}}{% else %}Select Year{% endif %}</option> {% for year in year_list %} <option value="{{year}}">{{year}}</option> {% endfor %} <!--<option value="2017">2017</option>--> <!--<option value="2019">2019</option>--> </select> <!--<label for="month"></label>--> <select name="month" > <option disabled selected>{% if month_selected %}{{month_selected}}{% else … -
Django Form request method is always GET, even method="POST" is supplied from templated
I am passing two parameters from views to form's init method with POST request from form of templates. But It always gets a GET method. Here is my code : views.py form = formA(team_one=team_one, team_two=team_two) print(request.method) if request.method == 'POST': team_one = match_obj.first().short_team_one team_two = match_obj.first().short_team_two forms.py class formA(forms.Form): team_one = "" team_two = "" def __init__(self, *args, **kwargs): team_one = kwargs.pop("team_one") team_two = kwargs.pop("team_two") super(formA, self).__init__(*args, **kwargs) obj = Detail.objects.filter(Q(current_one=team_one) | Q(current_two=team_two),) for o in obj: self.fields[o.name] = forms.BooleanField() Please HELP! -
Django - CustomQuerySet only works in objects
I'm using a CustomQuerySet using Custom QuerySet and Manager without breaking DRY?. I can only access custom functions using objects. Here's my Code: class CustomQuerySetManager(models.Manager): """A re-usable Manager to access a custom QuerySet""" def __getattr__(self, attr, *args): print(attr) try: return getattr(self.__class__, attr, *args) except AttributeError: # don't delegate internal methods to the queryset if attr.startswith('__') and attr.endswith('__'): raise return getattr(self.get_query_set(), attr, *args) def get_query_set(self): return self.model.QuerySet(self.model, using=self._db) class SampleModel(models.Model): objects = CustomQuerySetManager() class QuerySet(models.QuerySet): def test(self): print("test function was callsed") With this these happens: SampleModel.objects.test() # This works SampleModel.objects.all().test() # This doesnt works... Why does this happen? -
Whats the right way to get the current user logging in using angular and django-rest-framework?
Im using Angular as frontend and Django as backend. When fetching the logged in user, there is a small lag or "flickering" in the username displayed in the top menu due to the Angular having to ask the backend for the user data, after receiving the token and wait for the promise to return the user data. To authenticate and log in i use django rest framework: url(r'^token-auth/', obtain_auth_token) This returns a Token - all works well and Im logged in. But this call doesnt return any user data, so to solve this I created a separate api view that returns the user. A service in Angular is triggered to fetch the user data directly after receiving the token. But to do that Angular has to call the user view separately and that in turn can lead to "lag" in the way that the users data wont load instantly in the menu upon login (because Angular has to fetch the users data again, after receiving the users token on the first call). This got me thinking, what is the best way to get the logged in user data after receiving the Token and "beeing logged in"? Is there a better … -
On click (image/button) store data in ... to render another html template live
I would like to retrieve the img.id or img.alt data when an image is clicked in my (x.html) template. The retrieved data will then be used to fill another template (dashboard.html). My only question is how to retrieve the data on an 'onclick' event. Once i have the data stored somewhere, I will be able to figure out how to fill another template based on that information. And does your answer change if i would add that the 'dashboard.html' should be a live stat dashboard. I already have my js.js active, but i cannot find the correct function for it and the appropriate reference in the html. I tried several javascript/ajax solutions, but since i am not that skilled in js I was unable to get the function/javascript working on my page. Below the html (x.html) in which i would like to add a onclick function on each image that is imported via views. {% include 'navigation.html' %} <div id="Content"> <div id="List-Content"> <!--- All_Test --> {% for key, value_list in Drank.items %} <div id ="Content-List"> <div id ="Title-Box"> <h1 class="hero_header">{{ key }}</h1> </div> {% for value in value_list %} <div id ="Menu-Item"> <div id ="Menu-Item-Wrap"> <img style="margin: 0 auto;" src="{{ … -
There is no module django.core when starting a project
Hi am struggling for over 12 hrs with python 2.7, I was working with python 3.7 so i decided to change to 2.7 for a certain reason ,so i uninstalled 3.7 and installed 2.7 But after activating the virtual environment cant start a project with this error. I went through all the procedures here but i could not fix the problem. The strange thing I tried to install django outside the virtual environment later seems to work fine but i think this is inappropriate help out Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\cipher>pip install virtualenv Collecting virtualenv Installing collected packages: virtualenv Successfully installed virtualenv-16.5.0 C:\Users\cipher>virtualenv market New python executable in C:\Users\cipher\market\Scripts\python.exe Installing setuptools, pip, wheel... done. C:\Users\cipher>cd market C:\Users\cipher\market> .\Scripts\activate (market) C:\Users\cipher\market>pip install django==1.5.4 Collecting django==1.5.4 Installing collected packages: django Successfully installed django-1.5.4 (market) C:\Users\cipher\market>django-admin.py startproject market Traceback (most recent call last): File "C:\Users\cipher\market\Scripts\django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core (market) C:\Users\cipher\market> -
AssertionError: The `.create()` method does not support writable nested fields by default
I'm trying to perform a create in Django Rest Framework using a writable nested serializer. With the code below, I want to create dispatcher but it doesn't allow me to create dispatcher. What wrong I did in create serializers so that it doesn't allow me to create the dispatcher. Thank You !!! Serializers.py from django.contrib.auth import get_user_model from rest_framework import serializers from dispatcher.models import Dispatcher from dispatcher.models import DispatacherDocument User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password',) class documentserializers(serializers.ModelSerializer): class Meta: model = DispatacherDocument fields = [ 'dispatcher_document' ] read_only = True Dispatcherserializers(serializers.ModelSerializer): dispatcher_document = documentserializers(required=False) user = UserSerializer(required=True) class Meta: model = Dispatcher fields = [ "user", "disptacher_email", "disptacher_type", "phone_number", "address", "pan_number", "company_type", "dispatcher_document", ] def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) dispatcher_data = validated_data.pop('dispatcher_document ') dispatcher_document = documentserializers.create(documentserializers(), validated_data=dispatcher_data) print(validated_data) dispatcher, created = Dispatcher.objects.update_or_create(user=user, dispatcher_document=dispatcher_document, disptacher_email=validated_data.get( 'dispatcher_email'), disptacher_type=validated_data.get( 'dispatcher_type'), phone_number=validated_data.get('phone_number'), address=validated_data.get('address'), pan_number=validated_data.get('pan_number'), company_type=validated_data.get('company_type'), ) return dispatcher -
how can I display the today and now buttons in Django event form
I have created this event form. how can I display the Today and now buttons in the template of this form? class TaskForm(forms.ModelForm): class Meta: model = Task fields = 'all' # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } # widgets = { # 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M') , # 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), # } # fields = ('assignee','Task_Details', 'description','start_time','end_time') def init(self, *args, **kwargs): super(TaskForm, self).init(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) -
I how write if condition inside the json+ajax + table
I am facing the issue in writing the if condition in the td part var output = "" + "" + "" + "Report Date" + "Group Name" + "Group Status" + "Plan Name" + "Plan Status" + "DC" + "CRA" + "Suspended" + "Year End" + "Effective" + "Run Out" + "Employees" + "Dependents" + "" + "" + ""; for (var value in (data.queryset)) { output += "<tr>" + "<td>" + data.queryset[value].generated_date + '</td>' + '<td>' + data.queryset[value].group_name + '</td>' + '<td>' + data.queryset[value].group_status + '</td>' + '<td>' + data.queryset[value].plan_name + '</td>' + '<td>' + data.queryset[value].plan_status + '</td>' + {#'<td>' + data.queryset[value].debit_card + '</td>' +#} '<td>' + if (data.queryset.debit_card === 1) {None}else if (data.queryset.debit_card === 2) {Rx } else (data.queryset.debit_card === 3) {Full} + '</td>' + '<td>' + data.queryset[value].cra + '</td>' + '<td>' + data.queryset[value].claims_suspended + '</td>' + '<td>' + data.queryset[value].year_end + '</td>' + '<td>' + data.queryset[value].effective_date + '</td>' + '<td>' + data.queryset[value].termination_run_out_days + '</td>' + '<td>' + data.queryset[value].count_of_Employees + '</td>' + '<td>' + data.queryset[value].count_of_Dependents + "</td>" + "</tr>"; } output += "</tbody></table>"; displayResources.html(output); displayResources.find('#report').DataTable(options); setTimeout(() => { $('#main-content').show(); _this.html('Generate Report') }, 2000); }, error: function(error){ -
Why can't I run my Django project using PostgreSQL? WINDOWS10
First of, I'm on Windows 10. I just started learning Django. I did the tutorials that are with the Django documentation. I need to program an app that uses a PostgreSQL database (deadline is next Sunday! It's supposed to be a test following up a job interview, so I don't want to mess this up ^^). When I run the command "python manage.py runserver", I run into the following error : d:\Utilisateur\Documents\code\code_python\Django\Psycle_test\mysite>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\psycopg2\__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The Django documentation says that I need to install psycopg2. Which I did using the command "pip install psycopg2". I configured settings.py in my Django project in order to use a PostgreSQL database : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': … -
Why is ORM filter acting different in shell and server (both in production and development)
Using Django 2.2 and Postgres database. I'm supposed to show a product page, where someone chooses product attributes and then the view fetches the product variant based on the attributes. When I run a double filter based on two ManytoMany attributes in shell it works fine and returns the single product variant, but when it is run by the view the second filter is ignored and it returns multiple. I've tried this on both my machine (manage.py runserver / shell) and in the production environment (gunicorn vs shell). I've tried to filter by multiple methods, and second filter is always ignored. models.py relevant data class VariantType(models.Model): name = models.CharField(max_length=200, db_index=True) class VariantValue(models.Model): name = models.CharField(max_length=200, db_index=True) var_type = models.ForeignKey(VariantType, related_name='value', on_delete=models.PROTECT) class Product(models.Model): (info fields for product) class VariantProduct(models.Model): master = models.ForeignKey(Product, related_name='variants', on_delete=models.PROTECT) variant = models.ManyToManyField(VariantValue, related_name='products') (info fields for VariantProduct) views.py @require_POST def var_manage(request, product_id): data = request.POST sizevar = VariantValue.objects.get(id=data.get('size')[0]) colorvar = VariantValue.objects.get(id=data.get('colour')[0]) product = get_object_or_404(Product, id=product_id) var_product = product.variants.filter(master=product, variant=sizevar).filter(variant=colorvar) (further action with var_product) manage.py shell #set POST data manuall data = {'csrfmiddlewaretoken': ['...'], 'size': ['18'], 'colour': ['13'], 'items': ['1']}; sizevar = VariantValue.objects.get(id=data.get('size')[0]); colorvar = VariantValue.objects.get(id=data.get('colour')[0]); product = get_object_or_404(Product, id=product_id); var_product = product.variants.filter(master=product, variant=sizevar).filter(variant=colorvar); if I … -
How to get foreign key in views from django template?
I'm unable get the field name under cleaned_data for the form, as the field is coming under data for request.POST views.py def newProjectView(request): if request.method == 'POST': projectForm = ProjectInsertionForm(request.POST) if projectForm.is_valid(): jobDesc = projectForm.save(commit=False) jobDesc.save() messages.success(request, message="Succefully saved the Project.") return redirect('accounts:profile') else: messages.error(request, message='Unable to save the project, Please do check the details. \n%s \n%s' % (projectForm.cleaned_data, projectForm.data)) return redirect('accounts:profile') forms.py class ProjectInsertionForm(forms.ModelForm): class Meta: model = CompanyDesc fields = ('companyDets', 'title', 'details') models.py class CompanyDesc(models.Model): companyDets = models.ForeignKey(CompanyList, on_delete=models.CASCADE) details = models.TextField() title = models.CharField(max_length=200) def __str__(self): return self.title work.html <p> <form action="{% url 'accounts:newProject' %}" method="POST"> {% csrf_token %} <p><input type="text" name="companyDets" id="id_companyDets" value="{{ company.company }}" class="col-md-12" style="border-radius: 5px; border: 1px solid #d32878; padding: 5px;"></p> <p><input type="text" name="title" id="id_title" class="col-md-12" style="border-radius: 5px; border: 1px solid #d32878; padding: 5px;"></p> <p><input type="text" name="details" id="id_details" class="col-md-12" style="border-radius: 5px; border: 1px solid #d32878; padding: 5px;"></p> <p><input type="submit" class="razo-btn" value="Save Job"></p> </form> </p> In this example title and details are showing under cleaned data, but companyDets attribut was not in the cleaned data Am I doing anything wrong...? -
Django: how to over ride CheckboxSelectMultiple
I am using Materialize CSS and Django. However Django displays checkboxes in a way Materialize does not understand, so they do not render. How an I override CheckboxSelectMultiple to make it render correctly? I found a question similar to my one but using Bootstrap: Overriding django's CheckboxSelectMultiple widget for Awesome Bootstrap Checkboxes Perhaps something similar can be implemented for Django? Django displays like this: <label for="id_day_2"> <input type="checkbox" name="day" value="Tue" id="id_day_2">Tue</label> But Materialize CSS expects it like this: <input type="checkbox" id="id_day_2" name="day" value="Tue" /> <label for="id_day_2">Name</label> So how can I over ride the widget in order to get Django to display the code the way Materialize wants it? -
Getting MultiSelectField selected items in views.py with query
I am writing a method in views.py that should return a list of Artist objects by country and genre. I have this code in models.py: GENRES = ((1, 'Alternative'), (2, 'Blues'), (3, 'Classical'), (4, 'Country'), (5, 'Disco'), (6, 'Drum and Bass'), (7, 'Dubstep'), (8, 'EDM'), (9, 'Electronic'), (10, 'Experimental'), (11, 'Folk'), (12, 'Funk'), (13, 'Garage'), (14, 'Grime'), (15, 'Hardstyle'), (16, 'Heavy Metal'), (17, 'Hip Hop'), (18, 'House'), (19, 'Indie'), (20, 'Jazz'), (21, 'Multi-Genre'), (22, 'Pop'), (23, 'Punk'), (24, 'R&B'), (25, 'Reggae'), (26, 'Rock'), (27, 'Ska'), (28, 'Soul'), (29, 'Techno'), (30, 'Trance'), (31, 'Urban'), (32, 'World')) genres = MultiSelectField(choices=GENRES, null=True) country = CountryField(default="Poland") Currently I am looping through all objects and search the ones I need using python: countries_selection = request.POST.get('countriesSelection') genres_selection = request.POST.get('genresSelection') results = [] artists = Artist.objects.all() for artist in artists: if artist.country.name == countries_selection: if artist.genres: for genre in artist.genres.__str__().split(","): if genres_selection in genre: results.append(artist) else: results.append(artist) Obviously this is not a good approach. I want to get the same results by using query. I tried: Artist.objects.filter(genres__contains = 'Rock') But it does not return anything because only keys are saved in the database, not values. For example this query work, but I will not have the key … -
django password_reset doesn't works
I'm trying to add password reset function to my project. But after following the link from the letter I'm redirected to http://127.0.0.1:8000/password_reset_confirm/Mw/set-password/ and there I can see ! [ password_reset_confirm picture ] (https://i.imgur.com/Ca2cFR2.png). So аfter filling in the fields and clicking on the button I get an error. Here is the screenshot of the error ! [error picture ] (https://i.imgur.com/oXbhu47.png) I don't know where I shound search. Here is my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'tankruslan26@gmail.com' EMAIL_HOST_PASSWORD = 'jahhmcmltpqwigik' And the main urls.py path('password_reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), password_reset.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block main_section %} <div class="form-section"> <h2>Восстановление пароля</h2> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-danger">Запросить новый пароль</button> </form> </div> {% endblock main_section %} password_reset_done.html {% extends 'blog/base.html' %} {% block main_section %} <div class="form-section"> <h2>Вы успешно вышли обновили пароль</h2> Ваш пароль был отправлен на почту. </div> {% endblock main_section %} password_reset_confirm.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block main_section %} <div class="form-section"> <h2>Восстановление пароля</h2> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-danger">Установить пароль</button> … -
Django rest framwork : tag serializer
I'm trying to display the contents of a deal containing tags (no problem). But I also want to show the list of deals for a specific tag. deal/serializers.py from rest_framework import serializers from . models import Deal from . . tag.serializers import TagSerializer class DealsSerializer(serializers.HyperlinkedModelSerializer): tags = TagSerializer(many=True, read_only=True, source='tag_set') class Meta: model = Deal fields = ('url', 'id', 'title', 'link', 'tags') tags/serializers.py from rest_framework import serializers from . models import Tag from . . . api.deal.serializers import DealsSerializer class TagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ('url', 'id', 'name') class TagAllSerializer(serializers.HyperlinkedModelSerializer): dea_tags = DealsSerializer(many=True, read_only=True) class Meta: model = Tag fields = ('url', 'id', 'name', 'dea_tags') deal/models.py tag_set = models.ManyToManyField(Tag, related_name='dea_tags') I missed a step because I have an error ImportError: can not import name 'DealsSerializer' -
Face Detection with Flask and Dlib
I want to create a UI for my face recognition code. I am using flask to connect HTML pages to python code. I have one simple machine learning model which will give output. I want to stream camera on the HTML page and display the output there. The following code streams a camera on html page, but after streaming I am not able to connect it to python face recognition code. My python code is in detector function. #Flask code @app.route('/detector1') def detector1(): return render_template('detect_face.html') @app.route('/video_viewer2') def video_viewer2(): return Response(detector(),mimetype='multipart/x-mixed-replace; boundary=frame') I want to show live web camera on HTML page and after clicking button it should give me value predicted by my machine learning model. -
How to change default behavior of serializers
I am doing some stuff with the django restframework. Very basic now, but I like to have my data coming back to me bit differently. This is how I get the response now: [ { "line": "line1", "user_text": "Some text", "topic": "value/xrp" }, { "line": "line2", "user_text": "Some text 2", "topic": "beer/heineken/sale" } ] This is what I like to get: { "line1": { "user_text": "Some text", "topic": "value/xrp" }, "line2": { "user_text": "Some text 2", "topic": "beer/heineken/sale" } } This is my serializer: class LineSerializer(serializers.Serializer): line = serializers.CharField(max_length=16) user_text = serializers.CharField(max_length=16) topic = serializers.CharField() And the model (as reference) class Line(models.Model): display = models.ForeignKey(Display, on_delete=models.CASCADE, related_name='lines') line = models.CharField(max_length=16) user_text = models.CharField(max_length=16, null=True, blank=True) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.line I looked in the rest framework documentation and a bit here on stackoverflow but I could not find an answer yet. If someone has hints for me that would be very much appreciated :) -
Django admin increases response times
I recently added an app to my Django web application. I am baffled at an issue that is occurring. When I add the below admin.py file to the app and deploy the code, response times increase in multiple areas of the site, with many areas unrelated. Is there something wrong about the way the ModelAdmin is written? Has anybody experienced this before? I am running Django 1.11. admin.py: class SubscriberAdmin(admin.ModelAdmin): list_display = ('email',) fields = ('email', 'verified') readonly_fields = ('email', 'verified') list_per_page = 50 admin.site.register(Subscriber, SubscriberAdmin) models.py: class Subscriber(models.Model): email = models.EmailField(null=False, unique=True) activation_key = models.CharField(max_length=64) key_expires = models.DateTimeField(default=get_key_expiration) verified = models.BooleanField(default=False) agency_class = {} agency_type = None @classmethod def send_notifications(cls, agency_type, slugs): """ Sends notification emails to all subscribers. :param agency_type: 'salary' or 'pension' :param slugs: [list of agency slugs] """ cls._set_agency_type(agency_type) subscribers = cls.objects.all() for subscriber in subscribers: subscriber._send_notification(slugs) def _send_notification(self, slugs): # code removed for brevity -
Django: get_context_date is not called in ListView
I have django 2.0 app using class based views. I have overrided the get_context_data to add custom contexts. but is does not work properly. class CollectorListView(LoginRequiredMixin, UserPassesTestMixin, ListView): login_url = '/account/login/' model = Collector template_name = "collectors_list.html" print('this_class_is_called') def test_func(self): try: return self.request.user.giver except Giver.DoesNotExist: return False def get_context_data(self, **kwargs): context = super(CollectorListView ,self).get_context_data(**kwargs) print('context_data_is_running') context['stars'] = 'STARS' return context However, the listview works, it does not call the overriden get_context_data method. in the console I get 'this_class_is_called' message printed, but I don't get the 'context_data_is_running'. -
Uploading multiple profile pictures saving only the last one Django
Initially, this worked fine only uploading one photo, but I have expanded it to three. Each of the 3 photos is clickable, triggering onclick="_upload()" and when the page is saved, the photos should display in their respective places (image, image_two and image_three). But when the page is saved, the last photo that was chosen displays in the image_three slot. Even if I choose a photo by clicking on image (the first image) it displays and saves to image_three, leaving the other two images as default photos. I can obviously go into the backend and manually add the photos, and then they display in their correct spaces client side, however that's not helpful. Am I missing something? Another question hinted at needing an Image class as ForeignKey to Profile but why is that necessary? update image form <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <!-- clickeable first image to upload new photo --> <input type="file" name='image' accept="image/*" class="clearablefileinput" id="id_image" style="display:none"> <a href="#"> <img class="img-thumbnail account-img" src="{{ user.profile.image.url }}" width="240" class="img-fluid mx-auto d-block" onclick="_upload()"> </a> <!-- clickeable second image to upload new photo --> <input type="file" name='image_two' accept="image/*" class="clearablefileinput" id="id_image_two" style="display:none"> <a href="#"> <img class="img-thumbnail account-img" src="{{ user.profile.image_two.url }}" width="120" class="img-fluid mx-auto d-block" …