Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django site administration running but Posts link not loading
New to Django & following Django Girls' tutorial. Here I was setting up admin, the superuser, and then running the site which worked. I clicked on a link, Add Post or Post, but neither loaded. img of admin site OKAY img of Post not loading here is the text files just in case, models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title for admin.py from django.contrib import admin from .models import Post #Register your models here. admin.site.register(Post) :[ I don't see any errors via sublime text, and It never indicates error. lol. -
Using UpdateView's success_url to return to PagedFilteredTableView
I followed this discussion to implement a table with filtered content. In the displayed table, I have a cell in each row that allows a user to click on a link and edit that row's data. In the process, UpdateView is used. On a submit from UpdateView's form, I'd like to return to the filtered content/table that was used to initiate the connection for editing the row's data. In my code below, the 'next is {}' prints the desired URL but the framework returns an error: The view ...didn't return an HttpResponse object. It returned None instead. Which function should I use to have the UpdateView return to the desired URL? class UpdateMyModelView(UpdateView): model = MyModel template_name='data_form.html' fields = ['A', 'B', 'C'] def form_valid(self, form): instance = form.save(commit=False) r = self.request p = r.POST print ('request is: {}'.format(r)) print ('p is {}'.format(p)) print ('request POST.next is: {}'.format(p['next'])) self.success_url = p['next'] print ('next is {}'.format(self.success_url)) super(UpdateMyModelView, self).form_valid(form) -
Django Password Resest Via Email
I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. I took by example this question and this site. But my problem is a bit different. I don't have a local database containing the users, so I cannot perform operations over their attributes. I receive user data via an API (user id, user email, user password). So, which is the best way to generate a unique link to send via email to user so that this link would tell me who the user is and allow me to reset his/her password? And also, how could I redirect it in urls.py? I wish that this link could be used only a single time. My views.py is like this: def password_reset_form(request): if request.method == 'GET': form = PasswordResetForm() else: form = PasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] content_dict = { 'email': email, 'domain': temp_data.DOMAIN, 'site_name': temp_data.SITE_NAME, 'protocol': temp_data.PROTOCOL, } subject = content_dict.get('site_name')+ ' - Password Reset' content = render_to_string('portal/password_reset_email.html', content_dict) send_mail(subject, content, temp_data.FIBRE_CONTACT_EMAIL, [email]) return render(request, 'portal/password_reset_done.html', {'form': form,}) return render(request, 'portal/password_reset_form.html', {'form': form,}) And the template the e-mail I'm sending is: {% autoescape off %} You're … -
Django - Why are variables declared in Model Classes Static
I have been reading and working with Django for a bit now. One of the things that I am still confused with is why the model classes that we create in Django are made up of static variables and not member variables. For instance class Album(models.Model): artist = models.CharField(max_length=128, unique=True) title = models.CharField(max_length=128, unique=True) genre = models.CharField(max_length=128, unique=True) def __unicode__(self): return self.name I read this page here which explains static and instance variables in python however i am still confused as to why Django wants the field variables in models be static ? -
Django: Get distinct values from a foreign key model
Django newbie, so if this is super straightfoward I apologize. I am attempting to get a listing of distinct "Name" values from a listing of "Activity"s for a given "Person". Models setup as below class Activity(models.Model): Visit = models.ForeignKey(Visit) Person = models.ForeignKey(Person) Provider = models.ForeignKey(Provider) ActivityType = models.ForeignKey(ActivityType) Time_Spent = models.IntegerField(blank=True, null=True) Repetitions = models.CharField(max_length=20, blank=True, null=True) Weight_Resistance = models.CharField(max_length=50, blank=True, null=True) Notes = models.CharField(max_length=500, blank=True, null=True) class ActivityType(models.Model): Name = models.CharField(max_length=100) Activity_Category = models.CharField(max_length=40, choices=Activity_Category_Choices) Location_Category = models.CharField(max_length=30, blank=True, null=True, choices=Location_Category_Choices) I can get a listing of all activities done with a given Person person = Person.objects.get(id=person_id) If I then use the activity_set to get all activities, that works to show all of them activity_list = person.activity_set.all() What I can't sort out is how to generate a list of distinct/unique Activity_Types found in person.activity_set.all() This is pretty straightforward in plain ol' SQL, so I know my lack of groking the ORM is to blame. Thanks. -
Why doesn't my selenium webdriver authentication work (Django 1.9)
I am going through a process of registering and logging in for a list of users. I am using the same username and password to make things simple. from selenium import webdriver from selenium.webdriver.common.keys import Keys import re for address in geolocations: # register browser.get("http://127.0.0.1:8000/register") username = browser.find_element_by_id("id_username") print("username is being set as " + re.sub(' ', '', address)) password = browser.find_element_by_id("id_password") print("password is being set as " + re.sub(' ', '', address)) location = browser.find_element_by_id("location") submit = browser.find_element_by_id("register") username.clear() password.clear() location.clear() username.send_keys(re.sub(' ', '', address)) password.send_keys(re.sub(' ', '', address)) location.send_keys(address) location.send_keys(Keys.RETURN) submit.click() browser.implicitly_wait(1) # login browser.get("http://127.0.0.1:8000/login") username = browser.find_element_by_id("username") password = browser.find_element_by_id("password") username.clear() password.clear() password.send_keys(re.sub(' ', '', address)) # addresses have spaces print("password is being set as: " + re.sub(' ', '', address)) browser.implicitly_wait(2) submit = browser.find_element_by_id("submit") submit.click() browser.implicitly_wait(2) browser.quit() Even though the same string is being used for registering and logging in, the login authentication is not working. But the same username/password combos work when I register/login manually. Can anyone tell me what's causing this? -
django wizard - saving separate forms to a single model
I'm using django wizard to have multiple forms (will have several pages of forms in the end). I have a single custom user model and I've split the signup into several modelforms (using Meta, fields). However I'm not clear on django wizard how the done method should be setup to save all the data from the forms to a single instance of user? models.py class User(AbstractUser): name = models.CharField(_("Name of User"), blank=True, max_length=255) account_name = models.CharField(max_length=255) account_number = models.IntegerField() def __str__(self): return self.username forms.py class SignupForm(allauthforms.SignupForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) class UserAccountForm(forms.ModelForm): class Meta: model = User fields = ['account_name', 'account_number', ] views.py SIGNUP_FORMS = [ ('signup', SignupForm), ('direct_debit', UserDirectDebitForm), ] TEMPLATES = { 'signup': 'account/signup.html', 'direct_debit': 'site/directdebit.html', } class SignupWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): xxxxxxx return HttpResponseRedirect(reverse('home')) signup_view = SignupWizard.as_view(SIGNUP_FORMS) -
Manually combine multiple Django QuerySets, and serialize result using DRF
I have been researching this for a couple days. Unfortunately, all of the proposed solutions I have found so far don't exactly work for me. I am looking to manually combine two Django QuerySets into a single Django model, which I then want to serialize using a Django Rest Framework serializer. I then use the serializer for outputting JSON. I have found various solutions on SO suggesting the use of itertools and chain, but it is unclear then how to serialize the result of chain. Note that my goal here is for web application performance purposes. Each QuerySet works fine independently, but it requires two separate Ajax calls to retrieve the results. I would prefer to make only one Ajax call, manually combine the results on the server-side, then return the combined JSON. -
How to print a Django date / time field?
I am trying to print a Django date / time field in the shell via the "str" function, but I get an error: class Foo(models.Model): owner = models.ForeignKey(User, db_index=True, editable=False) dt_tm = models.DateTimeField(db_index=True) def __str__(self): return 'owner: ' + str(self.owner) + ', date / time: ' + str(self.dt_tm) >>> foo = Foo(user=mr_bar, dt_tm=now()) >>> foo ... TypeError: Can't convert 'datetime.datetime' object to str implicitly I am not fussy about the date / time format as I won't be using this elsewhere in my application, just in the shell. -
In Django, how to add on_delete constraint on an inherited model
I have two models in Django: from django.db import models class Car(models.Model): ... class Buick(Car): ... Currently I can't delete a car with a related buick because I get this error: django.db.utils.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`localdb`.`buick`, CONSTRAINT `car_ptr_id_refs_id_b38c9532` FOREIGN KEY (`car_ptr_id`) REFERENCES `car` (`id`))') So I'd like to add a cascade delete buicks when I delete a car, but to where? Django's on_delete is applied to a ForeignKey. I can't think of a django way to do this, only through mysql. -
upload app to the server
HI everyone I have a pretty basic question, I create a project in Django on my local server, I create several apps too, and now I want to move only the apps to one project in Django on a server. To do that I copy the entire file of one of my apps, and I move to the server, where are many apps. I modified my settings.py to add the name of my app in INSTALLED_APPS, and modified the file urls.py to add the URL of my app. Restart the server, and I still don't see the app. How I can see in the server the full path of the other apps, to see what happens with my own app. I forgot something when I move the app to the server! -
Django find request headers before csrf protections
I'm trying to debug a complex problem I have with csrf tokens. How can I print out the request headers before the view answers with a 403 - CSRF Failed: CSRF token missing or incorrect? My view is answering with that 403 error, I'm pretty sure I am sending the token in the ajax request. So, I need to see what headers is django receiving. Where can I get them? which middleware has the task of checking the csrf token? I'm not sure how relevant is this, but I'm using Django Rest Framework and the view that receives the request looks like this: class CreateCartItem(generics.CreateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (JSONRenderer,) serializer_class = CartItemSerializer -
how to pass quantity in pinax stripe subscription?
i am using the pinax stripe package in my django project where a user can enroll multiple people for subscriptions. i know that stripe has a quantity parameter which can be passed for subscriptions but could not find it in pinax package. Can someone guide me on how can i pass the quantity parameter in pinax-stripe package. -
When I try to resubmit the form in Django, the site becomes unresponsive. What should I be doing?
I created a simple form class as follows: from django import forms class NameForm(forms.Form): faculty_id = forms.CharField(label='Faculty ID:',max_length=20,initial="") password = forms.CharField(label='Password:',max_length=20,initial="") batch = forms.CharField(label='Batch:',max_length=2,initial="") section = forms.CharField(label='Section:',max_length=1,initial="") And I created a simple template: {% extends "header.html" %} {% block content %} <h2>Register</h2> <form action="http://127.0.0.1:8000/sample_graph/" method="POST" >{% csrf_token %} {{form}} <input type="submit" value="Register"> </form> {% endblock %} In views.py there is a respective method that calls the above template: def register_user(request): if request.method == "POST": #"i guess" this will never happen as when the user clicks the submit button, he is directed to blog/sample_graph (look at the forms's action), the corresponding view method for which is graph() as defined below after this method form = NameForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('http://127.0.0.1:8000/blog/sample_graph/') else: form = NameForm() return render(request, 'blog/register.html', {'form': form}) The view method for blog/sample_graph is: def graph(request): '''form = NameForm(request.POST) if form.is_valid(): username = form.cleaned_data['your_name']''' if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): faculty_id = form.cleaned_data['faculty_id'] password = form.cleaned_data['password'] batch = form.cleaned_data['batch'] section = form.cleaned_data['section'] <do something...> return HttpResponse(buffer.getvalue(), content_type="image/png") #returning an image as the HttpResponse The scenario: The user navigates to ~/blog/register, where he fills the form (that is expanded from the mentioned html template), and hits submit … -
Django models in Many2Many relationship: filter by a group of member
I have these models: class Skill(models.Model): name = models.CharField(max_length=20) class Engineer(models.Model): name = models.CharField(max_length=20) skill = models.ManyToManyField(Skill) class City(models.Model): city = models.CharField(max_length=20) I have 2 questions, please spare your time to help me. Thank you :) 1) I would like to filter Engineer by a group of skills. Let's say I need to filter engineers, who have these skills ['HTML', 'python', 'CSS']. How can I do that? 2) I would like to filter Engineer by a group of skills AND in a specific area. Let's say I need to filter engineers, who have these skills ['HTML', 'python', 'CSS'] AND this engineer must live in Anaheim. How can I do that? -
Why is my get_form_kwargs not passing variable to form?
I am trying to pass a variable from a view to a form. The variable controls what results populate a dropdown box in the form. It's a simple string such as 'CANINE' which will pull results from the Breed model (containing many species) such that only dogs are returned. I've followed several example to the letter and just cannot get variable to be found in the form. The value is always 'None'. My guess is that only specially named variables are passable in kwargs to a not-yet-built form, but I'm not sure. Any guidance as to what I'm missing would be much appreciated. I've been at this for hours and am making no headway. Form: class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ( 'species', 'breed', # FK to Breed model 'gender', 'name', 'client', 'weight', 'date_of_birth', 'colour', 'remarks', 'microchip', ) def __init__(self, *args, **kwargs): # The form is not expecting these kwargs to be passed in, # so they must be popped off before anything else is done. species_code = kwargs.pop('species_code', None) super(PatientForm, self).__init__(*args, **kwargs) # if species_code (passed in from view) is 'FELINE' then filter the queryset # on Breed model to only return a list of cats, … -
Porque me sale el siguiente error? [on hold]
Hello I get the following error, what I want is to do the query in django me seeping through the current month, but I get the following error: expected string or buffer My code is as follows: ahora = datetime.now() mejor = Clasificacion.objects.filter(fecha = ahora.month ).values('clasificador').annotate(total=Sum('total')).order_by('-total')[:1] -
Migration clashes with forms.py
The command python manage.py makemigrations fails most of time due to the forms.py, in which new models or new fields are referenced at class definition level. So I have to comment each such definitions for the migration to operate. It's a painfull task. I don't understand why the migration process import the forms.py module. I think that importing models modules should be sufficient. Is there a way to avoid those errors ? -
ASCII error with my Django API
I'm learning a tutorial in order to study Django so I'm really new with that. I started a project which is named etat_civil and I created an application which is named blog. I get this kind of things : My blog views.py file looks like : #-*- coding : utf-8 -*- from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home (request) : text = u"""<h1>Bienvenue sur mon blog ! </h1> <p>Les crêpes bretonnes ça tue des mouettes en plein vol ! </p>""" return HttpResponse(text) and my etat_civil urls.py file looks like : #-*- coding : utf-8 -*- from django.conf.urls import url from django.contrib import admin from blog import views urlpatterns = [ url(r'^accueil$', views.home), ] Then, in the terminal I executed the command line : python manage.py run server But I get this error and I don't know from where is this error : macbook-pro-de-valentin:etat_civil valentinjungbluth$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x1109e1050> Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 361, in … -
Django - inlineformset-factory (How to Edit)
I saw many tutorials and questions in many foruns and websites. And when I search for "inline formset-factory" are many links appear. But few talk about how edit, with inline formset-factory. I have a problem in my project, I did it save, but when I will try edit, rise some errors This is my code class Dia_Producao(models.Model): id = models.AutoField(primary_key=True) diaTrabalho = models.CharField("Dia de Trabalho", choices=DIATRABALHO_CHOICES, blank=True, null=False, max_length=10) dataTrabalho = models.DateField("Data de Trabalho") fkSemanaMes = models.ForeignKey(Semana_Mes, on_delete=models.CASCADE,verbose_name="Semana do Mês") dataCadastro = models.DateTimeField("Data Cadastro", auto_now=False, auto_now_add=True) statusBaixa = models.BooleanField("Status Baixa") def __str__(self): return "%s - %s" %(str(self.diaTrabalho), self.fkSemanaMes) def get_absolute_url(self): view_name = "dias_trabalho" return reverse(view_name) class Meta: verbose_name_plural="Dia Produções" class Digi_Usu(models.Model): id = models.AutoField(primary_key=True) fkDiaProducao = models.ForeignKey(Dia_Producao, verbose_name="Dia Produção") fkUsuario = models.ForeignKey(Usuario,on_delete=models.CASCADE, verbose_name="Usuário") totalDia = models.IntegerField("Total do Dia") def __str__(self): return "%s / %s" %(self.fkDiaProducao, self.fkUsuario) def __unicode__(self): return str(self.fkDiaProducao) class Meta: verbose_name_plural = "Dia Semana" class Hora(models.Model): hora = models.CharField("Hora Trabalho", choices=HORA_CHOICES, blank=True, null=False,max_length=6) qtdlHora = models.IntegerField("Total Hora") dataCadastro = models.DateTimeField("Data Cadastro", auto_now=False, auto_now_add=True) fkDigiUsu = models.ForeignKey(Digi_Usu, verbose_name="Dia Producao/Usuário") def __str__(self): return self.hora def __unicode__(self): return self.hora class Meta: verbose_name_plural = "Horas" in my form.py. HoraFormSet = inlineformset_factory(Digi_Usu, Hora, fields='__all__', extra=0, max_num=24) views.py class DigitalizacaoCreateView(CreateView): model = Digi_Usu, Hora, … -
Modify Django settings programmatically
I have Django project. I need to add app to INSTALLED_APPS or change template config using another python script. What is the best way to do that? I have several ideas. Open settings.py as text file from Python and modify it. Seems to be wheel reinvention and opens box with many errors (escaping and so on). Use Python modules like ast but it is pretty low level and more for read access (and I need to write data back). Use some Django tools (I am not sure if such tool exists). What is the best way to do that? PS: Parse a .py file, read the AST, modify it, then write back the modified source code is related, but it is not Django specific and pretty old. -
how to get all fields in a object.filter() django
my view imports from .models import Car, Owner from django.db import models def switchingowners(request): ok my models look like class Owner(models.Model): carID = models.ForeignKey(Car) Owner_Entry_Number = models.IntegerField() Owner_Date = models.DateField('Proprietor start date', null=True, blank=True) Owner_Last_Name = models.CharField(max_length=50, null=True, blank=True) Owner_First_Name = models.CharField(max_length=50, null=True, blank=True) Owner_Middle_Initial = models.CharField(max_length=6, null=True, blank=True) Owner_Address = models.CharField(max_length=80, null=True, blank=True) my database back in has information in all fields ownersofcar = Owner.objects.filter(CarID = request.user['CarID']) it tells me TypeError and the filtered objects i see are self [<Owner: 1248612 MALCOLM DESRIVIERES >, <Owner: 1248612 JULIETTA REMY >, <Owner: 1248B612 THERESA DESIR >, <Owner: 1248B612 ALEXANDER JEAN>] where on earth are the other fields? i dont see any documentation on secifying which fields i want to receive cause i want them all! each field has important information im basically switching all the names from one car to another car/ multiple cars but filter is not giving back all the fields -
How to pass bound form as context to TemplateView via HttpResponseRedirect
I'm trying to put multiple account management forms on the one page with a TemplateView as follows: class AccountManagement(TemplateView): """ Generic view to display the account management template """ template_name = 'accountmanagement.html' def get_context_data(self, **kwargs): context = super(AccountManagement, self).get_context_data(**kwargs) context['user'] = self.request.user # pass unbound form instances to context # if there aren't bound instances already there if context.get('usercreate_form') is None: context['usercreate_form'] = UserCreateForm() if context.get('password_form') is None: context['password_form'] = PasswordChangeForm() return context I'm handling UserCreation with a FormView (because this example is simplified; I also need some non-model data, and CreateView needs a ModelForm). This view processes the POST request, and is supposed to redirect to the TemplateView with a success message, or pass the invalid bound form back to the context so that the template can render the errors. Trouble is, it doesn't do the part in bold italics (obviously HttpResponseRedirect doesn't pass the context). Why? How can I get the bound form back into the TemplateView context here so that the form.errors will be available and the user doesn't have to retype the data? class UserCreate(FormView): """ Generic view to create a User. """ form_class = UserCreateForm http_method_names = ['post',] success_url = reverse_lazy('accountmanagement') failure_url = reverse_lazy('accountmanagement') def … -
Modal doesn't open with django/python
I'm having a little problem with a modal in django/python. I have a link which calls an id and the id is a modal. However, the modal isn't opening. I'm pretty sure that this is happening because the link is inside a "automatic" form, but I'm new in django and python so I have no idea. The code is: {% block body %} <div class="col-lg-12 page-content"> <h1 class="content-title">Meus Dados</h1> <hr class="star-light"> <div class="form-content"> <form class="form-horizontal" method = 'POST' action="/user/edituser/"> {% csrf_token %} {% for field in form_user %} {% bootstrap_field field exclude="password,repeat_password" %} {% endfor %} <div class="button-div"> <a class="btn btn-info btn-block btn-password" href="#change-password" data-toggle="modal">Alterar senha</a> {% buttons %} <button class="btn btn-success btn-block btn-edit" type = 'submit'>Salvar Dados</button> {% endbuttons %} </div> </form> <a class="btn btn-danger btn-block btn-delete" href="/user/delete" name="delete">Excluir minha conta</a> </div> </div> <div class="modal hide" id="myModal"> <div class="modal-header"> <button class="close" data-dismiss="modal">&times;</button> <p class="modal-title" id="myModalLabel">Change Password</p> </div> <div class="modal-body"> <div class="row"> <div class="modal-col col-sm-12"> <div class="well"> <form method="post" id="passwordForm"> <input type="password" class="input-lg form-control" name="password1" id="password1" placeholder="New Password"> <input type="password" class="input-lg form-control" name="password2" id="password2" placeholder="Repeat Password"> </form> </div> </div> </div> </div> <div class="modal-footer"> <a href="#" class="btn btn-success btn-bloc">Alterar Senha</a> </div> </div> {% endblock %} Any doubts, please ask. Thanks. -
Django - Get data from a form that is not a django.form
I am working with Django in order to do a quite simple web application. I am currently trying to have a succession of forms so that the user completes the information bits by bits. I first tried to do it only in HTML because I wanted to really have the hand on the presentation. Here is my code. I have two templates, create_site.html and create_cpe.html. I need to get informations from the first page in order to know what to ask in the second page. Here is my create_site.html <body> <form action="{% url 'confWeb:cpe_creation' %}" method="post" class="form-creation"> {% csrf_token %} <div class = "form-group row"> <label for="site_name" class="col-xs-3 col-form-label">Name of theSite</label> <div class="col-xs-9"> <input id="site_name" class="form-control" placeholder="Name" required="" autofocus="" type="text"> </div> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Créer</button> </form> </body> And here is the views.py that I'm using to do all of this : def site_creation(request): template = loader.get_template('confWeb/create_site.html') return HttpResponse(template.render(request)) def cpe_creation(request): if request.method == "POST" : print(request.POST) What I would like to do is to get the value of the input of my form, inside my view "cpe_creation". I tried getting informations from the "request" object but I didn't manage to do that. Maybe I'm lacking very basic …