Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Modelform password validate iteration
I am trying to write Django Modelform to prompt user to register an account with a robust password (contains Uppercase, lowercase, digits and special chars). If the multiple conditions for a password are not met, it will raise multiple field level validation error. For example, if I enter a password "shafin071", the Validation errors should say - The password must contain at least 1 uppercase letter, A-Z. - The password must contain at least 1 symbol But right now I'm not getting the 2nd validation error. 1) Can you please help me find a better iteration that will check all the conditions? 2) How can I use clean() to throw a field level validation error instead of form level? I'm fairly new to coding so some explanation will be appreciated. Thank you! forms.py: import re from django import forms from django.utils.translation import gettext_lazy as _ from .models import Students class StudentRegisterForm(forms.ModelForm): class Meta: model = Students fields = [ 'firstName', 'lastName', 'email', 'password', 'password2', 'street', 'apt', 'city', 'state', 'zipcode', ] labels = { 'firstName': _('First Name'), 'lastName': _('Last Name'), 'password2': _('Confirm Password'), 'Apt': _('Apt/House'), 'zipcode': _('Zip Code'), } widgets = { 'password': forms.PasswordInput, 'password2': forms.PasswordInput } help_texts = { 'password': … -
Sorl-Thumbnail : Clear cache of only one image?
Is it possible to clear cache of only one image from a folder. I need to use this command line : python manage.py thumbnail clear_delete_all but on one image and not on all images. Is it possible to give it an image path or name? Thanks ! -
manage.py migrate cannot access remote MySQL database
I have a Django app on that connects to a remote MySQL database (both on AWS, just different servers). The connection works fine and the app properly interacts with the database (fetches from and adds data to it). However, when I am trying to perform a manage.py migrate, I get the following error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Is there something specific to do for manage.py to interact with the remote database instead of trying to hit a local one (that doesn't exist)? -
Django Rest Framework - Use all query params not part of standard filters as postgres JSON field query
I have a Model (call it Thing), it has 4 fields, thing1, thing2, thing3, thing4. I want to filter normally, using query params, against thing1, and thing2, I don't want to filter against thing3, and thing4 is a JSON Field. All query params not thing1 and thing2 should be combined together to form the filter for thing4 (the JSON field). Right now I have the following: models.py from django.contrib.postgres.fields import JSONField class Thing(models.Model): thing1 = models.CharField() thing2 = models.CharField() thing3 = models.CharField() thing4 = JSONField() views.py class ThingViewSet(viewsets.ModelViewSet): queryset = Thing.objects.all() serializer_class = ThingSerializer filter_fields = ('thing1', 'thing2') class Meta: model = Thing fields = '__all__' def filter_queryset(self, *args, **kwargs): query_dict = self.request.GET.dict() thing4_filter_dict = {} for field, value in query_dict.items(): if field in self.filter_fields: continue thing4_filter_dict['thing4__%s' % key] = value return super().filter_queryset(*args, **kwargs).filter(**thing4_filter_dict) you can then call this using, for example GET http://localhost:8000/things/?thing1=some_value&other_thing=1&some_other_thing=2 And here, other_thing=1 and some_other_thing=2 will be used to filter against the JSONField (thing4) Does anyone have any suggestions on a better way to do this? In the django source code the docs for filter_queryset says something like "you probably don't want to override this method". So I'm wondering is there some other better way I … -
What is diff bw declared-services and service in manifest.yml?
In the manifest.yml for a django application deployed on cloud foundry PAAS, i can see there are two labels for services :declared-services and services . I want to know what is the difference and for Oracle database which is the actual service bound? declared-services: oracle_db: label: oracle-ods plan: shared-nr services: - applogger - oracle_ods - odsui-kerberos-sso -
Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried:
I can't seem to spot the error in my code and I have tried everything. It is probably something simple that is escaping my eye. Please help! Any input is appreciated. New Django learner here. template <header class="w3-container w3-blue"> <h1><a href="{% url 'details' Testimony.id %}"</a>{{testimony.Title}} </h1> </header> models.py class Testimony(models.Model): ... def __str__(self): return int(self.id) urls.py urlpatterns = [ ... path('<int:id>/details/', views.detail, name='details'), ] views.py def details(request, id=None): print('1') testimony=get_object_or_404(Testimony, id=id) print('2') return render(request, 'details.html', {'testimony': testimony}) -
Can internal ip addresses of the worker machines be used to connect the worker to rabbitmq queue?
the two machines the "master rabbitmq queue handler" and the "worker machine are servers of same platform (i.e digitalocean)". Can their internal ips be used to connect them? If yes will it be any faster than the external ip connection? -
passing arguments in django
I am implementing a search function in django and I want to use ListView. how do a pass the search string to my function in views.py? here is my view function that I want to modify: class PersonList(ListView): model=Person context_object_name='persons' and here is the template: <form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" method="post">{% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{name}}"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form>r code here -
How to bind multiple models to one ManyToManyField?
There are,for example, such classes: class A(models.Model): id = models.CharField(max_length=256, primary_key=True) mtm = models.ManyToManyField(B, C, D) class B(models.Model): id = models.CharField(max_length=256, primary_key=True) class C(models.Model): id = models.CharField(max_length=256, primary_key=True) class D(models.Model): id = models.CharField(max_length=256, primary_key=True) I know the implementation class of the field And the wrong, did so to make it clearer. You need to have that model And had a relationship ManyToMany with models b,C,D. How can this be done? Is there a special field? -
Dynamic url for list of charts by category issue (queryset filter)
Django 'CategorisedListView' object has no attribute 'slug' or Page not found (error 404) issue I'm on Django 2.0, using generic class list view. I have tried dynamic url based on slug and queryset filter on slug to get list of charts by category. Please help! I've been stuck here for a couple of days since. views.py class CategoriesView(generic.ListView): template_name = 'Bokeh/categories.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() class CategorisedListView(generic.ListView): model = Category template_name = 'categories/list_of_charts_by_category.html' context_object_name = 'categorised' def get_queryset(self): self.category = get_object_or_404(Category, name = self.kwargs['slug']) return Chart.objects.filter(category=self.slug) models.py class Category(models.Model): name = models.CharField(max_length=100) image_file = models.ImageField(default=None, unique=True) slug = models.SlugField(max_length=100, unique=True) parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True, null=True, related_name='children') def __str__(self): return self.name def get_absolute_url(self): return '{slug}/'.format(slug=self.slug) class Meta: ordering = ('name',) verbose_name = 'Category' verbose_name_plural = 'Categories' class Chart(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(max_length=250) url = models.URLField(default=None, blank=True) embed_url = models.TextField(default=None, blank=True) image_file = models.ImageField(default=None, unique=True) code_file = models.FileField(default=None, blank=True, unique=True) chart_library = models.CharField(max_length=250) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) tag = TaggableManager() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name + ' - ' + self.chart_library def get_absolute_url(self): return reverse('Bokeh:detail', kwargs={'pk': self.pk}) def read_file(self): data = self.code_file.path with open(self.code_file.path, 'r', encoding='UTF-8') … -
How to get response of chatterbot in image/hyperlink format?
Not able to get response of ChatterBot as image/hyper link. I tried to place html image tag in my training data set i.e., . Training data set: image_response_data_set.yml categories: - myown conversations: - - can you show me image link? - <img src="example.jpg" alt="Smiley face" height="42" width="42"> As my tag is considering as a string, it won't show me as image. Can any one help me, how can i train bot to give response as image? Do I need to use any other format instead of .yml? Note: I'm doing this using ChatterBot/examples/django_app from github. -
Django: Creating a new Object from an HTML form
I'm happy to join stackoverflow :) This is my problem/question: I am working on Django (pretty newbie... yet), and I'm building a dynamic website (frontend/backend) just for practice. My problem is that I need to make my site able to build a new Model Object, from an user's HTML Form (tempalte), I have been searching on google for days, but I always find the vice-versa answer to my problem (How to create a new form from a model object). Python version: 2.7.15 Django version: 1.11 My model (in models.py): class Orden(models.Model): nombre = models.CharField(max_length=24, blank=True, null=True) email = models.EmailField() mensaje = models.CharField(max_length=1024, blank=True, null=True) My view (in views.py): def products(request): return render(request, "products.html", {}) In my urls.py: urlpatterns = [ url(r'^$', views.inicio, name='inicio'), url(r'^products/$', views.products, name='products'), url(r'^about/$', views.about, name='about'), url(r'^admin/', admin.site.urls), ] And this is my html template from where I'm trying to make users able to create new objects (from a class called Orden, which means Orders) {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <form enctype="multipart/form-data" method="POST">{% csrf_token %}{{ form.as_p }} <div class="col-sm-8 col-sm-offset-2"> </div> <div class="col-sm-4 col-sm-offset-2"> <input value="{{ nombre }}" id="{{ nombre }}" name="{{ nombre }}" type="text" class="form-control" placeholder="Su nombre" … -
Django: Array value must start with "{" or dimension information
I try to add some array like in the example tags = ArrayField(models.CharField(max_length=200),default=list) I get this error: django.db.utils.DataError: malformed array literal: "" DETAIL: Array value must start with "{" or dimension information. using postgresql_psycopg2... -
One form field alone fails to display value from database
My model: class DirectoryDoctors (models.Model): num = models.AutoField(primary_key=True) name = models.CharField(max_length=100) design_choices = ( ('IMO', 'IMO'), ('AIMO', 'AIMO'), ('Dental Surgeon', 'Dental Surgeon'), ('Regional Deputy Director', 'Regional Deputy Director'), ('Joint Director', 'Joint Director'), ('Director', 'Director'), ('unspecified', 'Unspecified') ) designation = models.CharField( choices=design_choices, max_length=30, default='unspecified') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) email = models.CharField(max_length=50, default='', blank=True) dob = models.DateField(null=True, blank=True) specialiast_or_not_choices = ( ('Yes', 'Yes'), ('No', 'No'), ('Unspecified', 'Unspecified') ) specialiast = models.CharField( choices=specialiast_or_not_choices, max_length=30, default='Unspecified') specialty_choices = ( ('Internal Medicine', 'Internal Medicine'), ('General Surgery', 'General Surgery'), ('ENT', 'ENT'), ('Ophthalmology', 'Ophthalmology'), ('Dermatology', 'Dermatology'), ('Paediatrics', 'Paediatrics'), ('Respiratory Medicine', 'Respiratory Medicine'), ('Psychiatry', 'Psychiatry'), ('Obstetrics and Gynaecology', 'Obstetrics and Gynaecology'), ('Physical Medicine', 'Physical Medicine'), ('Radiodiagnosis', 'Radiodiagnosis'), ('Anaesthesia', 'Anaesthesia'), ('Unspecified', 'Unspecified'), ('Not Applicable', 'Not Applicable') ) specialty = models.CharField( choices=specialty_choices, max_length=30, default='Unspecified') institution = models.ForeignKey(DirectoryHospital, on_delete=models.DO_NOTHING) bloodgroup_choices = (('apos', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ('AB+', 'AB+'), ('AB-', 'AB-'), ('-', '-') ) bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=15, blank=True) spousename = models.CharField(max_length=100, blank=True) children = models.CharField(max_length=200, blank=True) present_address = models.CharField(max_length=200, blank=True) permanent_address = models.CharField(max_length=200, blank=True) class Meta: unique_together = ["name", "mobile", "email"] My form: class DirectoryDoctorsForm(ModelForm): class Meta: model = DirectoryDoctors fields = [ 'name', 'designation', 'mobile', 'alternate', 'email', 'dob', … -
Can I search through Serializer fields instead of Model Fields in ListAPIView?
I have a Serializer which has values from OneToMany and ManyToOne Relation. class A(models.Model): abc = AnyField() bcd = AnfField() class B(models.Model): xyz = ForeignKey(A) pqr = CharField() class C(models.Model): lmn = ForeignKey(A) def = CharField() My Serializers are as follows: class BSerializer(ModelSerializer): class Meta: fields = '__all__' class CSerializer(ModelSerializer): class Meta: fields = '__all__' class ASerializer(ModelSerializer): B = SerializerMethodField() C = SerializerMethodField() class Meta: fields = ('id', 'abc', 'bcd', 'B', 'C') def get_B(self, obj): return BSerializer(queryset=obj.b_set.all(), many=True).data def get_C(self, obj): return CSerializer(queryset=obj.c_set.all(), many=True).data Now, In my views: class AListView(ListAPIView): serializer_class = ASerializer queryset = A.objects.all() search_fields = ('id', 'abc', 'bcd', 'B__pqr', 'C__def', ) I want to search in the serializer fields. Is there a way, where I can search in B's fields or 'C's fields. Using search_fields, I can only search in A's fields (abc, bcd). -
How to get saved value in select tag in generic UpdateView?
I'm editing a form a with generic UpdateView, when i open the form i'm unable to get saved value in select tag other fields are working properly. forms.py class EmployeeForm(forms.ModelForm): city = forms.ModelChoiceField(queryset=city_master.objects.all()) state= forms.ModelChoiceField(queryset=state_master.objects.all()) country = forms.ModelChoiceField(queryset=country_master.objects.all()) class Meta: model=employee_master fields = '__all__' widgets= { 'name':forms.TextInput(attrs={'class':'form-control'}), 'for_station': forms.TextInput(attrs={'class': 'form-control'}), 'contact_no': forms.TextInput(attrs={'class': 'form-control'}), 'email_id': forms.TextInput(attrs={'class': 'form-control'}), 'joining_date': forms.TextInput(attrs={'class': 'form-control'}), 'date_of_birth': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.Textarea(attrs={'class': 'form-control','rows':2, 'cols':10}), 'country': forms.Select(attrs={'class': 'form-control'}), 'state': forms.Select(attrs={'class': 'form-control'}), 'city': forms.Select(attrs={'class': 'form-control'}), 'pin_code': forms.TextInput(attrs={'class': 'form-control'}), 'remarks': forms.Textarea(attrs={'class': 'form-control','rows':2, 'cols':10}), 'active': forms.CheckboxInput(attrs={'class': 'form-check-input'}), } views.py for create and update i am using the same form class EmployeeCreate(CreateView): model = employee_master form_class = EmployeeForm class EmployeeUpdate(UpdateView): model = employee_master form_class = EmployeeForm I expect that country, state and city should appear with saved data when i edit. -
NewConnectionError raise while installing requirements.txt certifi
I try to run docker-compose up to build django app but I got this error message. Building web Step 1/6 : FROM python:2.7 ---> bfa54426aeda Step 2/6 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 52295fd3b228 Step 3/6 : RUN mkdir /deniz1 ---> Using cache ---> dff17bbae4d8 Step 4/6 : WORKDIR /deniz1 ---> Using cache ---> 0f95497fe436 Step 5/6 : ADD . /deniz1/ ---> Using cache ---> 750b3033f58d Step 6/6 : RUN pip install --upgrade -r requirements.txt ---> Running in 0559d5fd6935 Processing ./cve2NVT/PyCVESearch Collecting certifi==2018.4.16 (from -r requirements.txt (line 1)) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070c10>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/certifi/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070450>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/certifi/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070710>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/certifi/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070d50>: Failed to establish a new connection: [Errno -3] Temporary failure in name … -
Proccess data from multiple forms in request.POST
Within my CreateView and UpdateView I am using a form for the main model and multiple forms to directly create/update related models: class MyModelCreateView(CreateView): model = MyModel form_class = MyModelForm MyModelForm instantiates the required forms for the related fields I mentioned within itself. My problem is that when I serialize the data and send it to the view, it doesn't know how to handle the data from the extra forms. When I access to request.POST this data gets discarded. I am serializing the forms like this: let data = $('#main-form').serializeArray(); $('.other-form').each(function() { data.push({name: 'id-' + $(this).data('id'), value: $(this).serializeArray()}); }); This sends the following array to the server (I stringified it here for a clear display): [ { "name": "name", "value": "some name" }, { "name": "id-194", "value": [ { "name": "prop1", "value": "on" }, { "name": "prop2", "value": "some prop" }, { "name": "prop3", "value": "other prop" } ] }, { "name": "id-195", "value": [ { "name": "prop2", "value": "some prop" }, { "name": "prop3", "value": "other prop" } ] } ] However the contents of request.POST are these: <QueryDict: {u'name': [u'some name']}> Notice how all other data is ignored. I can get to send it to the server the … -
Setting local variables in a django model
I have the following model: class MeasurementParameter(models.Model): tolerance = models.FloatField() set_value = models.FloatField() tol_low = None tol_high = None def tolerance_band(self): tol = self.set_value * self.tolerance/100 self.tol_high = self.set_value + tol self.tol_low = self.set_value - tol print self.tol_low return self.tol_high, self.tol_low I wish to set the calculated local variables tol_low and tol_high using the tolerance_band method. The model is has a ManyToMany relationship with another model called Product. class Product(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) parameters = models.ManyToManyField(MeasurementParameter, related_name='measurement') def calc_all_tol_bands(self): for parameter in self.parameters.all(): hi, lo = parameter.tolerance_band() def __str__(self): return self.name So in my view I attempt to calculate all tolerance bands by: product.calc_all_tol_bands() However if I try and get the local variables: product.parameters.all()[0].tol_low I get None all the time. What do I need to do to be able to set calculated values in the MeasurementParameter model? John. -
Django ZoHo Python SDK v2 CRM Problem initialisation
Im trying to integrate the ZoHo crm v2 sdk with my Django app. On the Django runserver, im able to get access tokens and using the refresh method and store them in the zcrm_oauthtokens.pkl file. The sdk then automatically refreshes the access token using the refresh token, so no problem here. However on my production server (heroku) im getting this error message: 2019-01-16T11:07:22.314759+00:00 app[web.1]: 2019-01-16 11:07:22,314 - Client_Library_OAUTH - ERROR - Exception occured while fetching oauthtoken from db; Exception Message::'NoneType' object has no attribute 'accessToken' It seems to me that the tokens are being saved to file, but when the sdk try to access them it is looking for them in a DB and not the file specified in the token_persistence_path. In my settings.py I have this: ZOHO_CLIENT_ID = config('ZOHO_CLIENT_ID') ZOHO_CLIENT_SECRET = config('ZOHO_CLIENT_SECRET') ZOHO_REDIRECT_URI = config('ZOHO_REDIRECT_URI') ZOHO_CURRENT_USER_EMAIL = 'jamesalexander@mylastwill.co.uk' ZOHO_PATH = os.path.join(BASE_DIR, 'wills_online', 'zoho') zoho_config = {'apiBaseUrl': "https://www.zohoapis.com", 'currentUserEmail': ZOHO_CURRENT_USER_EMAIL, 'client_id': ZOHO_CLIENT_ID, 'client_secret': ZOHO_CLIENT_SECRET, 'redirect_uri': ZOHO_REDIRECT_URI, 'token_persistence_path': ZOHO_PATH} and in a views file I have this: from zcrmsdk import * import logging from django.shortcuts import HttpResponse from wills.models import PersonalDetails, ZoHoRecord, WillDocument from wills_online.decorators import start_new_thread from wills_online.settings import zoho_config logger = logging.getLogger(__name__) class ZohoRunOnce: def __init__(self): self.already_run = False … -
How can I create a django model instance with deferred fields without hitting the database?
Say I have some fields of a row of a django Model that I know exists in the database, but don't have them encapsulated in a Model instance. Is there any easy way for me to wrap them in a Model instance, without doing an extra DB query, and end with an instance that has those fields populated but all other fields deferred? So say I have model: from django.db.models import CharField, IntegerField, Model class Person(Model): name = CharField(max_length=20) age = IntegerField(default=10) And I have a dictionary: raw_person = {'id': 3, 'name': 'Alice'} And I want to end with a model instance without another database query: alice = Model(id=3, name='Alice', age=<deferred>) such that doing: alice.name is immediate, but alice.age would require another query to the database to get the age for alice. Obviously (?) I can't just do: alice = Model(id=3, name='Alice') Because that would set age = 10 since that's the default on the field, but that is probably not Alice's actual age. Any ideas? -
Calling a long synchronous function from celery task
Celery async task failed to call a sync module function, from flibrary import Importer @shared_task def autoimport_dataset_task(folder_path): print('Task started') imp = Importer(folder_path) imp.import_all() # it takes long time to execute print('Task Finished') If I invoke the above task synchronously using autoimport_dataset_task(folder_path), it does created an instance for Importer class and invokes import_all instance method but If I call the above task asynchronously, autoimport_dataset_task.delay(folder_path) the task succeeded with None as output but it fails to invoke import_all function, seems like it even fails to instantiate. -
How to fix invalid syntax unknown error in Python django?
I am learning django and started to watch some tutorials, when I add url() function to urls.py, it gives an invalid syntax error urlpatterns = [ url(r'^$', views.home, name='home') url(r'^admin/', admin.site.urls), ] url(r'^admin/', admin.site.urls), ^ SyntaxError: invalid syntax -
Heroku django app crashing with error code H10
My heroku app is crashing with error code H10. I have followed every step from heroku official docs. Here is the log from the app itself State changed from starting to crashed 2019-01-16T10:57:44.464922+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=seatbachao.herokuapp.com request_id=c2c4ee41-f05b-4ec4-a835-3920b64972c1 fwd="157.39.41.104" dyno= connect= service= status=503 bytes= protocol=https 2019-01-16T10:57:45.587098+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=seatbachao.herokuapp.com request_id=4d885a78-5933-493b-a2a4-44f753bd06b4 fwd="157.39.41.104" dyno= connect= service= status=503 bytes= protocol=https -
how to use django-rest-framework to implement a method that can authenticate users and paginate
I saw some ways to implement paging with drf on the Internet.For example, the following method: def get(self, request, format=None): roles = Product.objects.all() pg = PageNumberPagination() page_roles = pg.paginate_queryset(queryset=roles, request=request, view=self) ser = ProductSerializer(instance=page_roles, many=True) return Response(ser.data, status=HTTP_200_OK) But this method only accepts a single number page number in the request query parameters.I hope this method can accept parameters about user information in order to authenticate user rights.