Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JQuery Validate for Django Model Forms
I have looked over this documentation (http://streamhacker.com/2010/03/08/jquery-validation-django-forms/) for some help regarding form validation. In my forms.py I have the following: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'language'] widgets = { 'language': forms.RadioSelect(attrs={ 'class':'{required:true}' }), } So for the language field, I want to serve it as a RadioButton field and I want to make it a required field. So if the user leaves this field empty, then a warning would pop up. Here is my models.py where I defined the language column: LANGUAGE = (('AR', 'Arabic'), ('FR', 'French'), ('ES', 'Spanish')) language = models.CharField(max_length=20, choices=LANGUAGE) Anyways, no warnings pop up when I submit the form even with the language field empty. Any ideas? -
Using and further parsing of form.errors.as_json to return http response in Django
I am relatively new to both JSON and Django forms. And I wonder how Djagno's user_form.errors.as_json() should be used to transfer error messages to client-slde. Right now, I have the following code: On the server-side. I have: if form.is_valid(): # some code else: return JsonResponse(user_form.errors.as_json(), status = 400, safe = False) Client: $.post('/url/', data, function(response){ // Success }).fail(function(response){ var errors = $.parseJSON($.parseJSON(response.responseText)); // looks stupid The akward line $.parseJSON($.parseJSON(response.responseText)); proves that I am doing something wrong. Can anyone provide a best-practice code pattern for sending -
Unable to install mysqlclient using pip3 on MacOS sierra
I want to use mysql in django so, trying to download mysqlclent using $ pip3 install mysqlclient but always this error comes up Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/hb/vmtpfjk12fdcm_8l95hfqzmr0000gn/T/pip-build-pm_wn_w8/mysqlclient/ here are my terminal logs $ pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.9.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/hb/vmtpfjk12fdcm_8l95hfqzmr0000gn/T/pip-build-pm_wn_w8/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/hb/vmtpfjk12fdcm_8l95hfqzmr0000gn/T/pip-build-pm_wn_w8/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/hb/vmtpfjk12fdcm_8l95hfqzmr0000gn/T/pip-build-pm_wn_w8/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/hb/vmtpfjk12fdcm_8l95hfqzmr0000gn/T/pip-build-pm_wn_w8/mysqlclient/ Please help -
Django Allauth google error: SocialApp matching query does not exist
Setting up oauth2 for google with django-allauth getting an error when I click google Can see the login page and the social auth settings the error log below Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py" in dispatch 92. app = provider.get_app(self.request) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/base.py" in get_app 52. return SocialApp.objects.get_current(self.id, request) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/models.py" in get_current 38. provider=provider) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 122. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get 387. self.model._meta.object_name Exception Type: DoesNotExist at /accounts/google/login/ Exception Value: SocialApp matching query does not exist. -
Page not found(404) error on Django
This is my music\urls.py code:- music\urls.py And this is my views.py code:- views.py Now why am I getting a Page not found(404) error whenever I try to open this link 127.0.0.1:8000/music/2/ in browser Please Help! -
Import external files in Django
i am currently working in Django . The values in the settings.py would change depending upon the scenerio . So what i thought was to have a JSON file , that would contain the setting values. So that we can import that file in Settings.py . So whenever there is a change in the settings.py values , it would be enough to change this JSON . How can i do it ? -
django rest POST request has an extra u
My view is as follows: @api_view(['POST']) @parser_classes((JSONParser,)) def addCigar(request, format=None): print(request.data) form = CigarForm() if request.POST: form = CigarForm(request.data) if form.is_valid(): cigar.save() cigar = Cigar.objects.filter(id=cigar.id) serializer = CigarSerializer(cigar, many=True) return Response(serializer.data) else: return Response("Form not valid, insert correct fields.") The print statement prints: {u'origin': u'India', u'rating': u'4', u'strength': u'Strong', u'brand': u'Nitis h', u'aroma': u'Wood', u'shape': u'Thin', u'notes': u'Good'} Why there is this extra u? I always get Form invalid error. In my Angular2 frontend the data that is being sent looks like following: {"brand":"Nitish","origin":"India","shape":"Thin","strength":"Strong","aroma":"Wood","notes":"Good","rating":"4"} -
How to update django template variable without reloading page (AJAX)?
This context processor def cart_proc(request): return (dict(cart=Cart(request))) gives me variable {{cart}} in my template, so I can use {{ cart.count }} in base.html. count is method that count amount of products in cart. This is my js function addProduct(){ $('form.add-product').on('submit', function(){ var link = $(this) var quantity = $(this).find('#id_quantity').val() $.ajax({ 'url': link.attr('action'), 'type': 'POST', 'dataType': 'json', 'data': { 'quantity': quantity, 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val() }, 'success': function(data, status, xhr){ alert('Success'); return false; }, 'error': function(xhr, status, error){ alert('Error on server. Please try again later.'); return false; } }); return false; }); } And my view (I use django-cart for my cart) def add_to_cart(request, id): form = QuantityForm(request.POST) if form.is_valid(): product = Product.objects.get(id=id) quantity = request.POST['quantity'] cart = Cart(request) cart.add(product, product.price, quantity) return JsonResponse({'status': 'success'}) I want to update {{cart.count}} when I add product in cart with AJAX, without page reloading. Now it updating only after reloading. -
Save model forms in django
This is supposed to be a trial run of a sign up form but the database is not storing the username and password. The error I'm getting is "The User could not be created because the data didn't validate". views.py def add_model(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid: model_instance=form.save(commit=False) model_instance.save() forms.py class UserForm(forms.ModelForm): class Meta: model=User fields=['username','password'] models.py class User(models.Model): username=models.CharField(max_length=25, primary_key=True,default="") password=models.CharField(max_length=15,default="") def __str__(self): return self.username -
Django, avoid N+1 query
I have three models in play, and want to avoid N+1 query. class Rule(models.Model): pass class RuleConstraint(models.Model): rules = models.ManyToManyField(Rule) class Foo(models.Model): rule = models.ForeignKey(Rule, related_name='foos') for a given foo, I can get related RuleConstraints like the following RuleContraint.objects.filter(rules__foos=foo) Question is, how do I avoid N+1 query symptom, when I have foos instead of a single foo. ie, is there a better way of doing than for foo in foos: rule_constraints = RuleConstraint.objects.filter(rules__foos=foo) -
unable to resole: type object 'Member' has no attribute '_default_manager, django 1.10
I have the following problem: When I am trying to delete a member from my DB via the template, I'm receiving the following error: type object 'Member' has no attribute '_default_manager I'm not sure what am I doing wrong, because everything seems to be as normal as possible. Bellow are my model, view and template snippet for my issue. GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) class Member(models.Model): """Model for a member""" surname = models.CharField(max_length=255) names = models.CharField(max_length=255) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) dob = models.DateField() # anniversary = models.ForeignKey(Anniversary) email = models.EmailField() phone = PhoneNumberField(help_text='Please, use this format +3232') address = models.CharField(max_length=255) suburb = models.CharField(max_length=255, choices=Suburbs_list, default=Suburbs_list[0][0]) province = models.CharField(max_length=255, choices=Provinces_List, default=Provinces_List[8][1]) country = models.CharField(max_length=255, default='Unite Kingdom') previous_church = models.CharField(max_length=255) added_date = models.DateField(default=datetime.date.today) def __str__(self): return self.surname class Meta: ordering = ['-suburb', 'province'] And my Delete View: class DeleteMember(LoginRequiredMixin, generic.DeleteView): """ This view will be responsible of deleting an member """ model = Member template_name = 'members/delete_member.html' success_url = reverse_lazy('website:home') and my form: class MemberForm(forms.ModelForm): dob = forms.DateField(widget=extras.SelectDateWidget, label='Date of Birth') phone = forms.CharField(label='Phone Number', widget=forms.TextInput(attrs={'placeholder': '+41524242424'})) class Meta: model = Member exclude = ['added_date'] error_messages = { 'phone': { 'max_length': _("Please use this format +41524242424 ."), } } … -
Django Serializer overide "name" and cannot send name value to DB
I got this code: class DeviceSerializer(serializers.ModelSerializer): icon = serializers.CharField(source='icon_before') name = serializers.SerializerMethodField('_get_device_name') class Meta: model = models.Device fields = ('id', 'name', 'host', 'icon', 'status', 'featured', 'pin', 'room', 'target', 'series', 'type') @staticmethod def _get_device_name(obj): return '%s - %s - %s' % (obj.name, obj.target, obj.room.name) and I am trying to understand what can I do to override name but to let django send name value from restapi post into db, right now it doesn't, it will if I remove the "name = override". Thank you. -
How to convert Context in python2 to python3 [duplicate]
This question already has an answer here: How do I format a string using a dictionary in python-3.x? 5 answers def __unicode__(self): context = { "sender": self.sender_object, "verb": self.verb, "action": self.action_object, "target": self.target_object, } return "%(sender)s %(verb)s %(target)s" %context I need to return the values using python 3 I will change of course unicode to str I can return it using this line but I need more smart code using context like python 2 return "{} {} {}".format(self.sender_object, self.verb, self.target_object) -
Django send push notification when database value changed
I'm newbie with Django, and I have to create a server that is able to detect when a specific value into the database is lesser than X, and then, send a notification to specific user. My idea was something like: Value lesser than X is detected. The server adds a notification record to notification's table into database. Server send a push notification to the designed user. In the app there is a view for notifications that reads the mentioned table. I'm able to implement points 2 and 3, but the first point I have no idea of how I can start it. -
Django templates seem to reverse order of RTL text if contains html tags like <b>
I have an arabic paragraph like this: <div dir="rtl"><b>کلمه اول</b>: {{ value }}</div> Which django templates render like this: کلمه اول: {{ value }} even though the direction is right-to-left How can i make it behave in the same way that a normal line would look without the <b></b> tags Like this: https://fiddle.jshell.net/oae93a2k/2/ Thank you! -
django rest form not valid error
I have a model, model form and a view as follows: @api_view(['POST']) def addCigar(request): print(request.POST) form = CigarForm() if request.POST: form = CigarForm(request.POST) if form.is_valid(): cigar.save() cigar = Cigar.objects.filter(id=cigar.id) serializer = CigarSerializer(cigar, many=True) return Response(serializer.data) else: return Response("Form not valid, insert correct fields.") Form: class CigarForm(ModelForm): class Meta: model = Cigar fields = ['brand','origin','shape', 'strength', 'aroma', 'notes', 'rating', ] Model: class Cigar(models.Model): brand = models.CharField(max_length=50, blank=False,) origin = models.CharField(max_length=30, blank=False,) shape = models.CharField(max_length=20, blank=False,) strength = models.CharField(max_length=20, blank=False,) aroma = models.CharField(max_length=20, blank=False,) notes = models.CharField(max_length=100, blank=False,) rating = models.IntegerField(null=True, ) My angular2 frontend service: public addCigar( brand: string, origin: string, shape: string, strength: string, aroma: string, notes: string, rating: number) { console.log("In service") let obj = new CigarModel(brand, origin, shape, strength, aroma, notes, rating); let body = JSON.stringify(obj); console.log(body) let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.myUrl + 'api/cigar/add/', body, options) .toPromise() .then(response => response.json()) } This however gives me form not valid error. The print statement in the view prints <QueryDict: {}> and console.log in service body prints {"brand":"Nitish","origin":"India","shape":"Thin","strength":"Strong","aroma":"Wood","notes":"Good","rating":"4"} What am I doing wrong here? Is problem with my frontend or backend? -
How to convert string to django.db.models.query_utils.Q format?
For a search function I want to save django query to database & later execute it. I have saved the query as shown below in one table(Company, which have id,qryText). The django query is saved as string. qrySaved = (AND: ('code__in', ['10', '11', '12']), ('color__in', ['1', '2', '3'])) I am unable to execute it like q = Company.objects.get(id=1) Car.objects.filter(q.qryText) as q.qryText is a string not django.db.models.query_utils.Q format. How could I execute this string query ? -
Multiple images upload
I was using this code form simple model (without any relations). But I've problem with two models, Gallery and GalleryImage https://github.com/Chive/django-multiupload class Gallery(models.Model): title = models.CharField(max_length=200) date = models.DateField(auto_now_add=True) author = models.ForeignKey(User, blank=True) class GalleryImage(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name='image_in_gallery') image = models.ImageField(upload_to='gallery/%Y/%m/%d') title = models.CharField(max_length=200) What should forms.py in this case seems? -
django-scheduler can't find static files
I'm new to Django. I followed the instructions on the README and then I couldn't find any further instructions on how to use scheduler, so I copied the fullcalendar.html from the django-scheduler-sample project into my project. However, it can't find any of the css or js files required after a collectstatic or a bower install. Is there a detailed tutorial somewhere on how to add django-scheduler to an app? Why is fullcalendar.css not being added to staticfiles? I'm using Django 1.10.5, Nginx, and Gunicorn. -
How to make multiple checkbox bounded with date
I have a model class Journal(models.Model): name = models.ForeignKey('Student',max_length=256, verbose_name='Student name', blank=False) status = models.BooleanField(widget=forms.CheckboxSelectMultiple, default=False, verbose_name='Status') date = models.DateField(). I need possibility make choice of different date, put checkbox on or off. How I can bound checkbox with date. I added image for better explaining what I need.enter image description here.Thanks. -
TypeError: view must be a callable or a list/tuple in the case of include(). I am using wut4lunch app from the tutorial
from django.conf.urls import include, url from django.contrib import admin import wut4lunch.views urlpatterns = [url(r'^admin/', include(admin.site.urls)), url(r'^$', 'wut4lunch.views.index', name='home'), url(r'^newlunch', 'wut4lunch.views.newlunch', name='newlunch') ] This code is the part of wut4lunch app mentioned in the blog: https://www.airpair.com/python/posts/django-flask-pyramid I have given the content of url.py. Please explain the problem -
python django dictionary values
i want to print the values of the dictionary. here dict is in data.entityFeatures {% for key in data.entityFeatures %} <tr> <td>{{ key }}</td> <td>{{ data.entityFeatures[key] }}</td> </tr> {% endfor %} i'm getting following error when i run this code Could not parse the remainder: '[key]' from 'data.entityFeatures[key]' -
Add django url template tags to pandas html table with jQuery
In my django-view I use pandas to create a pivot table which is then handed via context to the template. This works just fine. I want the headers of the columns to be links triggering new views. So I wrote a simple jQuery script to do this. But I run into problems as soon as I want to pass a kwarg with the url template tag.. $(document).ready(function(){ $('thead th').each(function(){ $(this).html('<a href="{% url "cat_view" cat="' + $(this).html() +'" %}">'+ $(this).html() +'</a>'); }); }); I get the following error: Reverse for 'cat_view' with arguments '()' and keyword arguments '{'cat': "' + $(this).html() +'"}' not found. 1 pattern(s) tried: ['category/(?P[\w-]+)/$'] my url entry looks like this: url(r'category/(?P<cat>[\w-]+)/$', categoryView, name='cat_view'), Am I making an error with the syntax or is it a general problem with my approach? The error message suggests, that django interprets what I write in the jQuery script instead of what the jQuery is supposed to pass over to django.. but I don't know how to avoid this.. -
Making a user profile , clashing of fields
Users class: class Users(models.Model): user = models.OneToOneField(User, related_name='user') user_id = models.BigAutoField(primary_key=True) I am getting error like this : ERRORS: myWebsite.Users.user_id: (models.E006) The field 'user_id' clashes with the field 'user' from model 'myWebsite.users'. Any help would be greatly appreciated. -
How can I schedule Django background task in Heroku without using Credit card or without money?
I deployed a Django app using free version of Heroku. Now I need to run some background task so I choose django-background-tasks . As per the documentation, I have to run python manage.py process_tasks command after running the project using python manage.py runserver . So I added Procfile as below worker: python manage.py process_tasks web: gunicorn CYC_Heroku.wsgi But, I couldn't scale the app cause, I'm using a free version. then, can I do the same without paying money / without credit card ??