Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a pull-down menu in Django?
I try to create a pull-down menu in Django, but there is no such a menu in the output. Here is my view.py: class MajorProgramForm(forms.Form): major_programs = forms.ChoiceField(label="Major Programs", choices=MAJORS, required=True) def choose_major_program(request): if request.method == "GET": form = MajorProgramForm(request.GET) context["form"] = form return render(request, "program.html", context) And here is my template.py: <html> <head> <title>Choose Your Courses</title> </head> <body> <div id="header"> <h1>Choose Your Courses</h1> </div> <div class="frame"> <form name="form", action="{% url 'choose_major_program' %}" method="GET"> {% csrf_token %} <ul> {% for option in form.major_programs.choices %} <li>{{ option.name }}</li> {% endear %} </ul> <input type="submit" value="Submit"> </form> </div> </body> </html> And the result is this: A web page Thanks! -
DJANGO customer USER field ? import error ImportError: No module named simplemathcaptcha.fields
i am adding user field. i got this error from my admin ImportError: No module named simplemathcaptcha.fields i have no idea of this. plz help me -
Media images not showing, even though they successfully load on the page
Uploaded images from users are stored in the media folder, like most Django apps. However for some reason they stopped showing after I made a few changes in my app. The weird thing is, when I click inspect element on the image div, it shows the img src and it's correct. When I hover over the img src: <img src="/media/REC-2.jpg">, it just says 'Could not load the image'. Keep in mind, all of my static files show fine. Just the media images, (images that are uploaded through a user Post), arn't showing. There's also a weird thing in my view that could indicate what the problem is. Here's my code: choices.py CATEGORY_CHOICES = ( ('1', 'news'), ('2', 'sport'), ('3', 'technology'), ) urls url(r'^(?P<category>\w+)/', boxes_view, name='bv'), views def boxes_view(request, category): print('initial', category) for a, b in CATEGORY_CHOICES: if b == category: category = a print('category', category) posts = Post.objects.filter(category=category) for post in posts: print('POST', post.id) return render(request, 'boxes.html', {'posts': posts}) Here's what comes up in my terminal after loading the page (http://127.0.0.1:8000/news/): initial news category 1 POST 1 POST 2 ... POST 241 POST 242 [09/Mar/2017 23:39:33] "GET /news/ HTTP/1.1" 200 19661 [09/Mar/2017 23:39:34] "GET /static/css/base.css HTTP/1.1" 304 0 initial media … -
Can Django template variables be used inside Jquery/Bootstrap to control collapse plugin?
I'm working Django CB Views and my template currently has form fields being rendered from an UpdateView. I've split the form and rendered the fields as individual elements. The form has 4 fields, 2 of which are currently under a bootstrap collapse plugin. This plugin is set to hide by default. <div id="advanced_panel" class="panel-collapse collapse"> But, if the 2 fields are populated, I want to set it to: <div id="advanced_panel" class="panel-collapse collapse in"> This is what I have so far. My template: {% block content %} <form action="" method="post">{% csrf_token %} {% include 'partials/form_field.html' with field=form.title %} {% include 'partials/form_field.html' with field=form.body %} <a class="btn btn-default" data-toggle="collapse" href="#advanced_panel" aria-expanded="true" aria-controls="advanced_panel">Advanced</a> <div class="panel-collapse collapse" id="advanced_panel"> <div class="card card-block"> {% include 'partials/form_field.html' with field=form.responder_name %} {% include 'partials/form_field.html' with field=form.response %} #Only show if these two fields exist. </div> </div> <a href="{% url 'backend_reviews' %}" class="btn btn-default">Cancel</a> <input type="submit" class="btn btn-primary" value="Update Review" /> <a href="{% url 'backend_reviews_delete' review.pk %}" class="btn btn-warning pull-right">Delete Review</a> {% endblock %} How can I do this, maybe using {% if %} and Jquery some how? -
Django Runserver crashes due to autoreload?
so i'm very new to Django. But my problem is as follows: When I create a project, the runserver often won't start. I type: python manage.py runserver Powershell freezes for a while and says: "Python is not responding" The Problem does not appear when typing: python manage.py runserver --noreload I am using Windows 10 and Django 1.10.6 as well as Python 3.6 The problem has also been reported on the forum of djangoproject but there was no solution offered. Is there any way to fix this? Will disableling autoreload affect working with the Localhost? Thank you. -
Take an informations from a form and send it somwhere using soap
I need to take informations from a form and send it somewhere using soap ? and to use this form to submit something to the database ? I need a simple example by django. please Help me :) -
Blog Tagline vs Headline in Django Sample
The Official Django 1.10 documentation gives an example of a models.py for a blog app with the following, class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) My question is what is the difference between the tagline and headline? Why give an Entry a name and tagline through the Blog model? -
Django - __init__() missing 2 required positional arguments: 'user' and 'request'
What i want to achieve: Current admin (who are logged in) should create a new admin without having to change the admins (who are logged in) association name from a dropdown-list. Basically want the new admin to be in the same association as the current admin who are logged in. Still a newbie so appreciate your help =) models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Meta: db_table = 'Administrator' class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' def __str__(self): return self.asoc_name forms.py class SignUpForm(forms.ModelForm): association = forms.ModelChoiceField(queryset=Association.objects.none(), widget=forms.Select(attrs={'class': 'form-control'}), required=True) class Meta: model = Administrator fields = [..., 'association',...] def __init__(self, user, request, *args, **kwargs): self.user = user self.request = request qs = Administrator.objects.filter(association=self.request.user.association) super(SignUpForm, self).__init__(*args, **kwargs) self.fields['association'].queryset = qs views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if not form.is_valid(): return render(request, 'admin/signup.html', {'form': form}) else: ... asoc_pk = form.cleaned_data.get('association') asoc = Association.objects.get(id=asoc_pk.pk) ... Administrator.objects.create_user(... association=asoc, ...) user = authenticate(... association=asoc, ...) return redirect('/') else: return render(request, 'admin/signup.html', {'form': SignUpForm()}) -
Trying to launch pgadmin4 on Windows, but it will not connect to the server. Getting this message
Trying to launch pgadmin4 on Windows, but it will not connect to server. Getting this message --Does not connect to server -
Django REST Framework, create nested serializers
I have 2 models linked by a Foreign Key field, But I cannot create objects for both of them together. I have tried the following - models.py class MyUserManager(BaseUserManager): def create_user(self, e_mail, user_type, iaccept, password=None): if not e_mail: raise ValueError('Users must have an e-mail address') user = self.model(e_mail = e_mail, user_type = user_type, iaccept = iaccept) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, e_mail, user_type, iaccept, password): user = self.create_user(e_mail, user_type, iaccept, password = password,) user.is_admin = True user.is_active = True user.save(using = self._db) return user class User(AbstractBaseUser): name = models.CharField(max_length = 255, blank = False, null = False) user_name = models.CharField(verbose_name = 'User Name', max_length = 255, blank = False, null = False) e_mail = models.EmailField(verbose_name = 'E Mail', max_length = 255, unique = True, blank = False, null = False) iaccept = models.BooleanField(default = True, blank = False, null = False, verbose_name = 'I do accept') is_admin = models.BooleanField(default = False, blank = True) [--other--] objects = MyUserManager() class Company(models.Models): name = models.CharField(verbose_name='Name', max_length = 255, unique = True, blank = True, null = True) created_by = models.ForeignKey(User, verbose_name = 'Created by', default=get_current_user, related_name = 'company_created') [--other--] Now, I have a serializer.py . I want that whenever … -
Django displays wrong user account
We're running a Django 1.9 app with around 200K users on Heroku. We normally see around 300 to 1000 active users any given time. Today we received a complaint from one of our users that when she logged in, using her credentials, she was in another user's account. She logged out and tried again, only to see another user this time. We received the same complaint from another user a couple of months ago but we could not reproduce the issue. We're still unable to reproduce it. However it's even more critica, as we're storing sensitive PII now. settings.py MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', 'pipeline.middleware.MinifyHTMLMiddleware' ] CSRF_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.humanize', . . . ] We're using Heroku's PostgreSQL DB as the session storage. Any ideas what we might be doing wrong? -
Django not seeing all STATIC_DIRS
In development mode, my django app is serving static files from *one of the STATICFILES_DIRS, but not the other. Here is my code in a settings.py file: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'bower_components'), # OK os.path.join(BASE_DIR, 'practice_custom'), # Not OK ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] Files in bower_components are found, but files in practice_custom are not. Both directories are in the same place (top level). If I rename the bower_components directory to bower_componentszzzzzz then the files are not found, which means they were being found via the staticfiles app. FileSystemFinder also seems to be working, in fact I put print statements in the code in the find() method(---looking for:), and it shows the paths being provided, as you can see they are formatted the same, but one results in a 404. ---looking for: practice_custom/xyz/style.css [09/Mar/2017 21:55:11] "GET /static/practice_custom/xyz/style.css HTTP/1.1" 404 1732 ---looking for: bower_components/c3/c3.min.css [09/Mar/2017 21:55:11] "GET /static/bower_components/c3/c3.min.css HTTP/1.1" 200 2043 Any ideas? -
How to share a Django database with another Python app?
Is it a good practice to just import the models of my Django app in the secondary app and query the database? Does it have any performance issues or something? Actually the second application is a simple lightweight websocket server. -
How to save and pass token a through request object in Django?
So I'm trying to authenticate against a token-based authentication microservice. I know this is not ideal, but just to start out with I have written this quick middleware. middleware.py def process_request(self, request): if request.token = None: pass else: username = validate_token(request.token) request.username = username views.py def login(request): form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): my_token = authservice_login(user,pass) request.token = my_token My question is, once someone has logged in and a token is returned, how do I keep this token persistent between all requests? I guess I'm a little foggy about the Django request object. If I login and then go to other pages where other views are called, do I still have access to the request.token that I created during login? I think what I'm ideally wanting is after a login, to pass this token to all requests via the middleware? -
"Couldn't import Django..." message when trying to migrate database to Heroku
I have previously push my app to Heroku and everything worked fine but now after I installed some packages such as node.js and npm the migration to Heroku using heroku run python manage.py migrate failed and show File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I tested the buildpacks of my app on heroku and see that heroku has detected my app as node.js app. I think this invited the issue. I added python as a buildpack manually but the problem persists. Any idea? -
How to used a form with soaplib, postgresql and django 1.10
Can I used a form on web service SOAP and added the informations of forns with postgresql , soaplib , Django1.10 and python 2.7 ? If i can , then how to use it.? I want a simple exemple with form.. help me plz :) -
Tutorials for django using Visual studio
It might seem like a drag to most of you guys but i am trying to learn web development using python. Since throughout my ordinary development career i have only used visual studio's ide for development, it would be really helpful to me if any of you can share a comprehensive step by step web development project using django like music store app tutorial microsoft offers for asp.net mvc5. Really looking forward to this. A novice like me can get real help out of this. Any sort of help would be appreciated. Thanks in advance. -
Trying to get the errors from a failed Stripe charge
I set up a simple stripe payment to play around with and I can successfully charge a card but when it fails I am getting an AttributeError with 'CardError' object has no attribute 'messages' instead of an error message on the html page. In my model I have it get a stripe charge and return a tuple with the success of the charge and the details of the charge or the error messages. # models.py class Sale(models.Model): def __init__(self, *args, **kwargs): super(Sale, self).__init__(*args, **kwargs) import stripe stripe.api_key = settings.STRIPE_SECRET_KEY self.stripe = stripe customer = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) charge_id = models.CharField(max_length=32) def charge(self, price_in_cents, number, exp_month, exp_year, cvc, address_zip): if self.charge_id: return False, Exception(message='This charge has already been issued.') try: response = self.stripe.Charge.create( amount = price_in_cents, currency = 'usd', card = { 'number': number, 'exp_month': exp_month, 'exp_year': exp_year, 'cvc': cvc, 'address_zip': address_zip, }, description = 'Thank you for signing up for our program.') self.charge_id = response.id self.customer = request.user except self.stripe.error.CardError as ce: return False, ce except Exception as e: return False, e return True, response My forms setups up the field and gets the charge from the model. # forms.py class SalePaymentForm(forms.Form): number = CreditCardField(required=True, label="Card Number") expiration = CCExpField(required=True, … -
Django - For loop
I am building a script that have several users and every hour it should query for the user who has not been updated the longest, find changes from an API and update the user. It should do this for all users always. I have thought about using a counter variable. Search for the user with the smallest counter variable and for the one with the biggest counter variable, update the smallest variable user and change it to biggest counter variable + 1. I wonder if there's a way to do this without explicitly declaring a counter variable in the model. -
Python Django + RQ: job is executing but skipping all if/elif blocks
I'm at a loss as to what is happening here. I have a simple django web site where I log in and fill out a basic form with some information (device address, electrical socket 1/2, on/off). When I submit the form, RQ submits this task (which uses requests to make a HTTP GET request to a URL) into the queue and it is executed. I put a return 'JOB FINISHED' at the end of the function and I see that the jobs are finishing with result 'JOB FINISHED'. So the function is being executed but for some reason it skips over all of the if/elif blocks. Looking at the django-rq dashboard and the worker console output, it looks like the arguments are being passed correctly. If I copy/paste the function into a python window it runs successfully when I pass it the same arguments. views.py @login_required(login_url="/login/") def index(request): if request.method == 'POST': form = APIForm(request.POST) if form.is_valid(): queue = django_rq.get_queue('default') queue.enqueue(api_call, form.cleaned_data['device'], form.cleaned_data['socket'], form.cleaned_data['change_to']) obj = SocketChange() obj.device = form.cleaned_data['device'] obj.socket = form.cleaned_data['socket'] obj.change_to = form.cleaned_data['change_to'] obj.submitter = request.user obj.save() return HttpResponseRedirect(reverse('log')) else: return render(request, 'api/index.html', {'form': form}) else: form = APIForm() return render(request, 'api/index.html', {'form': form}) tasks.py @job def … -
Django via TCP socket
I have created django app that I uploaded on "pythonanywhere website". This app use quite a big database which I have to update every day and I wanted this database to be on my computer only. Inside on of my django view I have created TCP client and after user type some information to app, this client send query to database on address when my server with database is running (my computer IP). Everything was good on local network. I could connect to database from one computer to another and receive answer from it. Unfortunatelly I am unable to do it online on "pythonanywhere" website. I have read that it's impossible to do it through this website right now and I am looking for some alternative way to solve this problem. Long story short. I am looking for a way to deploy my django website and connect it with server on my computer. If there is some other, easier way to do it, please advise, but I would rather keep my database on computer. Thank you. -
Is it possible to get the template url in a view function?
I found a question that suits my struggle atm, but I do not understand the what is exactly is going on. I'd like to refere to this question Django form in the base template. How to display validation error? In the answer there's the following def search(request, template): search_form = SearchForm(request.POST or None, request.FILES or None) ... ormitted ... return render(request, template, {'form': search_form}) Along with request a template is passed, and I'm not sure what that is and how it works. So I was hoping for some clearification. When I try to insert the template in my own view parameters I get the following error: create_user() missing 1 required positional argument: 'template' this is my view function: def create_user(request, template): form = CreateUserForm(request.POST or None, request.FILES or None) return render(request, template, {'create_user_form': form }) -
Django UpdateView - ManyToMany Form in Classed Based View
So I am having issues with an UpdateView which contains one field which is a manytomany field. The purpose of the view is to be able to select multiple objects and then have them saved into the manytomany connector table in the database. Seems fairly straightforward and is odd how the Django generated form doesn't deal with this. Currently, the Django generated form allow you to select multiple objects but when it is saved only one of the objects is saved. Models.py class Gallery(models.Model): date_added = models.DateTimeField(_('date published'), default=now) title = models.CharField(_('title'), max_length=50, unique=True) slug = models.SlugField(_('title slug'), unique=True, help_text=_('A "slug" is a unique URL-friendly title for an object.')) description = models.TextField(_('description'), blank=True) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public galleries will be displayed ' 'in the default views.')) photos = SortedManyToManyField('Photo', related_name='galleries', verbose_name=_('photos'), blank=True) class Photo(ImageModel): title = models.CharField(_('title'), max_length=60, unique=True) slug = models.SlugField(_('slug'), unique=True, help_text=_('A "slug" is a unique URL-friendly title for an object.')) Views.py class GalleryPhotoUpdate(UpdateView): model = Gallery fields = ['photos'] template_name = 'otologue/gallery_photo_update.html' success_url = reverse_lazy('otologue:galleries') def get_queryset(self): queryset = super(GalleryPhotoUpdate, self).get_queryset() return queryset.filter(galleryextended__user=self.request.user) def get_context_data(self, **kwargs): context = super(GalleryPhotoUpdate, self).get_context_data(**kwargs) context['form'].fields['photos'].queryset = Photo.objects.filter(photoextended__user=self.request.user) return context @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
Django nginx + uwsgi [error] : *1 connect() failed (111: Connection refused) while connecting to upstream
I am getting 502 error and in error log [error] 18959#18959: *1 connect() failed (111: Connection refused) while connecting to upstream....... upstream django { server 127.0.0.1:7000; } server { listen 80; server_name ec2-instance-address.us-west-2.compute.amazonaws.com; access_log /srv/project/logs/access-nginx.log; error_log /srv/project/logs/error-nginx.log; location / { uwsgi_pass django; include /srv/project/conf/envs/stage/uwsgi/params; } location /static/ { root /srv/project/; index index.html index.htm; } location /media/ { root /srv/project/; index index.html index.htm; } location ~ ^/favicon.(\w*)$ { alias /srv/book-stage/static/favicon.$1; } } -
Create error message datefield
I want to create an error message for following form: class ExaminationCreateForm(forms.ModelForm): class Meta: model = Examination fields = ['patient', 'number_of_examination', 'date_of_examination'] Every Patient has 2 Examinations (number of examination = Choices 1 or 2) and the error message should be activated when the date of the second examination < date of the first examination. Something like this: def clean_date_of_examination(self): data = self.cleaned_data['date_of_examination'] #don't know how to query this var1 = ( Patient1 with number_of_examination = 1) var2 = ( Patient1 with number_of_examination = 2) if var2.date_of_examination < var1.date_of_examination: raise forms.ValidationError("Second examination should take place after first examination") Hope you guys can help me to define this error message!