Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
expected string or Unicode object, Photo found in django
here i want to read the image from db and apply some operations on my image like noise remove .... and finally i will appy pytesseract to get the text def GetData(request): img = Photo.objects.get(id=1) #wrapper = FileWrapper(open(img.file)) # Read image with opencv img = cv2.imread(img) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) b,g,r = cv2.split(img) # get b,g,r rgb_img = cv2.merge([r,g,b]) # switch it to rgb # Denoising dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21) img = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY) # Apply threshold to get image with only black and white img = cv2.adaptiveThreshold(img, 127, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11,2) new_image = cv2.blur(img, (1, 1)) -
Django Password Rest using Rest API
Our team works on project with django-rest-api on back-end and angular-2 on front end. we have problem with password reset. Here urls: from django.contrib.auth import views as auth_views urlpatterns = patterns( '', url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), ) When request to password_reset is posted, user receives email with link contains password reset token. The token should have an expiration time within 24 hours. want to make password reset api, so we can change the password using postman and also frontend developer use this api. -
Django [Python] website
I am running a Django project (where I am quite new) I have the scenario where the App fetches data from an API every 30 seconds and displays the same in website (presently at local server) Question is is there any way to acheive this? I searched over internet but couldn't find a possible answer. -
Setup static file in Django from serving site in production mode
I am trying to run my static files from the same serving site on production mode. This is what I did. In setting.py, I have set, DEBUG = False ALLOWED_HOSTS = ['12.10.100.11', 'localhost'] I included, 'django.contrib.staticfiles' in INSTALLED_APPS I set the Static root directory to, STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") I ran, python manage.py collectstatic, to copy all the static files to local serving directory. (following: https://djangobook.com/serving-files-production/) I then point static url directory to, STATIC_URL = ("/static/") I then run, python manage.py runserver 12.10.100.11:8000 However, on console inspect the error shows: Get http://12.10.100.11:8000/static/css/main.css 404 (not found) on my base.html looks something like this: {% load static %} <link rel="stylesheet" href="{% static '/css/main.css' %}" type="text/css" /> I am new to django and need lots of advise, thanks Jef -
Submit form with input added in the URL and not as parameter
Supposing I have the following Form. Is there a better way to send the value of the input in the URL like in the example "indication_effects/+MY_VALUE" and get rid of the parameter indication=MY_VALUE?? Maybe it is possible to do it with Django or should I simply use a django form? Thank you, <form id="indication-form" class="form-horizontal" method="get"> <div class="form-inline"> <div class="col-md-8"> <input type="text" class="form-control" id="indication-input" name="indication" /> <button class="btn btn-primary" type="submit" id="indication-submit">Submit</button> </div> </div> </form> var indicationForm = $('#indication-form'); $("#indication-submit").on("click", function () { indicationForm.attr("action", "indication_effects/" + $("#indication-input").val()); indicationForm.submit(); }); -
Django Add staff users to handle other user's informations
I am developing a website that allows the management of reservation of cars by users. I created a first app that manages user accounts such as : registration with email confirmation / login / logout ...etc i've created a special user that have staff permissions During registration, each new user must load pdf documents, these documents will then be verified by the staff user If the uploaded documents are good, this member sends to the user a PDF_contract to be signed electronically My question is How to display files uploaded by users for the staff user, so that he can check and send them a Pdf document. NB: i'm beginner in django and python My code: views.py from mysite.core.forms import SignUpForm, ProfileForm, DocumentForm from mysite.core.models import Profile from mysite.core.tokens import account_activation_token from django.views.generic.list import ListView from django.views.generic.detail import DetailView # Create your views here. def index(request): return render(request, 'index.html') @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: … -
Django override the form label template?
In my settings.py I have set FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' now in can add my own templates in: <project>/templates/django/forms/widgets/ or <app>/templates/django/forms/widgets/ this works great! However, what I can't find is where do I override the default (form) label? class TestForm(forms.Form): first_name = forms.CharField(label="First name", max_length=50) last_name = forms.CharField(label="Last name") nick_name = forms.CharField(required=False) The above form would render the labels like this: <label for="id_first_name">First name:</label> I thought it would easy as adding a label as template: templates/django/forms/widgets/label.html This doesn't work. Was going through the Django docs, but I can't find how to do this for labels. Apparently a label is not a widget. https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#built-in-widgets My question, where/how do I change the default label? -
Display image in template with Django
I am trying to display images into articles in my blog project built with Django. Here is the related code: settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = "/media/" urls.py (project): urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: class Article(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150) author = models.CharField(max_length=80) text = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de parution") image1 = models.ImageField() image2 = models.ImageField() image3 = models.ImageField() def __str__(self): return self.titre views.py: def article(request, id, slug): article = get_object_or_404(Article, id=id, slug=slug) return render(request, 'blog/post.html', {'article': article}) post.html: <img src="{{ article.image1.url }}"/> <img src="{{ article.image2.url }}"/> <img src="{{ article.image3.url }}"/> However, it does not work. Images do not appear. Any suggestions ? -
CheckBox Form Validation and Saving in the Views
I am new to Django forms. I am trying to save some related fields using a check box widget .. we have a manager and he wants to choose team members using a check box of all available members, but the return value of this checkbox is always an empty dictionary forms.py class AddAgentStaffForm(forms.ModelForm): class Meta: model = Hierarchy fields = ('agent',) widgets = {'agent': forms.CheckboxSelectMultiple} def __init__(self, agent, **kwargs): super(AddAgentStaffForm, self).__init__(**kwargs) self.fields['agent'].queryset = Agent.objects.filter( company=agent.company).exclude( agent__agent=agent).exclude( id=agent.id) def clean(self): agent = super(AddAgentStaffForm, self).clean() print agent # i got an empty dictionary here # some validation code so my question is what is the correct way to do this form .. and how to save it in the views here is my attempt to save one object .. what should I add to it to work for CheckBox view.py def add_staff(request, pk): agent = Agent.objects.get(id=pk) heads = Hierarchy.objects.filter(agent=agent) staff = Hierarchy.objects.filter(head=agent) if request.method == "POST": staff_form = AddAgentStaffForm(agent=agent, data=request.POST) if staff_form.is_valid(): obj = staff_form.save(commit=False) obj.head = agent obj.company = agent.company staff_form.save() else: staff_form = AddAgentStaffForm(agent=agent) context = { 'agent': agent, 'heads': heads, 'staff': staff, 'staff_form': staff_form} return render(request, 'hierarchy/add_staff.html', context=context) -
Deserializing data with nested natural keys in Django
I'm trying to deserialize data from a JSON file that contains nested natural keys. For me it seems like nested natural keys are not supported, or I'm doing it wrong. The JSON I try to load looks like this: { "model": "order.Order", "fields": { "shop": [123, "Demo"], "reference": "demo1", } }, { "model": "order.Item", "fields": { "order": [[123, "Demo"], "demo1"] } } The natural key for Order is (shop_id, reference), for Shop it's (account_id, name). Deserializing orders works perfectly fine. Are nested natural keys even supported by Django? -
I am attempting to add two models from separate local apps into one template
I am trying to access Content from content.models and Post from Post.models in the blog.html template. The idea for Content is to be able to edit text on the site through the django admin. The directory stucture is as follows: - src [Folder] - content [Folder] - migrations [Folder] - __init__.py - admin.py - apps.py - models.py - tests.py - views.py - main [Folder] - settings [Folder] - __init__.py - base.py - migrations [Folder] - __init__.py - db.sqlite3 - models.py - urls.py - views.py - wsgi.py - posts [Folder] - migrations [Folder] - templatetags [Folder] - __init__.py - admin.py - apps.py - forms.py - models.py - tests.py - urls.py - utils.py - views.py - templates - base.html - blogbase.html views.py - main looks is as follows: from django.shortcuts import render from django.http import HttpResponse from django.views.generic import View from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin # from posts.models import Post, Content # from app.models import * from posts.models import Post from content.models import Content class DashboardTemplateView(TemplateView): template_name = "base.html" context_object_name = 'name' def get_context_data(self, *args, **kwargs): context = super(DashboardTemplateView,self).get_context_data(*args, **kwargs) context["title"] = "This is about us" return context class MyView(ContextMixin, TemplateResponseMixin, View): def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context … -
Django: using mptt-django to allocate products to categories in a many-to-many relationship
I have a many-to-many relationship between products and categories. I am using mptt to manage the display of categories on the admin (which works fine) and so I can allocate products to categories. While the categories are working fine, it's the product side I'm having problems with. In my models.py I have (truncated for brevity): from mptt.models import MPTTModel,TreeForeignKey,TreeManyToManyField class ProductCategory(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True) class Product(models.Model) categories = TreeManyToManyField(ProductCategory) In my admin.py I have from django.forms import CheckboxSelectMultiple from .models import Product,ProductCategory from django.db import models from django.contrib import admin from mptt.admin import MPTTModelAdmin from mptt.models import TreeManyToManyField class ProductAdmin(admin.ModelAdmin): formfield_overrides = { TreeManyToManyField:{'widget':CheckboxSelectMultiple}, } This almost gets the job done but all of the categories are displayed with checkboxes which is not what I want since you don't want to add products to categories which have sub categories. What I want is the display of categories such that you can only add products to categories which don't have children, so in this example Category 1 Category 2 sub sub Category 3 sub And the labels would be Category 1 Category 2 > Catgory 2 sub > Category 2 sub sub Category 3 > Category 3 sub Many … -
Question mark in url pattern
Django 1.11.2 I need an url pattern for two cases: /blog/ /blog/.json/ So, in case of json, I'll respond with application/json content type. This URL pattern seems to be acceptable: url(r'^blog/?(?P<json>\.json)?/$', BlogFront.as_view()), At least, it works. The problem is I can't understand it. The last ? is to match 0 or 1 repetitions of the preceding RE. It's ok. The ? in the middle is about capturing a symbolic group. What about the first question mark? This is a mystery to me. Could you comment what does it mean? -
Form not saved in database by POST request in django view
My form was working fine but suddenly it stops working and I'm stuck here, help me please! When I prints form.errors in case of form not valid then it prints user is a required field. models.py class TarWithDocker(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, related_name='deployments') slug = AutoSlugField(populate_from='name', unique=True, name='slug') archive = models.FileField(upload_to='archives', name='archive') created_at = models.DateTimeField(default=timezone.now, editable=False) class Meta: ordering = ['-created_at'] views.py class AwdDeployment(LoginRequiredMixin, CreateView): template_name = 'deployments/awdDeployment.html' def get(self, request, *args, **kwargs): return render(request, 'deployments/awdDeployment.html', {}) def post(self, request, *args, **kwargs): if request.method == 'POST': form = AwdDeploymentForm(request.POST, request.FILES) if form.is_valid(): deployment = TarWithDocker() deployment.name = form.cleaned_data['name'] deployment.user = self.request.user deployment.archive = form.cleaned_data['archive'] deployment.save() return HttpResponse("Submitted") else: print("not saved") else: print("something happnes wrong") form = AwdDeploymentForm() return HttpResponseRedirect(reverse('users:deployments:awd')) -
Django NoReverseMatch not a valid view function
Django 1.11 I keep getting a NoReverseMatch error Reverse for 'menu_menuitem' not found. 'menu_menuitem' is not a valid view function or battern name views.py from .models import Category, MenuItem def show_category(request, category_slug): c = get_object_or_404(Category, slug=category_slug) menuitems = c.menuitem_set.all()\ template_name='category.html' context = { 'c':c, 'menuitems':menuitems, } return render(request, template_name, context) def show_menuitem(request, menuitem_slug): i = get_object_or_404(MenuItem, slug=menuitem_slug) categories = i.categories.filter(is_active=True) template_name="menuitem.html" context = { 'i':i, } return render(request, template_name, context) models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for category page URL, created from name.', blank=True, null=True) @models.permalink def get_absolute_url(self): return ('menu_category', (), { 'category_slug': self.slug }) class MenuItem(models.Model): name = models.CharField(max_length=250, blank=False, unique=True) slug = models.SlugField(max_length=250, unique=True, help_text='Unique value for menuitem page URL, created from name.', blank=True, null=True) categories = models.ManyToManyField(Category) @models.permalink def get_absolute_url(self): return ('menu_menuitem', (), { 'menuitem_slug': self.slug }) -
How to test signals when using factory_boy with muted signals
I am using factory_boy package and DjangoModelFactory to generate a factory model with muted signals @factory.django.mute_signals(signals.post_save) class SomeModelTargetFactory(DjangoModelFactory): name = factory.Sequence(lambda x: "Name #{}".format(x)) ... I have a post_save signal connected to the model: def send_notification(sender, instance, created, **kwargs): if created: send_email(...) post_save.connect(send_notification, SomeModel) How can I test the signals works when I create an instance of the model using the factory class? -
Run migrations without loading views/urls
I have following code in one of my views: @ratelimit(method='POST', rate=get_comment_rate()) def post_comment_ajax(request): ... However, upon initial ./manage.py migrate, get_comment_rate() requires a table in database, so I'm unable to run the migrations to create the tables. I ended up with following error: Django.db.utils.ProgrammingError: relation .. does not exist Is it possible to run migrations without loading views or is there a better way? -
django sql explorer - user based query access
I have a django sql explorer which is running with 5 queries and 3 users. Query1 Query2 Query3 Query4 Query5 I want to give access of Query1 and Query5 to user1 and Query4 and Query2 to user2 and likewise. my default url after somebody logins is url/explorer based on users permission he should see only those queries but as of now all users can see all queries, I tried to search stackoverflow and also other places through google but there is no direct answer. Can someone point me to right resource or help me with doing this. -
Django-filter filtering foreign model
i have two models class Sku(models.Model): manufacturer = models.ForeignKey('Manufacturer') class Manufacturer(models.Model): title = models.CharField() I want that in the filtering appeared only manufacturers associated with the current set of sku. my view part: c['skus'] = self.object.skus.filter(hide=False, prices__price_type=PRICE_ROZN).prefetch_related('prices', 'stock').all().order_by( 'prices__value') sku_filter = SkuFilter(self.request.GET, c['skus']) If Self existed at this moment, I would filter out the manufacturers in this way: class SkuFilter(django_filters.FilterSet): # manufacturer__title = django_filters.CharFilter(lookup_expr='icontains') manufacturer = django_filters.filters.ModelMultipleChoiceFilter( name='manufacturer', to_field_name='title', queryset=Manufacturer.objects.filter( pk__in=self.queryset.objects.values_list('manufacturer').distinct()), ) class Meta: model = Sku fields = ['manufacturer', ] But it is obvious that at the given moment the self does not yet exist. -
I keep getting the following error in django: "UnboundLocalError at /myapp/"
I am facing this error in django python: "UnboundLocalError at /myapp/" local variable 'album' referenced before assignment I Created a class in models.py file and import in views but facing this error Here is complete code of both files: Models.py from django.db import models from django.db import models class album(models.Model): artist = models.CharField(max_length=250) title = models.CharField(max_length=500) gender = models.CharField(max_length=100) def __str__(self): return self.artist+'--'+self.title views.py from django.http import HttpResponse from .models import album def myapp(request): all_albums = album.objects.all() title = album.artist html = '' for album in all_albums: url = '/myapp/' + str(album.id) + '/' html += '<a href="' + url + '">' + title + '</a><br>' return HttpResponse(html) -
Valid form is not coming out as valid in django
I have a form in django that is valid but when I try to validate it before grabbin gthe cleaned_data, it is giving me an error and I dont know why it is happening. Can someone help me figure it out.. I have a feeling it is something small but I am getting coders block and can't see it.. here is view.py method: def profile_setup(request): if 'username' not in request.session: return redirect('login') else: username = request.session['username'] currentUser = User.objects.get(username = username) if request.method == 'POST': form = ProfileForm(request.POST) print(form) if form.is_valid(): cd = form.cleaned_data age = cd['age'] print(age) city = cd['city'] print(city) phone = cd['phone'] print(phone) privacy = cd['privacy'] print(privacy) new_profile = Profile.objects.create( user = currentUser, age = age, city = city, phone = phone, privacy = privacy, ) return redirect('accounts') else: form = ProfileForm() message = 'fill out form below' parameters = { 'form':form, 'currentUser':currentUser, 'message':message, } return render(request, 'tabs/profile_setup.html', parameters) Here is the html: {% extends "base.html" %} {% block content %} <h1>Setup you profile: {{ currentUser.username }}</h1> {% if message %} {{ message }} {% endif %} <form action="." method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="submit" value="submit"> </form> {% endblock %} Here is what … -
S3ResponseError: 400 Bad Request using django&boto to upload User Auth image to AWS S3, when on django model.save()
I am trying to upload User's auth_image to s3 bucket on signup using django and AWS elastic beanstalk. On my local development settings, every test was passed as expected, and I checked the image uploaded to the destined path in S3 bucket. But after deploying using fab, signup request from frontend server(angular2) keeps getting 400 Bad Request. On my sentry error message, it reads: exception S3ResponseError: S3ResponseError: 400 Bad Request ... on boto/s3/bucket.py in _get_key_internal at line 232 else: if response.status == 404: return None, response else: raise self.connection.provider.storage_response_error( response.status, response.reason, '') def list(self, prefix='', delimiter='', marker='', headers=None, encoding_type=None): """ List key objects within a bucket. This returns an instance of an ... with the following variables with values as follows: headers None key_name 'media/license/2017/111-2017-07-26-850866.jpeg' query_args None query_args_l [] response <boto.connection.HTTPResponse object at 0x7fd9b0340860> self <Bucket: media-storages> ...request headers Response headers: [('x-amz-request-id', '9CF7B8F8FFD3AA84'), ('x-amz-id-2', 'm0PCvqEWlxNFPZrwzj46VjRYdFMdRmZPD7U25aOTtK/2TARmHxOXlxS2Y3e7BesVY/m9Gnh779Q='), ('x-amz-region', 'ap-northeast-2'), ('Content-Type', 'application/xml'), ('Transfer-Encoding', 'chunked'), ('Date', 'Wed, 26 Jul 2017 06:54:11 GMT'), ('Connection', 'close'), ('Server', 'AmazonS3')] Any ideas lads? -
django rest framwork iterate throug fields in model serializer
i want to iterate through the fields in ModelSerializer and want to make those field required . this not working . how can i do that. Somebody please help me. class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ("email", "phone_no", "full_name", "landline_no") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].required = True self.fields[field].allow_blank = False -
Django template tag on built-in login User.objects.all()
I am using built-in login of django. How I can display all the first name of the registered user on its template using tags? There's no function to add a context because it is built-in so this is what I added to my urls.py, the kwargs thing what I read to other post. from django.contrib.auth.models import User url(r'^login/$', auth_views.login, name='login', kwargs={'all_user': User.objects.all()}), my template at registration/login.html as default {% for user in all_user %} <option>{{ user.first_name }}</option> {% endfor %} When I am accessing now the login it returns an error: LoginView() received an invalid keyword 'all_user'. as_view only accepts arguments that are already attributes of the class. Is there a way that I can put the context on built-in login? -
I want to make a live web page builder for my web application. Where do I start?
I'm trying to build a simple live web page builder. What languages do I need to know for this? Where do I start?