Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Image gallery
I'm trying to make a image gallery template in Django that will pull in new images when they are added to the blog. What I'm wanting are three or four columns of thumbnail sized images in a grid. So far my template looks like this {% for image in images %} {% if forloop.first %} <tr> {% endif %} <td> <a href="{{ image.get_absolute_url }}"> <img src="{{ image.image.url }}" class="img-responsive img-thumbnail" width="304" height="236"/></a> </td> {% if forloop.last %} </tr> {% else %} {% if forloop.counter|divisibleby:"4" %} </tr><tr> {% endif %} {% endif %} {% endfor %} However this won't allow me to manipulate the images as easily as I would like I was hoping to use Bootstraps columns but each time I try that it gives me the images in a single column. -
Get most recently created object in a queryset?
Attempting to get the most recent object in a query set and I keep getting error TypeError at / 'PostManager' object is not iterable How do you do this without iterating? class DashboardTemplateView(TemplateView): template_name = "base.html" context_object_name = 'name' def get_context_data(self, *args, **kwargs): context = super(DashboardTemplateView,self).get_context_data(*args, **kwargs) context["title"] = "This is about us" return context class MyView(ContextMixin, TemplateResponseMixin, View): def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) # mission_statement = Content.objects.filter(Content.objects.title == 'test') # context = {'mission_statement' : mission_statement, # 'content_list' : Content.objects.all(), # 'post_list' : Post.objects.all()} # context = {'content_list' : Content.objects.all(), 'post_list' : Post.objects.all()} home_list = list(Post.objects).order_by('-id')[0] context = {'content_list' : Content.objects.all(), 'home_list' : home_list.objects.all()} return self.render_to_response(context) -
Django test - Get messages in HttpReponseRedirect with view call (so no follow = True)
I'm trying to test a login view, here is the test code: #test login view class LoginViewTest(TestCase): def setUp(self): self.client = Client() self.factory = RequestFactory() self.user = User.objects.create_user('user_test', 'user_test@test.com', 'pws_test') #self.browser = webdriver.Firefox() def test_successful_login(self): activate('en') request = self.client.post('/en/account/login/', {'username': 'user_test', 'password': 'pws_test'}, follow=True) request.user = self.user response = my_login(request) m = list(response.context['messages']) self.assertEqual(len(m), 1) self.assertEqual(str(m[0]), 'Login successfull') self.assertTrue(response.context['user'].is_active) self.assertRedirects(response, '/en/') And the error message: 'HttpResponseRedirect' object has no attribute 'context' I want to check if the message is correctly sent in case of successful login, but I am unable to access messages as my_login is a HttpRedirectResponse (as the login is successful), and I cannot simply set follow = True as I am directly calling a view and not a self.client.post. Does anyone have a solution ? Thanks -
executable BAT file for Django project
The BAT file is placed in Django project folder. I want to send it to the DESKTOP and the user just press one icon. Tell me where is my mistake. file.bat python manage.py runserver start C:\"Program Files (x86)"\"Google"\"Chrome"\"Application"\chrome.exe "http://127.0.0.1:8000/" -
Pass decimal value to django model from formated input
I, have a DecimalField in Django model and form, likewise I, have an input in html form, with comma as thounsand separator and dot for decimal separator (123,456.78), formated with jquery plugin Cleave.js, but when I, try save my form this show a message says: Enter a number. I' want save the data from the form, with value in decimal without lose the format in html. Sorry! my english is too bad. Here is my code: Model class Product(models.Model): Price = models.DecimalField( max_digits=17, decimal_places=2, default=0.00, validators=[ MinValueValidator( 100.00, message='>=100')]) Form class ProductForm(forms.ModelForm): price = forms.DecimalField( label='Price', label_suffix=False, max_digits=17, decimal_places=2, widget=forms.TextInput( attrs={'placeholder': '123,456.78'}) ) class Meta: model = Product fields = [ 'price' ] Html <html lang="es"> <head> <script src="{% static 'js/cleave.js' %}" type="text/javascript"></script> </head> <body> <input type="text" id="price" class="price"> <script> new Cleave('.price', { numeral: true, numeralDecimalMark: '.', delimiter: ',' }); </script> </body> </html> -
What does error mean? : "Forbidden (Referer checking failed - no Referer.):"
I have a website running, which appears to be working fine. Yet, now I've seen this error in the logs for the fist time. Forbidden (Referer checking failed - no Referer.): /pointlocations/ [pid: 4143|app: 0|req: 148/295] 104.176.70.209 () {48 vars in 1043 bytes} [Wed Jul 26 19:49:35 2017] POST /pointlocations/?participant=A2TYLR23CHRULH&assignmentId=3P4MQ7TPPYF65ANAUBF8A3B38A0BB6 => generated 2737 bytes in 2 msecs (HTTP/1.1 403) 1 headers in 51 bytes (1 switches on core 0) It happens when posting to /pointlocations/, but only for one specific person ( each participant is unique per account, so I know it's only one person, having this problem repeatedly. Over 500+ other participant have had no such problem/error. What does this error mean, what is likely causing it and can I fix this? -
getting name as USER OBJECT
i am building app in django and i have deployed this app on HEROKU , my error is i have "name" as foreign key in my model, when i am accessing name on my app which is deployed on heroku name is shown as "USER OBJECT" . I am able to access correct name while running in local server. i have tried many different ways but still not able to fix it. pictures for better understanding of my error -
django.db.utils.ProgrammingError: Could not load : column "" of relation "" does not exist
I just added a field to my model and added the values of the field to my fixtures. However, I am getting this error: django.db.utils.ProgrammingError: Problem installing fixture 'app/fixtures/tool.json': Could not load "": column "new_field" of relation "app_model" does not exist which is the same error I got before even putting values in the fixture. What is it that I'm forgetting? -
Accessing model data in Django template
I am using the below lines to pass data to my template index.html, model1 being the class in my models.py. data = model1.objects.all() return TemplateResponse(request, 'index.html', {'data': data}) I am able to access data on the front end by using a for loop as shown below {% for x in data %} <h3>x.name</h3> <h4>x.department</h4> {% endfor %} Since there are mutliple objects in this data, my question is if I want to access only the department of particular object with certain name, how can I do that? -
Syntax error in django
I keep getting a syntax error even though I am following a tutorial. I tried looking up for changes in the syntax. But since the video came out no changes have happened in django. The error looks like this: args = ('user': request.user) ^ SyntaxError: invalid syntax Thanks in advance for the help. -
How i registr the user in django model User....,
I have done my best to store value in the model User, but i can't please guide me what is the error and why it doesnot work.... relevant code is: urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='registration'), url(r'^customer/add/$', views.UserFormView.as_view(), name='customer-add'), ] i think post method is not working because when i click on the submit button the traceback was '[26/Jul/2017 23:50:37] "GET /customer/add/?csrfmiddlewaretoken=nLX4YAZ1Tk6Zt5DJUJNM9fiYtw91pZwsrDdZwb5tpr80qKBos36eV9SZdR23c9BT&username=dq&email=admin%40c.com&password=password123 HTTP /1.1" 200 2796 ' viws.py class UserFormView(View): form_class = UserForm template_name = 'registration/registration_form.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # return username if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('registration:index') return render(request, self.template_name, {'form': form}) forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User labels = { "email": "Your Email" } fields = [ 'first_name', 'last_name', 'username', 'email', 'password', ] registration_form.html {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form class="form-horizontal" action="" method="post"> {% csrf_token%} {% include 'registration/form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> … -
Django Factory boy and django hashid field primary key: "UNIQUE constraint failed"
I am using django hashid field in model primary keys and i'd like to use django factory boy for creating factories. class Camera(models.Model): id = HashidAutoField(primary_key=True) But as soon as I create factory for the second time I get this error. return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: camera_camera.id How does factory boy deal with custom fields? -
I can't get my model to show up on '/blog' but can get it to show up on '/'
I am able to get my blog list to show up on '/' but when I try to access in /blog nothing gets displayed. I am worried am have overridden something while implementing post_list in '/' Any help would be greatly appreciated blogbase.html is as follows: <div class="header"> <div class="logos container"> <ul> <li><a href=""><p></p></a></li> <li><a href=""><<p></p></a></li> <li><a href=""><p></p></a></li> </ul> </div> </div> {% include "messages_display.html" %} <div class='container'> <ol class='breadcrumb'> <li><a href='{% url "posts:list" %}'>Home</a></li> {% block post_detail_link %} {% endblock %} {% if not request.user.is_authenticated %} <li class='pull-right'><a href='{% url "register" %}'>Register</a></li> <li class='pull-right'><a href='{% url "login" %}'>Login</a></li> {% else %} <li class='pull-right'><a href='{% url "logout" %}'>Logout</a></li> {% endif %} </ol> {% block content %}{% endblock content %} </div> post_list.html is as follows: {% extends "blogbase.html" %} {% block content %} <div class='col-sm-6 col-sm-offset-3'> <h1>Posts</h1> <form method='GET' action='' class='row'> <div class='col-sm-6'> <div class='input-group'> <input class='form-control' type='text' name='q' placeholder='Search posts' value='{{ request.GET.q }}'/> <span class='input-group-btn'> <!-- <input class='btn btn-default' type='submit' value='Search' /> --> <button class='btn btn-default' type='submit'>Search <i class="fa fa-search"></i></button> </span> </div> </div> </form> {% for post in post_list %} <div class="row"> <div class="col-sm-12"> <div class="thumbnail"> {% if obj.image %} <img src='{{ obj.image.url }}' class='img-responsive' /> {% endif %} <div class="caption … -
I am tring to make " login with facebook" using Django. getting error
Making a project login with facebook . but it showing error my localhost url -- 127.0.0.1:8000/demo/index/ My code is like this setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'dashboard' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.join(BASE_DIR), 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) STATIC_URL = '/static/' LOGIN_URL = '/demo/login/' LOGIN_REDIRECT_URL = '/' SOCIAL_AUTH_FACEBOOK_KEY = '184354188769721' SOCIAL_AUTH_FACEBOOK_SECRET = 'c4d9ed712a59be2f9bb25b5368432f61' LOGIN_URL = '/demo/login/' LOGIN_REDIRECT_URL = '/' url.py url(r'^facebook/', include('social_django.urls', namespace='social')), index.html Login with Facebook I created facebook API and set domain - empty site url - empty in facebook login(plugins) Valid OAuth redirect URIs - http://localhost:8000/_auth/facebook Give solution wy its showing this error while login. URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Setenter code heretings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs. -
Django: save() method in form or model?
quite a generic question here but I was curious as to when and in what cases would you use a save method in a ModelForm over the Model class itself and vice versa? model: class Model(models.Model): ... def save(self, *args, **kwargs): super (Model, self).save(*args, **kwargs) modelform: class ModelForm(forms.ModelForm): ... def save(self, commit=True): model = super(ModelForm, self).save(commit=True) if commit: model.save() return model Thanks! -
How to load scheme.js from DRF?
Iam read the documentation about core api and django rest framework (http://www.django-rest-framework.org/topics/api-clients/#installation-with-node). I try make test app with this code: let client = new coreapi.Client() let schema = null client.get("localhost:8000/docs/schema.js").then(function(data) { // Load a CoreJSON API schema. schema = data console.log('schema loaded') }) But I take the error: Uncaught (in promise) Error: Unsupported media in Content-Type header: application/javascript; charset=utf-8 at Object.negotiateDecoder (utils.js?9d9d:32) at response.text.then.text (http.js?7faf:13) at -
Django editing model instance
The Django project that I am working on lists patient details and lets the user edit the details. I have been able to list it out but the views.py is not getting linked to the url for updating the list views.py: def update_patient(request, patient_id): patient = Patient.objects.get(id=patient_id) if request.method != 'POST': form = PatientForm(instance=patient) else: # POST data submitted; process data. form = PatientForm(instance=patient, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('patient:patient', args=[patient.id])) context = { 'patient': patient, 'form': form} return render(request, 'patient/update_patient.html', context) models.py class Patient(models.Model): patientID = models.CharField(max_length=20) firstName =models.CharField(max_length=20) lastName = models.CharField(max_length=20) age = models.IntegerField(max_length=None) SSN = models.CharField(max_length=15) address = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) urls.py url(r'^patients/(?P<patient_id>\update\d+)/$', views.update_patient, name='update'), update_patient.html {% extends "patient/base.html" %} {% block content %} <p><a href="{% url 'patient:patient' patient.id %}">{{ patient }}</a> </p> <p>Update Patient:</p> <form action="{% url 'patient:update' patient.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name='submit'>add entry</button> {% endblock content %} -
Storing several images in article in Django
I create a Django app which has articles, currently stored as html in a text-field in the model. In template I show them using {{article.text|safe }}. But I need to be able to put images in any place of acrticle: different quantity to each article or none to some of them. I see following options to do that: To store html-text including <img src='...'> in database (and loose the opportunity to use django staticfiles in this case?)... To create ImageField (or several) in model - in this case I will have limited fixed number of images for each article and new questions - how to put images inside html-content (not above or below). To store prepared articles htmls with images as staticfiles - get problems with access and loose the ability to edit content rapidly using django admin panel (ex. to fix a typo). To use WYSIWYG-editor with possibility to upload images in django admin. This post tells about django-adminfiles but it was last updated in 2013 and doesn't work in Django 1.9 and later (I use 1.11). Even if find a modern plugin like that - main problem is that content is currently beeing prepared by other people having … -
django model form error
ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form CustomUserChangeForm needs updating. from django.contrib.auth.forms import UserCreationForm, UserChangeForm from login1.models import CustomUser class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kargs): super(CustomUserCreationForm, self).__init__(*args, **kargs) del self.fields['username'] class Meta: model = CustomUser fields = ("email",) class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kargs): super(CustomUserChangeForm, self).__init__(*args, **kargs) del self.fields['username'] class Meta: model = CustomUser -
Django Email services
Want to integrating Email service with Django using Mailchimp. I want to essentially use mailchimp for all email communications - new user registration on the site, forgot password etc. What I want to do is something like - 1.Setup a specific email in mailchimp, such as the 'forgot password email' When a user forgets their password, I want to trigger mailchimp to send the specified mail Does anyone have experience doing the above? Thanks -
unable to update image in base 64 format using django rest framework
I am trying patch method to update this content given below of particular id longitude = "77.335654"; name = User; phone = 4884884545; pincode = 201010; "profile_photo" = "/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAACgKADAAQAAAABAAACgAAAAAD/7QA4UGhvdG9zaG9......so on but i am not able to update profile image as every time i get no profile pic update. please help me out i am new in django rest framework -
Django Paginator uses locale output
When I use Django Paginator with en locale, then page number is 3,987 instead of 3987. How can I get rid of thousand separator and show "raw" numbers, because link appears to be broken? -
Push Notification Django 1.9
I am working on the project which is already developed in Django 1.9. I have searched a lot and not find any compatible version of Library to implement the push notification Via Django DRF and Firebase (FCM). Can any one help me to suggest a Push notification library that can i implement for my project. Following are the libraries that i had searched and not working either with python3 or with django 1.9 https://github.com/jleclanche/django-push-notifications https://github.com/bogdal/django-gcm Just need suggestion to pick stable library to send push notification via Django Rest Frameworkd(DRF) using Firebase. Thanks In Advance -
Do I have to isolate my wsgi.py from my django project folder?
where should I place my wsgi.py? Do I have to isolate it from my django project folder? Should I move my django project folder outside of my home directory? Currently I copied my django project folder to /home/username/djangosites/project/ and my wsgi.py is in the folder /home/username/djangosites/project/project/ In the same folder there are files like settings.py urls.py ... From the modwsgi documentation: "Note that it is highly recommended that the WSGI application script file in this case NOT be placed within the existing DocumentRoot for your main Apache installation, or the particular site you are setting it up for. This is because if that directory is otherwise being used as a source of static files, the source code for your application might be able to be downloaded. You also should not use the home directory of a user account, as to do that would mean allowing Apache to serve up any files in that account. In this case any misconfiguration of Apache could end up exposing your whole account for downloading. It is thus recommended that a special directory be setup distinct from other directories and that the only thing in that directory be the WSGI application script file, and if … -
Use specific django settings file dependent of current site domain name
I have two sites sharing the same database, each site needs to use only one language. How can I use a different settings file based on the current url? Example : apple.com will use settings_apple.py and pomme.com will use settings_pomme.py settings.py ... LANGUAGES = [ ('en', 'English'), ('fr', 'French'), ] ... settings_apple.py (english) from settings import * SITE_ID = 1 settings_pomme.py (french) from settings import * SITE_ID = 2 And in django admin I have created two sites : apple.com pomme.com