Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django REST framework does not work show new fields in a model
I am new to Django, I am trying to achieve a Product Lookup module fetches data from MySQL responds to GET request. Here is my model models.py class CNF_BRAND(models.Model): COMPANY_NAME = models.CharField(max_length=255) BRAND_NAME = models.CharField(max_length=255) BRAND_DESC = models.CharField(max_length=1024) serializers.py class BrandSerializer(serializers.ModelSerializer): class Meta: model = CNF_BRAND GET response { "Status": "SUCCESS", "Brand": [ { "COMPANY_NAME": "Test", "BRAND_NAME": "Test Brand", "BRAND_DESC": "Classic", } ] } views.py response_data = {} brand=CNF_BRAND.objects.all() #Main Cone #Man Goods serializedProduct = BrandSerializer(brand, many=True) response_data['Brand'] = serializedProduct.data response = JsonResponse(response_data, status=status.HTTP_200_OK) return HttpResponse(response,content_type="application/json") which works fine. Updated Code class CNF_BRAND(models.Model): COMPANY_NAME = models.CharField(max_length=255) BRAND_NAME = models.CharField(max_length=255) BRAND_DESC = models.CharField(max_length=1024) TITLE = models.CharField(max_length=21) FAV_ICON = models.URLField(max_length=1024) GET response { "Status": "SUCCESS", "Brand": [ { "COMPANY_NAME": "Test", "BRAND_NAME": "Test Brand", "BRAND_DESC": "Classic", } ] } No Change in the Get Response. I did python manage.py makemigrations python manage.py migrate restarted the django server multiple times I can see the new fields in database & updated the field values. But unable to see the new fields in my response. -
Django REST Framework user registration Validation confusion
I am trying to register a user with Django REST API with two different methods With method 1 everything works fine but it gives This problem : Django REST Framework user registration confusion And with method 2 it gives the following error but is creating users in backend AttributeError at /api/users/register/ Got AttributeError when attempting to get a value for field password2 on serializer UserCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'password2'. Code: from django.contrib.auth import get_user_model from rest_framework.exceptions import ValidationError from rest_framework.serializers import (ModelSerializer,CharField) User = get_user_model() class UserCreateSerializer(ModelSerializer): password2 = CharField(label='Confirm Password') class Meta: model = User fields = [ 'username', 'password', 'password2', 'email', ] extra_kwargs = { 'password' : {'write_only': True}, 'password2': {'write_only': True}, } def validate_password(self, value): data = self.get_initial() password = data.get('password2') password2 = value if password != password2: raise ValidationError('Passwords must match') return value def validate_password2(self, value): data = self.get_initial() password = data.get('password') password2 = value if password != password2: raise ValidationError('Passwords must match') return value method 1: def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( … -
Django REST Framework user registration confusion
I am trying to register a user with Django REST API, everything is working fine but when I pass password2 attribute to extra_kwargs, its not hiding but hiding other attributes like password,email or username Code: from django.contrib.auth import get_user_model from rest_framework.exceptions import ValidationError from rest_framework.serializers import (ModelSerializer,CharField) User = get_user_model() class UserCreateSerializer(ModelSerializer): password2 = CharField(label='Confirm Password') class Meta: model = User fields = [ 'username', 'password', 'password2', 'email', ] extra_kwargs = { 'password' : {'write_only': True}, 'password2': {'write_only': True}, } def validate_password(self, value): data = self.get_initial() password = data.get('password2') password2 = value if password != password2: raise ValidationError('Passwords must match') return value def validate_password2(self, value): data = self.get_initial() password = data.get('password') password2 = value if password != password2: raise ValidationError('Passwords must match') return value def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username=username, email=email ) user_obj.set_password(password) user_obj.save() return validated_data Note: Using Python3 , Django 10.7 & Django REST framework 3 -
Translation in templates not belonging to a particular application
Django 1.11 I would like to make translations in the base.html template. This template belongs to the whole project (not to a particular directory). settings.py LANGUAGE_CODE = 'ru-RU' LOCALE_PATHS = [os.path.join(BASE_DIR, '../templates/locale',),] In the debugger I checked: this LOCALE_PATH equals to /home/michael/workspace/photoarchive_project/photoarchive/templates/locale What we have there: templates directory content (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive/templates$ tree . ├── base.html └── locale base.html {% load i18n %} <title>{% trans 'Photoarchive' %}</title> <a class="blog-nav-item" href="{% url 'frames:list' %}">{% trans "Frames" %}</a> <a class="blog-nav-item" href="{% url 'persons:list' %}">{% trans "People" %}</a> <a class="blog-nav-item" href="{% url 'places:list' %}">{% trans "Places" %}</a> <a class="blog-nav-item" href="{% url 'search_engine' %}">{% trans "Search" %}</a> Now I go to templates directory and: (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive/templates$ django-admin makemessages Nothing happens: no message in the terminal that something was processed. And locale directory is still empty. Could you help me understand how to make related django.po file appear? -
django limit number of items that can be created by user - user packages
I hope I typed my question title correctly. I have examined lots of posts but couldn't exactly find what I need. You know, for some listing websites like real estates or product selling sites there are some user packages: Free Member (for 1 item), Silver Member (for 3 items) and Gold Member(for 10) items.. Each type of user can create limited amount of items which are assigned for that package. They are not allowed to create more than the package allows. These packages might contain other specs. as well, like Free (3 photos), Silver (5 photos), Gold (10 photos) etc. How to do this "user - packages things" with django? How should I look for it? -
Stream file from remote url to Django view response
Is there any way to stream file from remote URL with Django Response (without downloading the file locally)? # view.py def file_recover(request, *args, **kwargs): file_url = "http://remote-file-storage.com/file/111" return StreamFileFromURLResponse(file_url) We have file storage (files can be large - 1 GB and more). We can't share download url (there are security issues). File streaming can significantly increase download speed by forwarding download stream to Django response. -
Restricting Access to Data Based on User Profile using Django Filter
I am using Django 1.11 and Django Registration Redux 1.5 and I am relatively new to programming. I am creating an application that should display data based on a the organization of the user logged in. I have created the following models: class Organization(models.Model): organization_name=models.CharField(max_length=200) organization_type=models.CharField(max_length=50) organization_code=models.IntegerField() organization_krapin=models.CharField(max_length=11) organization_contactname=models.CharField(max_length=200) organization_contactnumber=models.IntegerField() tariff=models.ForeignKey("Tariff", on_delete=models.SET_NULL, blank=True, null=True, ) def __unicode__(self): return str(self.organization_name) class OrganizationUserProfile(models.Model): user=models.OneToOneField(User, unique=True) organization=models.ForeignKey("Organization") def __unicode__(self): return str(self.user) class OrganizationOrders(models.Model): REBATE_OPTIONS = ( ('Y', 'Yes'), ('N', 'No'), ) mobile_number=models.IntegerField() order_status=models.BooleanField(default=False) scored_data_id=models.CharField(max_length=200, null=True) order_datetime=models.DateField(default=timezone.now) order_udatetime=models.DateField(null=True, blank=True) order_rebate_status=models.CharField(max_length=1, choices=REBATE_OPTIONS, default='N') organization=models.ForeignKey("Organization") def __unicode__(self): return str(self.mobile_number) And here is my views.py from __future__ import unicode_literals from django.shortcuts import render from .models import OrganizationOrders001, OrganizationUserProfile def orders(request): if request.user.is_authenticated: context = { 'organization_orders': OrganizationOrders.objects.all(), } return render(request, 'orders.html', context) else: return render(request, 'base.html') I want to filter the OrganizationOrders based on the Organization of the user profile as registered in OrganizationUserProfile. I will then display only the OrganizationOrders where the organization field matches the organization field of the user currently logged in. I will appreciate your answers. -
Broken plotly installation impacts Django
This is just to share some experience. Recently I have installed plotly for my Django project. An attempt of import plotly or any of its modules caused "list index out of range" exception. After long search, similar complaint was found @GitHub. This seems to be a bug, reported about 1.5 months ago. The report is about plotly version 2.0.5. I got version 2.0.9 installed. It looks the bug is still persisting. It maybe just incompatibility with Django thus (version 1.10.5). So I guessed that before that the plotly was working somehow. Tried to reinstall it to lower version. It helped. How to reinstall --> see in the answer. -
Django templates and JSON response
I'm using Django to create Website. In order to use json in html, I send json in views. Here is my code: views.py def json_data(request): data = words.objects.all() return JsonResponse(list(data), safe=False) models.py class words(models.Model): word = models.CharField(max_length=20) value = models.FloatField(default=0) def __str__(self): return self.word And I want to parse json and use it in this form. result.html items: [ {text: "Java", count: "236"}, {text: ".Net", count: "382"}, {text: "Php", count: "170"}, {text: "Ruby", count: "123"}, {text: "D", count: "12"}, {text: "Python", count: "170"}, {text: "C/C++", count: "382"}, {text: "Pascal", count: "10"}, {text: "Something", count: "170"}, ], I do not know how to code JS. Please help me. -
multiple forms that call same function
The situation: I have page that lists a number of submissions. Next to each submission I want to add a button to accept said submission. I'm doing this via a form. The html: {% for submission in submissions %} <div class="submission-container"> <div class = "col-sm-6"> {{ submission.submission_title }} </a> </div> <div class = "col-sm-6"> <form action="" method="post" class="accept_submission" style="float:left;"> {% csrf_token %} <input type="hidden" class="data-submission-id" value="{{ submission.SUBMISSION_ID }}" /> <input type="hidden" class="url-data" value="{% url 'submission_accept' %}" /> <input type="submit" value="Accept" class="btn btn-info" /> </form> </div> </div> {% endfor %} the jquery: $('.accept_submission').on('submit', function(event){ event.preventDefault(); var data_post = { submission_id : $('.data-submission-id').val() } execute_ajax_post(data_post); }); function execute_ajax_post(data_post) { var csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ url : $('.url-data').val(), type : "POST", data : data_post, success : function() { console.log("success"); }, }); }; Now the problem is that I want each form to pass on the submission_id of the particular submission the button is associated with. However when I use classes all buttons pass on the submission_id of the first listed submission. If I use id="accept_submission" only the first button works. How would I get this to work correctly? -
Django : request.POST is returning empty dictionary after button submit
I have three forms in a page, contact_me, feedback and subscribe. All the three forms are displayed as bootstrap-modal. On form field error, the user is redirected to a respective dedicated page showing all the errors. The problem I'm facing is that, all the three forms redirect to the dedicated error forms page when the user is not logged in. But, when the user logs in, user isn't directed to the error forms page instead, the current page gets reloaded. In views.py, request.POST shows an empty dictionary. Only the subscribe form is working properly even after user login. On the other hand, if the user submits a correct from, the object is stored properly. Here's my views.py: if request.POST.get("feedback"): print request.POST.get. #shows empty dict if feedback_form.errors: return comments.views.view_feedback(request, feedback_form) if request.POST.get("contact_me"): if contact_form.errors: return comments.views.contact_me_error(request, contact_form) if request.POST.get("subscribe"): print request.POST.get # shows proper dict if subscribe_form.errors: return comments.views.subscribe_error(request, subscribe_form) Here's my contact_me.html : <div class = "modal fade bs-example-modal-lg" id = "contact_me_form" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel"> <div class = "modal-dialog" role = "document"> <div class = "modal-content"> <div class = "modal-header"> <div class = "login"> <h2> A message to Sagar Jeevan </h2> <hr> <form method … -
Access request from the forms.Form to get data from dB related to user
I'd like to access the request data(user) via the Form class linked to the connected view as django.views.generic.View class. I've checked similar questions here: Curious about get_form_kwargs in FormView and here: Sending request.user object to ModelForm from class based generic view in Django and here: Django: Accessing request in forms.py clean function However they don't touch base with non-FormView classes. And as it's fairly old solutions, I was curious if there's more likely approach to reach request from forms.Form class. Here's my code: views.py class addTemplate(View): form_class = AddTemplate template_name = 'distrib_db/add_template.html' def get(self, request): if request.user.is_authenticated(): form = self.form_class(None) return render(request, self.template_name, context={'form': form}) def post(self, request): if request.user.is_authenticated(): form = self.form_class(request.POST) if form.is_valid(): c_data = form.cleaned_data template = Template(name=c_data['name'], text=c_data['text'], template_type=c_data['template_type'], user=request.user) template.save() return redirect('distrib_db:templates') forms.py class AddTemplate(forms.Form): name = forms.CharField(max_length=50) text = forms.CharField(max_length=500, widget=forms.Textarea()) template_type = forms.ChoiceField(choices=(('sms', 'sms'), ('email', 'email')), widget=forms.Select(attrs={'class': 't_type'})) I'd appreciate any approach, mb I lack knowledge and asking newbie questions, sorry about it. I just wanna get the python-way solution rather then build some js/jinja walk-arounds. Thank you for your time! -
What's wrong with my urls.py?
I'm trying Django 1.11 and I have an issue : This my file agora/agora/urls.py : from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^start/', include('start.urls', namespace='start')), ] And this is my file agora/start/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', view_first, name='view_first'), url(r'^/inscription', view_second, name='view_second'), url(r'^/about', view_about, name='view_about'), ] The Django server return an error : NameError: name 'view_first' is not defined Many thanks for your answers ! -
How to add more fields to blog posts in meezanine CMS?
I am developing an cms website by using Mezzanine CMS. I want to add the field as author name and image in blog post. can anyone help me how can i add custom fields in mezzanine's inbuilt blog application -
Add_fieldsets overriding add_form in Django-admin?
From this full example, we can see that both add_form and add_fieldsets are specified in UserAdmin. class UserAdmin(BaseUserAdmin): # ... add_form = UserCreationForm # ... add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('stu_id', 'password1', 'password2', 'first_name', 'last_name', 'tel', 'email')} ), ) In the resulting admin site, when I try to add a new user instance, the form layout is specified by add_fieldsets, rather than add_form. Does this means add_fieldsets overrides add_form in UserAdmin? If not, what role does add_form play? -
making the first image select by default as featured from the modelformset_factory
I need to make it possible for the first image to be selected as featured by default. Currently it works but only when the user selects the featured image. Forms.py class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') def __init__ (self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.fields['featured'] = forms.BooleanField( widget = forms.RadioSelect(choices=((self.prefix, 'featured'),))) class Meta: model = Images fields = ['image', 'featured', ] models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify # Create your models here. class Post(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=128) body = models.CharField(max_length=400) def __str__(self): return self.title def get_image_filename(instance, filename): title = instance.post.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename) class Images(models.Model): post = models.ForeignKey(Post, default=None) image = models.ImageField(upload_to=get_image_filename, verbose_name='Image', ) featured = models.BooleanField(default=True) -
Django model with sqlite3 regex
I have a standard django app, using sqlite3, and I have the regex installed. If I use the sqlite3 command line and load the regex extension, it works correctly. What I want is to be able to the regex extension from within django, but since everything is wrapped in the django model I don't have access to the API load_extension. Is there a way to autoload the extension from inside django? I've seen that I should be able to do something like select load_extension('/path/to/pcre.so'), but I'm also not sure how to execute that. -
How to configure and use SQLG with TinkerPop?
I need a way to run graph queries on python django. TinkerPop and gremlin provide a way to run graph queries. How do i make them persistent. I have no idea about the java stack. I tried the below commands: sudo apt-get purge maven maven2 maven3 sudo apt-add-repository ppa:andrei-pozolotin/maven3 sudo apt-get update sudo apt-get install maven3 git clone https://github.com/apache/tinkerpop.git cd tinkerpop mvn clean install -Dmaven.test.skip=true bin/gremlin.sh \,,,/ (o o) -----oOOo-(3)-oOOo----- plugin activated: tinkerpop.server plugin activated: tinkerpop.utilities plugin activated: tinkerpop.tinkergraph gremlin> :q git clone https://github.com/pietermartin/sqlg.git cd sqlg mvn clean install -Dmaven.test.skip=true not sure what to do next. how to run a gremlin-server that is configured with say a postgres database and connect to it from a python django web-app and execute queries like is-parent-of to check users permissions on the resource he is requesting? -
django csrf_token missing error
When I am trying to register, I'm getting an error: Forbidden (403) CSRF verification failed. Request aborted. My Code: @csrf_protect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data.get("firstname") last_name = form.cleaned_data.get("lastname") username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = User.objects.create_user(username=username,password=password) user.first_name = first_name user.last_name = last_name user.set_password(password) user.is_active = True user.save() return HttpResponseRedirect('/home/') else: form = RegistrationForm() return render_to_response('registration/registerHome.html',dict(form=form, context_instance=RequestContext(request) ) ) my form.py class RegistrationForm(forms.Form): """ A registration form to create normal user. """ firstname = forms.RegexField(regex=r'^\[a-zA-Z]+$', widget=forms.TextInput(attrs={ 'required':True, 'max_length':30, 'autocomplete':'off', 'class':'form-control input-sm', 'placeholder':'First Name' }), error_messages={ 'invalid': _("Only alphabets are allowed.") } ) lastname = forms.RegexField(regex=r'^\[a-zA-Z]+$', widget=forms.TextInput(attrs={ 'required':True, 'max_length':30, 'autocomplete':'off', 'class':'form-control input-sm', 'placeholder':'Last Name' }), error_messages={ 'invalid': _("Only alphabets are allowed.") } ) username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs={'required':True, 'max_length':30, 'autocomplete':'off', 'class':'form-control input-sm', 'placeholder':'username'}), error_messages={ 'invalid': _("Only [a-z A-Z 0-9 _] are allowed.") } ) password = forms.CharField(widget=forms.PasswordInput(attrs={ 'required':True, 'max_length':30, 'autocomplete':'off', 'class':'form-control input-sm', 'placeholder':'password', 'render_value':False }) ) def clean_username(self): try: user = User.objects.get(username__iexact=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(_("Username already exists.")) class Meta: model = User my template.html <form action="." method="post" role="form" id="register-form"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" /> </form> Someone, please help me, why I'm getting an error. … -
How to extract django objects having maximal value?
Supposing I have a django model: class Score(models.Model): name = models.CharField(max_length=32) value = models.Integer() def __unicode__(self): return u"{}: {}".format(self.name, self.value) And the table score looks line this: id | name | value ---+-------+------ 1 | john | 15 2 | ivan | 21 3 | david | 14 4 | john | 11 5 | john | 25 6 | david | 8 I want to extract the objects with maximal value for each name given as a list of names. For example: names = ['john', 'david', 'paul'] dct = process(names) # How to implement this function??? for name, obj in dct.items(): print name, obj should print: john john: 25 david david: 14 paul: None The performance matters. I am supposed to process around 10k names having around 1k records for each name in score. What is the best way to do it with django? Does it make a sense to use django ORM in this task? I use MySQL database. Thanks for advance. -
I use Django to return a template, but the outside css doesn't work
I return a html like this: urlpatterns = [ url(r'^station/$', views.stat_list) ] And in html, I link to a css file and the root is right because I can see it working by directly open it: <link rel="stylesheet" type="text/css" href="./station_list.css"> The image is the same problem: <img src="logo.png" style="max-width:120px; max-height:50px;" /> Why is that the html can't use the outside link? Thanks. -
Reverse accessor for content_type clashes
Trying to connect mezzanine project to existing django, I ran into this error: ERRORS: generic.Rating.content_type: (fields.E304) Reverse accessor for 'Rating.content_type' clashes with reverse accessor for 'Rating.content_type'. HINT: Add or change a related_name argument to the definition for 'Rating.content_type' or 'Rating.content_type'. star_ratings.Rating.content_type: (fields.E304) Reverse accessor for 'Rating.content_type' clashes with reverse accessor for 'Rating.content_type'. HINT: Add or change a related_name argument to the definition for 'Rating.content_type' or 'Rating.content_type'. Tried to add related_name to both of these fields in models (including '%(app_label)s' and '%(class)s'), but it doesn't work (however, worked with other similar errors I resolved, it's only these two remaining). So, in generic model content_type = models.ForeignKey("contenttypes.ContentType") In star_ratings model content_type = models.ForeignKey(ContentType, null=True, blank=True) Parent model class ContentType(models.Model): app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _('content type') verbose_name_plural = _('content types') db_table = 'django_content_type' unique_together = (('app_label', 'model'),) What should I change? -
wagtail / django understanding pages, link and appropriate data structures
I am having some trouble trying to understand what data structure to adopt for various data items and how to access them. Below is my menu structure and page items. Home page / | \ News About us Events / | \ / | \ n_item n_item n_item e_item e_item e_item I am using wagtailmenus to generate my header nav bar which works like a charm. All the pages inherit from either Page or MenuePage classes. Now my dilemma is when I want to feature/highlight "n_items" and "e_item" in my homepage maybe like the top 3 news and event items. I can't seem to figure out how to access those pages in my homePage way at the top? Should I have changed "n_items" to snippets instead and bound them to both my "homepage" and "news" page and same for events ? Ideally the aim would be to have "n_items" which I can select and they take me directly to that news item and additionally a "view all news" which redirects me to the "News" page. Keeping in mind I have adopted multi language support using the following ideology Also i will grant -
Convert opencv python application to web application
I Want to Convert my opencv python application to web application, So what i do? import cv2 import numpy as np img = cv2.imread('1.jpg',0) img = cv2.medianBlur(img,5) cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=0,maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0,:]: # draw the outer circle cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2) # draw the center of the circle cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3) cv2.imshow('detected circles',cimg) cv2.waitKey(0) cv2.destroyAllWindows() -
Limiting QuerySet Results according to a particular field
I have two Models Article & Category. I want to fetch the results of article such that there are 5 articles for each category. I was thinking of hitting the DB for querying 5 articles for each category, but I suppose that would be inefficient.(Incase there are 100 categories, DB will be called 100 times). I want to use the ORM to fetch it properly. I tried this, but am getting an error that aggregate functions cannot be used with groupby. query_set = Article.objects.extra(select={'count': 'count(5)'}, order_by=['-count']).values() query_set.query.group_by = ['category']