Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Bootstrap: dynamically filling bootstrap cards with form field labels
I have a form where users can select communities that they want to join. I'd like each community to have its own bootstrap card with a background color and the text of the community over the tile. Users should be able to select on multiple tiles and then press submit. The number of communities changes (can grow if users add more), so these cards need to be dynamically filled. Then, django would process the selected tiles as the selected choices. Currently, I just have the following simple code, which allows for multiple selections if the user holds down control (or command). {% extends 'qa/base.html' %} {% load staticfiles %} {% block content %} <div class="col-sm-8 input"> <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <input class="btn btn-submit pull-left" href="{% url 'qa_profile' user.id %}" type="submit" value="Choose Communities" /> </form> </div> {% endblock content %} Here is what it currently looks like (below). I can add more communities and the list will grow. I'm not sure how to do this with bootstrap tiles though and make them selectable. -
Django POST request redirects to empty url after submitting form
I have a login form with POST method and when I submit the login data, it goes straight to the empty url and doesn't execute the login method in views.py. Ideally, after I submit the form in www.url.com/login via submit button, it should return a HttpResponse but instead, it takes me to www.url.com/ I am new to Django, I'd appreciate it if you could look into it. Thanks! home.html <center><h1>Welcome to my website</h1> <form method='POST'> {% csrf_token %} {{ form }} <button type='submit' class='btn btn-default'>Submit</button> </form> </center> urls.py from django.contrib import admin from django.urls import path from .views import home, login urlpatterns = [ path('', home), path('login/', login), path('admin/', admin.site.urls), ] forms.py from django import forms class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control", "placeholder":"Your username"})) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control", "placeholder":"Your password"})) views.py from django.contrib.auth import authenticate, login from django.http import HttpResponse from django.shortcuts import render from .forms import LoginForm def home(request): context={ "form": "Test" } return render(request, "home.html", context) def login(request): login_form = LoginForm(request.POST or None) context={ "form": login_form } if login_form.is_valid(): username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: #request.user.is_authenticated() login(request, user) return HttpResponse("You are now logged in") else: return HttpResponse('Error') return render(request, "home.html", … -
how can I return to the previous page in Django 2
I'm Prety new in Django. I want to know how to return to the previous page from view to template without taking path or url. -
django-pytest xunit style access database issue
I start to test my Django project recently. At first, I test my code by accessing my local full data DB, but it seems like not a proper way. So , I try to change the access data way by code creating fake data before testing. And pytest provide xunit style , so setup_module or setup_class .... become my insert fake data entry point. Also , I add below code to conftest.py avoid insert @pytest.mark.django_db everywhere @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass But, I still get error message, when I create fake data in setup_module or setup_class. def setup_module(): print('setup_module....') HostSite.objects.create(prefix='us', vhost='www', enable_site=True, locale='en_us') Error Message: Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Could anyone help me to figure out what I miss? please. -
Django Start Project Error
I currently try to add Cartoview to the existing GeoNode installation. I just followed the tutorial from the documentation to create a new project for Cartoview using the command: django-admin.py startproject --template=https://github.com/cartologic/cartoview-project-template/archive/master.zip --name django.env,uwsgi.ini,.bowerrc webcartoview And it comes up the following error from the command prompt: I have successfully installed the Cartoview library (pip install cartoview). But I am not quite understanding what the error message means. Am I doing anything wrong? -
How do I check which app a given view belongs to?
I'm writing a middleware with process_view method and I want it to apply only to the views in my app (not django.contrib.auth and other imported ones). How can this be done? -
Django model manager get queryset depending on lookup value
Assuming I have model and custom manager like this: class FooManager(models.Manager): def get_query_set(self): super(FooManager, self).get_query_set() class Foo(models.Model): name = models.CharField(max_length=10) status = models.BooleanField(default=False) objects = FooManager() I feel like this should be pretty simple but looked through documentation and "self" probably I missed something obvious. My question is how I can return object/queryset depending on lookups passed during actual query? For example: objs = Foo.objects.all() print(objs, "Objects queryset only with status set to True") objs = Foo.objects.filter(name__icontains='a') print(objs, "Objects queryset with 'a' in name and status set to True") objs = Foo.objects.filter(name__icontains='a', status=False) print(objs, "Objects queryset with 'a' in name and status set to False") I could imagine something looks like this sample: class FooManager(models.Manager): def get_query_set(self): status = self.passed_lookups['status'] queryset = super(FooManager, self).get_query_set() if status is None: queryset = queryset.filter(status=True) else: queryset = queryset.filter(status=status) return queryset -
How do I filter through Django models that are not yet saved in DB?
Here is my model class and a function. I would only like to add new animals to my list. class Animals(models.Model): id = models.AutoField(primary_key=True) name = models.TextField(unique=True) class Meta: db_table = 'animals' animals = [] for name in ['duck', 'cow', 'cat', 'dog']: if (THIS ALREADY EXISTS) animals.objects.filter(name=name): # This will throw an error, because its a list continue else: animal = Animals(name=name) animals.append(animal) Keep in mind I do not want to save these models to the database yet, but it would be great to query my list of models stored in memory as if they were all saved as a database table. -
Cron Job for Django Project not activating
I am trying to add a cronjob to my django project that will reset the scores of my game every 1 minutes. I used cron tab and I think it’s my pathing/location of the function that is causing it to not trigger. Here is the hierarchy of the files and a few files in each of them. ProjectBackend— ProjectBackend— - settings.py - wsgi.py __init__.py urls.py manage.py heroku scores— admin.py cron.py models.py views.py urls.py apps.py In the settings.py above, I have the following : I added only crontab to installed_apps and the cronjob array. CRONJOBS = [ ('*/1 * * * *', ’scores.cron.my_scheduled_job’) ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scores.apps.ScoresConfig', 'django_crontab', ] I have replaced the cronjob’s second parameter with ’ProjectBackend.scores.cron.my_scheduled_job’ and other variations with no luck. I chose ‘scores’ instead of 'scores.apps.ScoresConfig' because it is designed as the name in apps.py I placed the function called my_scheduled_job in the cron.py in the above location. Right now all the function does is print out a string, which does not show up on Terminal when I do the following in the directory where manage.py is located. ‘Python3 manage.py crontab add’ ‘Python3 manage.py crontab show’ To which it says … -
Django: after I render a template from a view with dynamic data the template stays static and does not change when data is added to the database
In my views.py I have this code from .forms import * from students.models import Student from classes.models import Class from venues.models import Venue from courses.models import Course from registrations.models import Registration class Test(View): template_name = "test.html" context = {} data_summary = { "total_students": Student.objects.all().count(), "total_classes": Class.objects.all().count(), "total_courses": Course.objects.all().count(), "total_registrations": Registration.objects.all().count(), } def get(self,*args, **kwargs): return render(self.request,self.template_name,self.data_summary) In my test.html I have this: <...snip ...> <h3> Totals: </h3> <hr> </div> <div class="row"> <div class="col-md-2 text-right"> <label style="color: Blue; font-size:24"> Students: </label> </div> <div class="col-md-2 text-right"> {% if total_students %} <... snip ...> The template renders very nicely but if I update my database and add another student and or class and reload my page the data in my dictionary does not update. I am at a loss why the data doesn't update. I am now banging my head and not in the 70's good way either. -
How to properly structure/pass in data for Highcharts.js series chart?
I'm trying to learn how to pass through my own values/labels to a Highcharts graph using Django, and I've been running into some issues with properly structuring data/passing arguments. I looked at this example (https://www.highcharts.com/demo/line-basic), and the data looked to be in the shape of an array of arrays, so I figured that's what my series should look like. This is what my views looks like: // in views.py: def make_graph(request): dates = // A list of datetime.date objects. values = [1, 2, 3, 4, 5, 2, 3, 5, 3, 3] data = [[d, v] for d, v in zip(dates, values)] context = {"data": data} return render("graph.html", context) Now, this is my Highcharts script: <script> var data = {{ data|safe }}; Highcharts.chart('container', { chart: { type: 'spline' }, title: { text: 'some title' }, subtitle: { text: 'some subtitle' }, xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%e. %b', year: '%b' }, title: { text: 'Date' } }, yAxis: { title: { text: 'y value' } }, tooltip: { headerFormat: '<b>{series.name}</b><br>', pointFormat: '{point.x:%e. %b}: {point.y:.2f} m' }, plotOptions: { spline: { marker: { enabled: true } } }, colors: ['#6CF', '#39F', '#06C', '#036', '#000'], series: [{ name: "Trend", data: data … -
How to loop dictionary with multiple values in Jinja?
I have a dictionary like so: {'a': [Object, 0], 'b': [Object, 1] } Where object is an actual object with multiple attributes. I'm trying to a check on each key to see if the second value in the array is a 0 or 1. If it is a 1, then I'll display "Hello" if it's a 0, I'll display "Goodbye" Here's what I have so far that doesn't seem to work: {% for key in follower_list %} {% if follower_list[key][1] == 0 %} <p>Hello</p> {% else %} <p>Goodbye</p> {% endif %} Here, follower_list is the dictionary. I'm getting an error by my IDE saying operator expected where follower_list[key][1] is there a way I can do this type of logic in Jinja? -
Access request attributes inside django admin
I'm developing an application in Django and i add the request to certain clean methods of my user creation form, when i try to make some updates to the User in admin site i've got an error that the request is None, obviously the parameter is not add to form like when i request in view, searched for this answer in lot's of plataforms but can't resolve my problem. First the init method of my form adding the request attribute: def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') Now the clean for groups field using request attribute: def clean_groups(self): if self.request.user.groups.all() or self.request.user.is_staff: if self.request.user.groups.filter(name="Administrador") or self.request.user.is_staff: return self.cleaned_data['groups'] else: if list(self.cleaned_data['groups']) == list(self.request.user.groups.all()): return self.cleaned_data['groups'] else: raise forms.ValidationError( self.error_messages['non_administrator'], code='non_administrator', ) elif not self.request.user.groups.all() and self.cleaned_data['groups']: raise forms.ValidationError( self.error_messages['non_administrator'], code='non_administrator', ) elif not self.request.user.groups.all() and not self.cleaned_data['groups']: return self.cleaned_data['groups'] For last i will put my admin for Users: class MyAdmin(auth_admin.UserAdmin): save_on_top = True fieldsets = ( ('Personal Info', { 'fields': ('image_tag', 'avatar', 'email', 'password', 'first_name', 'last_name', 'date_joined', 'last_login') }), ('Relationships', { 'fields': ('groups', 'user_permissions', 'user_institution') }), ('User status', { 'fields': ('is_active', 'is_staff', 'old_password') }), … -
KeyCDN and DO spaces: {% static %} vs {{ STATIC_URL}} when STATICFILES_STORAGE is set
I am using digitalocean.com spaces to store static files for my Django app. I set it up successfully according to their tutorial (same settings as AWS). I now want to put a CDN in front of the static files. KeyCDN has a document describing how to do this but suggests using {{STATIC_URL}} in templates rather than the {% static %} templatetag. Django admin uses the {% static %} templatetag not {{ STATIC_URL}}. In some cases there is no difference, however, if you define STATICFILES_STORAGE, as is required to store static files in digitalocean.com spaces, the templatetag {% static %} ignores whatever you explicitly declare in settings.py for STATIC_URL. I have: STATICFILES_STORAGE='storages.backends.s3boto3.S3Boto3Storage' S3Boto3Storage sets the template tag {% static %} to point to https://ams3.digitalocean.com/bucket_name/path/to/static/ regardless of the setting of {{ STATIC_URL }}. Manually setting STATIC_URL= in settings.py as KeyCDN suggests: STATIC_URL = 'http://keycdndjango-1c6b.kxcdn.com/static/' has no effect on what the templatetag {% static %} returns. So i cannot figure out how to make KeyCDN work with this setup. Any help is appreciated! -
How I save this element dictionary
Suppose I have a model like this: class Post(model.Model) name = model.CharField(max_lenght) description= model.CharField() mission = models.ForeignKey and i have this dictionary d={'name':'jerry', 'description':'all} I save dictionary on model so: p=Post(**d) p.save() But if I have this dictionary d={'name': 'jerry', 'description':'all', 'mission':'ciao','name1': 'jerr', 'description1':'al', 'mission1':'ciao','name2': 'jer', 'description2':'a', 'mission2':'ciao' } How I save this element dictionary on model? -
How do I filter Django models to only include models that appear in a child (with a ForeignKey) table?
I have these two Django models: class Animals(models.Model): id = models.AutoField(primary_key=True) name = models.TextField(unique=True) class Meta: db_table = 'animals' class AnimalSounds(models.Model): id = models.AutoField(primary_key=True) animal = models.ForeignKey(Animal, on_delete=models.PROTECT) sound = models.TextField(unique=True) class Meta: db_table = 'animal_sounds' Now my SQL query would look something like this: SELECT * FROM animals WHERE animals.id IN ( SELECT animal_id FROM animal_sounds ) How would I do this using Django models? Something like this conceptually: Animals.objects.filter(id__in=AnimalSounds.objects.all('ids')) -
Websocket lost connection issue
I am implementing a project with django channels and have faced with an unexpected issue. Due to specific of this web app, I need the established websocket connection, on every page of this app, but unfortunately when I click to navbar menu, the page reloaded completely, and websocket lost it connection. So, could you professionals give me a clue of how can I make one websocket connection, which will never be lost, no matter how many times the webpage be reloaded? P.S. I couldn't make navbar static and separate from the page, cause it's slightly different on each page for some design and usability reasons. -
Jquery selector on Django loop
So I have this {% for producto in reparto_martes %} <div class="col-md-3"> <div class="card mb-4 box-shadow product-box"> <img class="card-img-top product-photo" data-src="holder.js/100px225?theme=thumb&amp;bg=55595c&amp;fg=eceeef&amp;text=Thumbnail" alt="Thumbnail [100%x225]" style="height: 225px; width: 100%; display: block;" src={{ producto.foto }} data-holder-rendered="true"> <div class="card-body"> <h4 class="card-text producto_precio">${{ producto.precio }}</h4> <h5 class="card-text producto_nombre">{{ producto.nombre }}</h5> <div class="d-flex justify-content-between align-items-center"> <button type="button" class="btn btn-success anadir_button">Añadir</button> <small class="text-muted"></small> </div> </div> </div> </div> {% endfor %} It looks like this: https://gyazo.com/0b329d87af9372250a53ae25347b59b0 I need to select the items name when the user clicks on the anadir_button. $(document).ready(function(){ $(".anadir_button").click(function(){ $('.producto_precio').clone().appendTo('#list_pedidos'); }); }); ^This one just selects all the three items (Bananas, bolson frutal, almendras) $('.producto_precio').last()clone().appendTo('#list_pedidos'); ^And this one just selects 'almendras'. -
The 'avatar' attribute has no file associated with it
I cannot upload image, if I delete image, I got this error!!! <img src="{{user.teacher.avatar.url}}" class="user-image" alt="User Image"> models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_regex = RegexValidator(regex=r'^\0?1?\d{11}$') mobile = models.CharField(validators=[phone_regex], max_length=11, blank=True) avatar = models.ImageField(upload_to='avater', blank=True) def __str__(self): return self.user.first_name + ' '+self.user.last_name @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Teacher.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.teacher.save() forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email') views.py @login_required def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = TeacherForm(request.POST,request.FILES, instance=request.user.teacher) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() # if Teacher.avatar is not None: # print (".............img................", Teacher.avatar) messages.success(request,('Your profile was successfully updated!'), extra_tags='alert') return redirect('Dashboard:profile') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = TeacherForm(instance=request.user.teacher) return render(request, 'Dashboard/updateProfile.html', { 'user_form': user_form, 'profile_form': profile_form }) This is the current situation, also I cannot log in with an Admin in the admin panel that has no association with Teacher -
Django authentication system
i'm using the django built in authentication system and in my login template i have this code : login.html: {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> {% if user.is_authenticated%} you are already logged in {% else %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endif %} {% endblock %} but what i realy want to do is te redirect the user to the home page if he trays de access to login page while already logged in ,but i am new to django so i dont know ho to do that thank you -
Cannot assign "9": "Characterweapons.weaponid" must be a "Weapons" instance
I've been reading similar questions to mine but they didn't help me. I'm getting this error while I try to submit my form: Cannot assign "9": "Characterweapons.weaponid" must be a "Weapons" instance. This "9" is the ID from the weapon I got from my form, so that's very good, but when I try to put it in my weaponid column in my table Characterweapons, it gives me the error. models.py: from __future__ import unicode_literals from django.db import models class Category(models.Model): categoryid = models.AutoField(db_column='CategoryID', primary_key=True) # Field name made lowercase. categoryname = models.CharField(db_column='CategoryName', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = True db_table = 'category' def __str__(self): return self.categoryname class Characters(models.Model): characterid = models.AutoField(db_column='CharacterID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', unique=True, max_length=255) # Field name made lowercase. level = models.IntegerField(db_column='Level') # Field name made lowercase. credits = models.IntegerField(db_column='Credits') # Field name made lowercase. class Meta: managed = True db_table = 'characters' def __str__(self): return '%s %s %s' % (self.name, self.level, self.credits) class Weapons(models.Model): weaponid = models.AutoField(db_column='WeaponID', primary_key=True) # Field name made lowercase. weaponname = models.CharField(db_column='WeaponName', unique=True, max_length=255) # Field name made lowercase. class Meta: managed = True db_table = 'weapons' def __str__(self): return '%s … -
Pass context to a ajax call in a callback
I know there are plenty of questions and answers about this, here for example, but I cant get it to work in my specific situation. I am trying to pass variables to a view with an ajax call, the start and end dates. $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); $.ajax({ type: "POST", url: "/courses/pageviewsbydate/", data: { 'start_date' : start, 'end_date' : end, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: GA_pagesviewsSuccess.bind(this), dataType: 'html' }); console.log("got here"); }); -
Circular import error in django
I organized my django structure to have a views and urls folder. When importing django.contrib.auth.views.login in /appfolder/urls/_ init _.py or actually anywhere in the urls or views folder like so: from django.contrib.auth.views import login I keep getting: ImportError: cannot import name login I assume it has to do with the changed structure. I want to include it in my url patterns like so: path('portal/', login, {'template_name': 'portal/index.html'}) How can I import login without getting a circular import error? appfolder │ └─── __init__.py └─── admin.py └─── apps.py └─── forms.py └─── models.py │ └───urls │ │ __init__.py | │ │ books_urls.py | | | movies_urls.py | | | portal_urls.py | │ |_ _ _ _ _ _ _ _ _ _| | └───views │ │ __init__.py | │ │ books_views.py | | | movies_views.py | | | portal_views.py | │ |_ _ _ _ _ _ _ _ _ _ | -
Django 2.1 static files 404 in WAMP Server
I am using DJango 2.1 and python 3.7.0 version. Using mod_wsgi trying to run the application in apache web server. The static files used in django application is not downloading 404. I tried lot of solution but nothing worked. Here are my configuration, please help! FYI: I used .whl file to install the mod_wsgi file , download and copied the .pyd file directly in apache modules directory STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join( os.path.dirname(__file__), 'static', ), ) <IfModule wsgi_module> WSGIPythonPath C:/Apache24/htdocs/django_app Alias /static/ C:\Apache24\htdocs\django_app\example_app\static <Directory C:/Apache24/htdocs/django_app/example_app/static> Require all granted </Directory> WSGIScriptAlias / C:/Apache24/htdocs/django_app/example_app/wsgi.py <Directory C:/Apache24/htdocs/django_app/example_app> <Files wsgi.py> Require all granted </Files> </Directory> -
how to get wrong password event on login using django contrib auth?
I've tried to use the contrib login form from django. I made a template like this: {% extends "base.html" %} {%block content%} <div class=" vertical-center"> <div class="container login "> <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-sm"> <input placeholder="id" class="form-control" type="text" name="username"> </div> </div> <div class="row"> <div class="col-sm"> <input placeholder="pass" class="form-control" type="password" name="password"> <p class="text-center hidden">wrong id or pass</p> </div> </div> <div class="row"> <div class="col-sm"> <button class="btn btn-outline-dark btn-block" type="submit ">Login</button> </div> </div> <div class="row"> <div class="col-sm"> <p class="reference text-center"> <a href="/forgot">forgot my pass.</a> </p> </div> </div> </form> </div> </div> {%endblock%} {%block footer%} Badwolf {%endblock%} to access this template I made this on the url.py from django.conf.urls import url from django.contrib.auth.views import login, logout from . import views urlpatterns = [ path('', views.main, name='main'), url(r'^login/$', login, {'template_name': 'login.html'}), url(r'^logout/$', logout, {'template_name': 'logout.html'}), ] the page works fine, but if I type a wrong password I want a label to tell the user that. Currently the page simply reloads. How can i get from django the event of wrong password and tell the user?