Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
render form using template_name in django viewflow
Hi im new to django viewflow. The template is using TemplateResponseMixin and im not really familiar to it. I want my form to render into my page. My problem is how will i able to render my form. I already create a form in forms.py. Code below from django import forms from viewflow.models import Task from viewflow.models import ProcessData class ProcessDataForm(forms.ModelForm): date = forms.CharField() requestDate = forms.CharField() requestDescription = forms.CharField() ncosRequester = forms.CharField() def __init__(self, *args, **kwargs): kwargs.setdefault('prefix', '_viewflow_activation') super(ActivationDataForm, self).__init__(*args, **kwargs) class Meta: model = ProcessData fields = ['date', 'requestDate', 'requestDescription', 'ncosRequester'] I also added a code in models.py. Code below from __future__ import unicode_literals from django.conf import settings from django.db import models from django.template import Template, Context from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible, force_text from .activation import STATUS, STATUS_CHOICES from .exceptions import FlowRuntimeError from .fields import FlowReferenceField, TaskReferenceField, TokenField from .managers import ProcessQuerySet, TaskQuerySet, coerce_to_related_instance from django.utils import timezone class ProcessData(models.Model): date = models.CharField(max_length=200) requestDate = models.CharField(max_length=200) requestDescription = models.TextField() ncosRequester = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) class Meta: abstract = True And here is my views.py # My code here @method_decorator(login_required, name='dispatch') class AllProcessDataListView(FlowListMixin, TemplateResponseMixin, DataTableMixin, generic.View): list_display = [ 'process_form' ] template_name = … -
The content in email not rendered as standard HTML
I wrote the password_reset_email.html as <p> You're receiving this email because you requested a password reset for your user account at JoCo. <br> <br> Please go to the following page and choose a new password: <br> {{ protocol }}://{{ domain }}{% url 'user:password_reset_confirm' uidb64=uid token=token %} {# {{ protocol }}://{{ domain }}/user/reset/{{ uid }}/{{ token }} #} <br> Your username, in case you've forgotten: {{ user.get_username }} <br> Thanks for using our site!". <br> When I checked it within email, found it not rendered: How to enable email content displayed as standard HTML? -
Django application not working after moving to different directory
I have a Django 2.0 project with following structure and it's working fine app_dir |- myapp |- settings |- __init__.py |- local.py |- production.py |- __init__.py |- wsgi.py |- urls.py |- other_app |- templates |- other_app |- index.html |- models.py |- views.py |- urls.py |- manage.py |- static_resources # directory just to keep core files which are not used in application |- .gitignore |- .dockerignore |- Dockerfile |- docker-compose.yml |- Pipfile |- Pipfile.lock |- Procfile |- requirements.txt |- start.sh |- db.sqlite3 as you can see Django applications and other files which are not directly used in application are all at the same level. So, I thought to move Django applications to src directory to make it separate from other files which are of no use or are auto created. My new directory structure looks like app_dir |- src |- myapp |- settings |- __init__.py |- local.py |- production.py |- __init__.py |- wsgi.py |- urls.py |- other_app |- templates |- other_app |- index.html |- models .py |- views.py |- urls.py |- manage.py |- static_resources # directory just to keep core files which are not used in application |- .gitignore |- .dockerignore |- Dockerfile |- docker-compose.yml |- Pipfile |- Pipfile.lock |- Procfile … -
Notation for action attribute in Django forms
I'm learning about Django forms and while following the tutorial (for v1.11), it says to use dot notation when setting the value for the form action attribute. For example <form action="{% url 'myapp.views.detail' %}> This didn't work for me. While trying to figure out how to fix my issue I noticed different people used different notation to set the form action attribute. Some used <form action="{% /your-name/ %}">, some would use just <form action="{% detail %}">. What ended up working for me was <form action="{% myapp:detail %}">. Can somebody clarify what the differences between the different notations? -
Django Many to many field using a unique key instead of the primary key
I've got a django model that has a self, asymmetrical many to many relationship. I would like that relationship to reference objects using a unique identifying field other than the table's primary key field. I could not find any documentation discussing specifying a field to the ManyToMany object. Is there a way to do that? -
Error `Reverse for 'password_reset_confirm' not found.` though it's there
I configured urls.py as 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.PasswordResetConfirmView.as_view( template_name="user/password_reset_confirm.html", ), name='password_reset_confirm'), It does have a name password_reset_confirm, However, the browser prompts it was not a valid pattern NoReverseMatch at /user/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8001/user/password_reset/ Django Version: 1.11.13 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. How to handle such a problem? -
Please help, how to catch select value django modelform
Please, i need help. I don´t know how to catch the select value from a ModelForm. On template: <div class="form-group"> <label for="{{formulario.cod_sucursal.id_for_label}}"> {{formulario.cod_sucursal.label}}</label> <select name="{{formulario.cod_sucursal.name}}" id="{{formulario.cod_sucursal.id_for_label}}" class="custom-select form-control"> <option value='0'>Selección de Sucursal</option> {% for opciones in formulario.cod_sucursal %} {{opciones}} {% endfor %} </select> </div> The form is intentionally broken because is longer the render is: <form action="/tablaventas/recibo" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='0w3Y3WLmT6rbN488ohtG36LUMcS2t6XrhDu3X26V7fecg35kMkOzyv5kNXTRFu1Z' /> <div class="form-group"> <label for="encabezado-cod_sucursal">Cod sucursal</label> <select name="encabezado-cod_sucursal" id="id_encabezado-cod_sucursal" class="custom-select form-control"> <option value='0'>Selección de Sucursal</option> <option value="600">Pilgrim</option> <option value="200">Mandiola</option> <option value="100">Fch</option> </select> </div> views.py is: def tablaventas_recibo(request): if request.method=='POST': formu=VentasFormSet(request.POST, prefix='detalle') # formset encabezado=tablaVCPFormulario(request.POST, prefix='encabezado') # Formulario print(encabezado.errors) if formu.is_valid() and encabezado.is_valid(): codigo_sucursal=encabezado.cleaned_data co = formu.cleaned_data[1] print(codigo_sucursal) return HttpResponse('gracias') return HttpResponse(encabezado.errors) ...and ModelForm is: class tablaVCPFormulario(ModelForm): class Meta: model=VentasContrapuntoPilgrim fields='__all__' widgets = { 'titulo': TextInput, 'edicion': TextInput, 'fecha_contable':SelectDateWidget(attrs={'class': 'custom-select'}), 'cod_sucursal':SelectMultiple(choices=codigos_sucursal), } exclude = ('saldo','inicial','isbn',) prefix='encabezado' The exit tells me that cod_sucursal is None (it can´t catch the value), but is on the html into the template. I dont know, i am doing something wrong or i am missing something because the select value is noy caught and not sending on post method. Please, thanks in advance. -
Why an Internal Server Error ? TypeError : float() argument must be a string or a number, not 'BoundField'
I have created a movie renting app in Django 2.0 and Python 3.6. I am getting an error on BoundField and I am trying to add the new movie to the existing table in the database like movie_name and price. Bellow is mentioned code: #module.py file from django.db import models from django.forms import ModelForm class Customer(models.Model): f_name = models.CharField(max_length=50) l_name = models.CharField(max_length=50) address = models.CharField(max_length=125) cell = models.IntegerField(blank=True, null=True) class Movie(models.Model): genre = models.CharField(max_length=50) price = models.FloatField(blank=True, null=True) flag = models.BooleanField(default=True) user_id = models.ForeignKey('Customer', on_delete=models.SET_NULL, null=True) #______________________________________________________________________ #views.py code from django.shortcuts import render from .models import Customer, Movie # from django.http import HttpResponseRedirect from .forms import MovieForm, CustForm def dashboard(request): customer_data = Customer.objects.all() context = {'Customer_List': customer_data} return render(request, 'movie_renting_app/home.html', context) def movie_list(request): movie_data = Movie.objects.all() context = {"Movie_List": movie_data} return render(request, 'movie_renting_app/all_movies.html', context) def rented_movies(request): rented_movie = Movie.objects.filter(flag=True) context = {"Rented_Movies_List": rented_movie} return render(request, 'movie_renting_app/rent.html', context) def add_movies(request): if request.POST: form = MovieForm() print(request) m = Movie(genre=form['genre'], price=form['price'], flag=form['flag']) m.save() return movie_list(request) else: form = MovieForm() return render(request, 'movie_renting_app/new_movie.html', {'form': form}) def add_customer(request): if request.POST: form = request.POST print(request) c = Customer(f_name=form['f_name'], l_name=form['l_name'], address=form['address'], cell=form['cell']) c.save() return dashboard(request) else: form = CustForm() return render(request, 'movie_renting_app/new_customer.html', {'form': form}) def update_customer_info(request): … -
Display drop-down selection in django admin without selecting an object
Is it possible to show a drop-down selector in the model page before selecting an object and how would I achieve this (the page that lists every object and it's list_display's)? I want the user to be able to change the state of the object's choice field without having to click into the object, then changing it and finally pressing save. -
Django 1.11 media files not displayed
my urls file urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my settings STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' my template <a href="{{ courrier.piece_jointe.url }}">{{ courrier.objet }}</a> everything is set up correctly but when i click the link nothing the url show up http:127.0.0.1:8000/media/..... but the page is not redirected to the file content ! -
How can I limit the number of ManyToManyField in Django models?
I'm currently trying to implement some feature that users can track their recent visited stores in my website. To do that, I'm using ManyToManyField in Django models. Every time a user enters a detailed page of a store, the store object is stored in the user. But, I wanna use a queue and store only 10 stores, so when a 11th store is stored, the earliest one is removed so that only 10 stores can be stored. Is there a way to limit the number of ManyToManyField and remove the earliest one automatically? -
error on get text from image tessereact django
i'm try get text from a image(jpg) on spanish, but the result is strange characters. my code is this: import pytesseract from PIL import Image, ImageEnhance, ImageFilter from pytesseract import image_to_string #url image path = 'media/norms/temp.jpg' #get the text image = Image.open(path) text = pytesseract.image_to_string(image, lang='spa') print(text) the result is this: ,, .…c…… 1…¡_»€…m.a…m…1 ¿a¿f¿¿3_…k k…mmy … y : … … … o……… …… … … s…… … ………º… … … W…… ¿.º…………… n …… ……a.…………… …… …… …… ………… … EN……— o.… =¡ …… 13 M … Novrr|!5 & Rewqu c…… c…e……… de P…… me…… ue no…… a… …… dncnnuumz m… m…… 51Ru¡xglm …… Nm 157 de m de …… ¿. zum… mm… w.… eslab1:mmnnms que va…… a s…… p…au……=nn.na……n cnm¿vmmnsln1aime> .q………uyuo…e…m…… … a. … xul7ve …… Pvácncas He Ma…rmwa= pam … men…… de pmducms !u'mauáuHmscue ¡e =…x…e… … uuurma Dmumlunsl ¡— this is my image: this is my folder tesseract: please a little suggest or comment thanks !! -
Sending a file to a POST redirect URL
Let we send a POST request to a server (with a Django application) which returns 307 redirect to another server. The POST request contains a file (to be used on the second server). Is it safe to assume that the first sub-request will send only the headers and so the file won't be uploaded twice consuming much traffic? (I really think that this is not safe to assume, but my friend needs an authoritative opinion. So I ask others to point the answer, preferably with links to relevant standards.) -
ckeditor configuration in django admin
I need to add richtextfield to my admin panel in django, so i choose ckeditor, but ive got some promlems with configuration: when i try to move a row in django administration panel (with enter key) editor for some reason add P tag to my text, that i dont need (i mean in admin editor, not in template). Can i somehow deactivate it? Or replace with br tag? link I use default configuration of ckeditor settings.py CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', }, } models.py class Section_1(models.Model): order = models.IntegerField(blank=True, default=0) picture = models.ImageField(blank=True) text = RichTextField(max_length=200, blank=True) ytlink = models.URLField(blank=True) def __str__(self): return self.text class Meta: verbose_name = 'Секция 1' verbose_name_plural = 'Секция 1' integration in template: <div class="main-screen__middle-title"> {% for sec_1 in sec_1 %} {% if sec_1.order == 1 %} <h4 class="main-screen__middle-title_active" data-mScreen="mscreen{{ sec_1.order }}">{{ sec_1.text }}</h4> {% else %} <h4 data-mScreen="mscreen{{ sec_1.order }}">{{ sec_1.text }}</h4> {% endif %} {% endfor %} </div> so when i open template without {{ sec_1.text| safe }} i see this if i use it, ckeditor just ignore h4 tag link Questions are: 1) How to revome auto adding 'p' in admin panel? 2) How, if i use |safe to my variable, … -
Appending URL with query object
I'm querying a database for objects and passing it to my html file through my view. The way I have my urls.py set up is such that /index/object_primary_key - Therefore, each object in my database has its own URL. This is the code I typed thinking it would work, but I now know the URL function doesn't work that way: <a href="{% url 'index'%} {{object.pk}}">{{object.title}}</a> Is there a way to use a query and append it to a url? -
Reverse for 'onePart' with keyword arguments - issue
I've try to make my url like description/(party_number)-(pk), where party_number and pk are different for each object. But istead of this I get error: Reverse for 'onePart' with keyword arguments '{'pk': 10, 'nums':'A15151'}' not found. 1 pattern(s) tried:['description/(?:(?P[\d]+)-(?P[\d]+)/)?$'] in my views.py: def PartyNumView(request, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 2) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) return render_to_response('part_list.html', {'PartyNum': context}) def forOne(request, pk): onePart = get_object_or_404(Part, pk=pk) return render_to_response('singlePart.html', {'onePart': onePart}) my urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(?P<page_number>[\d]+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'description/(?:(?P<nums>[\d]+)-(?P<pk>[\d]+)/)?$', forOne, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] And part_list.html: {% for object in PartyNum %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url 'onePart' pk=object.pk nums=object.Party_number %}"> {{ object.Party_number }}</a></td> <td>{{ object.Film }}</td> <td>{{ object.Thick }}</td> <td>{{ object.Critical_temperature }}</td> <td>{{ object.R_s }}</td> {% endfor %} -
Invalidating Django session in JS without access to the server
I need the ability to invalidate the Django session even if there is no Internet connection (or the server is down, or anything). The session cookie is by default httpOnly, and I don't like to change it, so simply deleting it is not an option. Is there any standard way to deal with this issue? The relatively simple solution is to write a custom middleware on top of Django sessions. This middleware could add a secondary session token, say sessionid2, that would be acessible (and deletable) from Javascript. Both would be checked simultanously, so just one missing would invalidate the session. However, I would strongly prefer to use some of-the-shelf solution, if one exists. The application is supposed to work as Chrome's Progressive Web App, so I'll be happy with a Chrome-specific solution if there is some. -
Django - Relate to a user group a new record of another model
I want that when creating a new record in another model, it automatically relates to each of the users in another model. Example: I have a 3 models: - Events - Participants - Users When adding a new event you must add all users to the list of participants. I know I can do it with a cycle but I want to know if there is another way in django something like for example event = Events.objects.get (id = instance.id) participants = Participants (id_event = event, id_user = User.objects.all ()) participants.save () -
Attribute error: module 'volga.views' has no attribute 'add'
Its Django , i have put the html files , but when I run the server , it show the attribute error . Module 'volga.views' has no attribute 'add' from django.urls import path from . import views urlpatterns = [ path('', views.index), path('add/', views.add) ] -
Converting String to int array
I'm stucked with some problem. I've sent int array from JS to Python via AJAX and it has been converted to JSON (as I used JSON.stringify()), so now it's a string "[1,2,3,4,5]". How can I convert it in Python back to int array [1,2,3,4,5]? I've tried to convert this array to numpy array np.asarray(features_user, dtype="int"), but this not helped -
Use components in Django Framework
I'm struggling with using components in Django. My project: I'm working on a weblog that presents the current blog post. In the sidebar I want to include a component that lists ten latest posts and ten related posts. Each of these components are not only templates, but also include logic (which I rather would not include in the template using template tags). What would be the best way to go to include such components? -
Displaying detailed data from multiple Django models in html
I have the below Django model. As you can see, the directory of each strain is dynamic, and the Photos_save model is inline to the strain model (it lets me save multiple photos for each strain). I would like to have a detailed view of each strain and the pictures associated with it. Could any of you help me with the views.py and HTML code required to accomplish this? I'm quite new to Django, and so far I have managed to display all of the information of the strain, including the photos, on the index page (but I want the users to be able to click on the name of each strain and see a detailed view). class Strain(models.Model): """; Model representing strains. """ type_strain = ( ('W', 'Wild Type'), ('G', 'GMO'), ('P', 'Prospected'), ) def strain_directory_path(instance, filename): return 'strain_{0}/{1}'.format(instance.strain_name, filename) strain_name = models.CharField(max_length=100, blank=False, null=True, default=None) strain_description = models.CharField(max_length=500, blank=True, null=True, default=None) data_of_generation = models.DateField(null=True, blank=True, default= None) strain_source = models.CharField(max_length=500, blank=True, null=True, default=None) strain_parent = models.ForeignKey('Strain', null=True, blank = True, on_delete= models.CASCADE, default= None) strain_type = models.CharField(max_length=1 , blank=True, null=True, default=None, choices= type_strain) class Photos_save(models.Model): import datetime def strain_directory_path(instance, filename): return 'strain_{0}/{1}'.format(instance.strain_name, filename) strain_name = models.ForeignKey(Strain, on_delete=models.CASCADE, default= … -
Inlineformset without foreign key
I'm trying to implement an inline formset for two models in a graph database. The problem that I'm running into is that formsets are designed with foreign keys in mind. I'm relating a model to itself through another model. For simplicity sake, let's call them a Person model and a FriendRel model: Person -[FRIENDS_WITH]-> Person FriendRelFormSet = inlineformset_factory(Person, FriendRel, form=FriendRelForm, extra=1) I've tried setting the fk_name=None argument, but I am still met with the following error: ValueError: 'django_rel.RelationshipMeta' has no ForeignKey to 'django_node.NodeMeta'. So now I am looking into the documentation below, but it is a bit abstract for my skillset. Am I banging my head against the wall with this, or is it possible to avoid the whole foreign key thing? Overriding methods on an InlineFormSet https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#overriding-methods-on-an-inlineformset -
Django input validation to_python method
When a field is created in Django and its clean method is called you see a to_python method is being called. https://docs.djangoproject.com/en/2.0/ref/forms/fields/#django.forms.Field.required Why this (to_python) method is called when it just returns the value. def clean(self, value): """ Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value def to_python(self, value): return value -
Django prefetch_related with FK into a view
I am following the Django official site tutorial for the polls app and after finish it I am working in some improvement to acquire more knowledge about Django. My first purpose is to change the view to show all questions and possible answers to it. The models are: class Question(models.Model): question_text = models.CharField(max_length=200) publication_date=models.DateTimeField() def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.publication_date <= now was_published_recently.admin_order_field = 'publication_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text As you can see 1 choice is related to 1 question. In the view I am able to render all the questions, all the choices, but not a question and his choices. To do that I tried the following: View: from django.http import HttpResponse,HttpResponseRedirect from .models import Choice,Question from django.shortcuts import get_object_or_404,render from django.urls import reverse from django.views import generic from django.utils import timezone class IndexView(generic.ListView): template_name = 'surveys/index.html' context_object_name = 'question_choice_list' def get_queryset(self): return Choice.objects.all().prefetch_related('question') html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'surveys/style.css' %}" /> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if question_choice_list %} <ul> {% for …