Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't make 1 of the forms not reqired
I've got 2 forms on 1 page, It seems like this: <form method='post' enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ image_form }} <button type="submit" class="js-crop-and-upload" name="crop" value="crop">Crop</button> {{ profile_form.as_p }} <button type="submit" class="btn" name="save_profile" value="save_profile">Submit</button> </form> This html form contain ProfileForm for profile data and ImageForm for Profile.image field. I want to save Images clicking button "submit" with name="crop" and save profile clicking button "submit" with name="save_profile". I could easily do this by splitting this html form like this: <form method='post' enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ image_form }} <button type="submit" class="js-crop-and-upload" name="crop" value="crop">Crop</button> </form> <form method='post'> {{ profile_form.as_p }} {% csrf_token %} <button type="submit" class="btn" name="save_profile" value="save_profile">Submit</button> </form> But here if I would press submit "crop" - all data in profile form would be deleted. I'm really stuck, because when fill profile fields and press submit with name "save_profile" django tells me that fields from image_form are required and don't send POST to my view, also when some of the fields in profile_form are not filled I couldn't save image using image_form. Also I'm sending my view if this is needed: view: @login_required def profile_new(request): if Profile.objects.filter(user=request.user): return redirect('profile_edit') created_image = Photo.objects.filter(created_by=request.user) if request.method != "POST": profile_form = ProfileForm() image_form … -
Translate Function Success into Function then
I am trying to get django-rest-framework running with angularjs. In order to do the authorization I found django-rest-auth and angular-django-registration-auth Unfortunately the djangoAuth.js is using the depreciated function success within the 'request' variable and I get the following error message: TypeError: $http(...).success is not a function I tried to rewrite the code using the then function, but only end up in the error-Callback. What do I have to change? Thanks for your help. djangoAuth.js - Orginal auth .service('djangoAuth', function djangoAuth($q, $http, $cookies, $rootScope) { // AngularJS will instantiate a singleton by calling "new" on this function var service = { /* START CUSTOMIZATION HERE */ // Change this to point to your Django REST Auth API // e.g. /api/rest-auth (DO NOT INCLUDE ENDING SLASH) 'API_URL': 'localhost:8000/rest-auth', // Set use_session to true to use Django sessions to store security token. // Set use_session to false to store the security token locally and transmit it as a custom header. 'use_session': true, /* END OF CUSTOMIZATION */ 'authenticated': null, 'authPromise': null, 'request': function(args) { // Let's retrieve the token from the cookie, if available if($cookies.token){ $http.defaults.headers.common.Authorization = 'Token ' + $cookies.token; } // Continue params = args.params || {} args = args || … -
Keep div with and image the same height as other div with some text
I'm developing a web page in Django and in it there's a list of the last 5 news that I add with a for loop. The news item has an image on the left, and the title, date and the first 50 words of the news on the right. The image and the text are in separate divs inside another div. I would like to make the image div the same size as the text div, not the other way around. Not all the images have the same dimension. I prefer not to limit the size of the divs with a px value for responsive purposes. I'm using Bootstrap 3.3.7. Here is the Fiddle of what I have now. Is there a way to accomplish this with CSS? -
Unable to install uwsgi with pip on Ubuntu 16.04
I have taken VPS from godaddy and built a machine with Ubuntu 16.04. I want to host a Python (DJango) application. I successfully installed Nginix. Unfortunately, I am not able to install nginix with pip on this machine. When I run sudo pip install uwsgi I am getting the following error. Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-kfJCaG/uwsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-QJoglI-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-kfJCaG/uwsgi/ Please help asap. -
Can't import Django model into scrapy project
I have a folder Project which contains Django project called djangodb and Scrapy project called scrapyspider. So it looks like: Project djangodb djangodb myapp scrapyspider scrapyspider spiders items.py scrapy.cfg __init__.py I want to import model Product from myapp app. The problem is that it returns import error: from Project.djangodb.myapp.models import Product as MyAppProduct ImportError: No module named djangodb.myapp.models Tried many things but couldn't avoid this error. Do you have ideas? -
Django BooleanField doesn't work on edit form
My situation: Models.py class Box(models.Model): is_empty = models.BooleanField(default=False) upload_date = models.DateTimeField(auto_add_now=True) Forms.py class BoxForm(forms.ModelForm): class Meta: model = Box fields = (is_empty,) Views.py def edit_box(request, pk): box = get_object_or_404(Box, pk=pk) if request.method == 'POST': form = BoxForm(request.POST, instance=box) if form.is_valid(): form.save() return redirect('home') else: form = BoxForm(instance=box) return render(request, 'form.html', {'form': form}) The problem is that when I enter into the template form and I want to change checkbox value I can't do it, it seems disabled and I dan't know why. -
ValueError: Cannot query “”: Must be “User” instance
I am trying to create a story-sharing website where user can get to specific author's profile to see all the stories which the author wrote. However I am getting an error. ValueError at /storyauthor/1 Cannot query "yumin": Must be "User" instance. Here is my model class StoryAuthor(models.Model): """ Model representing a author. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def get_absolute_url(self): """ Returns the url to access a particular story-author instance. """ return reverse('stories_by_author', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return self.user.username -
Method Not Allowed (POST) using DeleteView
I am new to Django and i using Class based views to add a delete option to my Restaurant List, However when i click the delete button i am getting a blank screen and getting the following error in the console "Method Not Allowed (POST):" Below is my code views.py from __future__ import unicode_literals from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView, DetailView, CreateView,DeleteView from django.urls import reverse_lazy class RestaurantDeleteView(DeleteView): model = RestaurantLocation success_url = reverse_lazy('restaurants:list') urls.py from django.conf.urls import url, include from .views import ( RestaurantListView, RestaurantDetailView, RestaurantCreateView, RestaurantDeleteView, ) urlpatterns = [ url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'), url(r'^$',RestaurantListView.as_view(), name= 'list'), url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(), name="detail"), url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(), name="restaurant-delete"), ] delete.html <form method="t" action="" >{% csrf_token %} <p>Are you sure you want to delete <strong> {{ obj }}</strong>?</p> <input type="submit" value="DELETE" /> </form> -
Using SQLite on AWS EB: no such table django_session
In my django app with the standard folder structure I have created an .ebignore file with the following content: # SQLite db.sqlite3 The purpose is that when I deploy to AWS EB my SQLite database won't get overwritten. I want to keep the SQLite database on my server unchanged when I modify my app. However, after I deploy ('eb deploy') and I visit the /admin url of my website I get the following error: no such table: django_session What's the correct way to re-deploy to AWS without overwriting the SQLite database? -
Django no reverse match at /
I'm trying to make a picture the url to the post the picture represents, and I must be doing something wrong, but I don't know what. I am getting this error when trying to visit the home page of my site. Error during template rendering In template .../home.html, error at line 48 Reverse for 'view_post' with keyword arguments '{'post_id': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$'] and the code it showcases <a href="{% url 'view_post' post_id=post.post_id %}"><img src="media/{{ item.image }}"></a> Also this is my view def view_post(request, post_id): post = get_object_or_404(Post,id=post_id) return render(request,'gram/view_post.html',{'post': post}) And url url(r'^post/(?P<post_id>[0-9]+)/$', views.view_post, name='view_post'), Thank you for your help. -
Django - Selecting a particular object from a set of objects
I have the following models in my Django app: class Review(models.Model): ID = models.AutoField(primary_key=True) text = models.CharField(max_length=1000) review_user = models.ForeignKey("User", on_delete=models.CASCADE) review_book = models.ForeignKey("Book", on_delete=models.CASCADE) class Review_is_helpful(models.Model): ID = models.AutoField(primary_key=True) is_helpful = models.BooleanField() # associated user who gave the review, and the review itself review_user = models.ForeignKey('User', on_delete=models.CASCADE) on_review = models.ForeignKey('Review', on_delete=models.CASCADE) class Book(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=50) description = models.CharField(max_length=1000) class User(models.Model): ID = models.AutoField(primary_key=True) For every book, we will have any number of reviews, and for each review, users can tag the review as Helpful/Not helpful (or not tag at all). Now, if I have a Review QuerySet reviews, and a User object user inside a view function, I want to additionally have the following for each review in the QuerySet: 1. If the review has been tagged by the user as Helpful/Not helpful (the corresponding Review_is_helpful object exists), then the corresponding Review_is_helpful object should be there along with the review object. 2. If the user hasn't tagged the review as Helpful/Not helpful (the corresponding Review_is_helpful object does not exist), then any suitable false value, like None will be okay. I was looking for something along the lines of using reviews.annotate(...), but I'm not sure what … -
importing arbitrary fields of a model from excel by django-import-export
I am using Django I have a model like this class DialogText(models.Model): id = models.AutoField(primary_key=True) dialogId = models.ForeignKey(Dialog, on_delete=models.CASCADE, verbose_name="Dialog") whoSay = models.CharField(blank=True, max_length=255) text = models.TextField(blank=True, verbose_name="Dialog Text") image = models.ImageField(upload_to=textDirectory, blank=True, verbose_name="Picture") createdTime = models.DateTimeField(auto_now_add=True) state = models.CharField(blank=True, max_length=255) sayTime = models.CharField(blank=True, max_length=255) text_type = models.CharField(blank=True, max_length=255) I am using django-import-export to import my data from excel. But I don't want all fields of my model to be imported from excel. For example, I haven't any column named 'id' in excel or I should set 'createdTime' the current time of the server and don't import from excel. I have tried this but it didn't work: class DialogTextResource(resources.ModelResource): fields = ('whoSay', 'text', 'text_type', 'sayTime', 'state', 'image', 'dialogId') class Meta: model = DialogText class DialogTextAdmin1(ImportExportModelAdmin): resource_class = DialogTextResource Thank's for any help. -
Object not found, but does exist
I have an existing working site, that takes advantage of Adobe Lightroom's catalog being an sqlite3 db. The model is auto-generated. Whilst updating the code for the site (to TemplateView and streamlining), I thought I'd get adventurous and pull on one of the class models to get the information about how many times a face (person) appears in the photos. The model: class Aglibrarykeywordpopularity(models.Model): id_local = models.IntegerField(primary_key=True, blank=True, null=False) occurrences = models.TextField() # This field type is a guess. popularity = models.TextField() # This field type is a guess. tag = models.TextField(unique=True) # This field type is a guess. class Meta: managed = False db_table = 'AgLibraryKeywordPopularity' The 'tag' value is obtainable from another model, where it's called 'id_local': face_id = list(Aglibrarykeyword.objects.values_list('id_local', flat=True)) The values for the 'face_id' are all present in the previous 'tag' field when you view the db. However, when using: for a in face_id: face_pop.append(Aglibrarykeywordpopularity.objects.get(tag=a).occurrences) .. it complains that there are no matches. I've substituted 'a' for a number, or string of the number, even adding '.0' to the representation, and it still complains no matches. I've tried .filter...first() etc. slides.models.DoesNotExist: Aglibrarykeywordpopularity matching query does not exist My current work-around is going to output All() of … -
Django model accessed globally
I want to have a model accessed throughout the whole project in the templates, not to declare it on every view. Is this possible? What is the best way to do this? Something like User is accessed through request.user. -
Django: Working With Messages
I'm trying to create a messaging app similar to what we see on social networks. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") ... timestamp = models.DateTimeField(auto_now_add=True) Everything is fine I can filter out the messages for request.user, but couldn't order the users. I wants to order the Users based upon to whom request.user sent a message & who sent a message to request.user most Recently, as we see on social networks. How can I do that? -
How to handle AuthAlreadyAssociated at Python-auth/Django-Social?
I use this python-social-auth/social-app-django to connect my web with social media I want to ask how to handle errors when the same account is used to sign up? For example, I signed up using facebook and I signed up again using twitter. both successfully registered into two separate accounts, when I logged in using my facebook and then on my account settings page, I want to connect my twitter that has been registered before it will display an error message "AuthAlreadyAssociated at / oauth / complete / twitter /" AuthAlreadyAssociated This message appears after I authorize on the twitter redirect page when it gets redirected back to my web. In short, how to deal with accounts that have been registered in other accounts? This is my views.py: @login_required def settings(request): user = request.user try: github_login = user.social_auth.get(provider='github') except UserSocialAuth.DoesNotExist: github_login = None try: twitter_login = user.social_auth.get(provider='twitter') except UserSocialAuth.DoesNotExist: twitter_login = None try: facebook_login = user.social_auth.get(provider='facebook') except UserSocialAuth.DoesNotExist: facebook_login = None can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password()) return render(request, 'profile/settings.html', { 'github_login': github_login, 'twitter_login': twitter_login, 'facebook_login': facebook_login, 'can_disconnect': can_disconnect }) And this is my settings.html template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Navhi Microblog - … -
Django aggregation and filtering
I am working with a model having a date, a group, and an identifier. I want to retrieve for each group the id of the minimum date value. My model: class MyModel(models.Model): group = models.ForeignKey('myapp.Group') date = models.DateTimeField(blank=True, null=True) The goal is to retrieve this: [ (u'group1', datetime.date(2016, 1, 23), 15 <- Id of the minimum date for group1), (u'group2', datetime.date(2015, 6, 25), 314 <- Id of the minimum date for group2), ... ] I tried the following: MyModel.objects.values_list('group').annotate(Min('date')).order_by('group') This works fine but gives me the date: [ (u'group1', datetime.date(2016, 1, 23)), (u'group2', datetime.date(2015, 6, 25)), (u'group3', datetime.date(2015, 6, 26)) ... ] I cannot find a way to add the id to those tuples without breaking the grouping clause in SQL. I tried to do a where date = min(date), but aggregation is forbidden in where clause. -
DjangoCMS render_model with HTML
I'm using Django CMS and the Aldryn News Blog app on a client site to display a blog listing. The default template code uses {% render_model article "lead_in" %} to display the "Lead in" excerpt text. However it is displaying p tags for me and I actually need them to render. https://pasteboard.co/GSq8XObQ.png https://pasteboard.co/GSq8ONF.png I have tried both: {% autoescape off %} {% render_model article "lead_in" %} {% endautoescape %} {% render_model article "lead_in" |safe %} The first does nothing and the second errors out. How can I get it to render the html tags? -
Hidden fields, auto assign values in django
I am still a newbie on django and Python. This is also my first question. I am trying to create a hidden field and auto assign a value to the hidden field. It can be either in the views or in the templates. I have a field "kind" that needs to be hidden. Also I need to assign a value to it depending on different views/templates so it populates the database. This is my class view: class Monthlypage(CreateView): template_name = 'monthly.html' model = models.Lead form = forms.LeadForm() fields = ['name','email','tel','kind'] This is my model form: class LeadForm(forms.ModelForm): def __init__(self, *args, **kwargs): kind = models.Lead.kind class Meta: model = models.Lead kind = forms.CharField(widget=forms.HiddenInput()) fields = ['name','email','tel','kind'] This is my model: class Lead(models.Model): name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() kind = models.CharField(max_length=265) def __str__(self): return self.name def get_absolute_url(self): return reverse('registrations') This is my template: <form class="" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="hidden" name="kind" value="{{ form.kind.monthly }}" /> <input type="submit" name="" value="Submit" class="btn btn-info"> I have tried many options and spend 2 days using different solutions. But no matter what I do I can't seem to populate the kind field in the database. -
Django. Algorithm on the back of the server [on hold]
Need to make a schedule program with an algorithm on the back of the server. Is it possible to make it in "pure" python on the back or should I use something else, like Ajax to change data on the server? What should I use? -
How to get user id from JWT
How to get user id from JWT token. My JWT token has payload something like this: { "username": "Steve", "is_admin": false, "id": 1 } How do I get access to user id? I actually want to update certain fields in database as per the id, that are for a specific user. Secondly after gaining the access how do I get update the fields? models.py class Profile(models.Model): branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('branch', 'year' ,'image',) What will be the view to update these fields? -
How can we log into a webserver using username password csrftoken and csrfmiddlewaretoken
I am trying to log into a server using my authentication(username and password) for app development purpose with swift 4. However my server requires csfrtoken and csrfmiddlewaretoken. How can I extract the csrfmiddlewaretoken value and make a Post request to log with all the other authentication? -
Access to file uploaded with FileField Django
I'm trying to create a Django form with a filefield to upload a pdf based on a model. #models.py class ProductionRequest(models.Model): ... contract_file = models.FileField('Contract file (PDF)', upload_to='contracts/') ... I can upload the file and save it in my object, but when I try to show the file in my template with this code {{ prod_req.contract_file }} it only show me the path to the file "contracts/file_uploaded.pdf". How can I make a link to download (or open in a new tab ) the file ? Plus : when I try to open the file from Django admin, with this link Contract file (PDF) : Currently: contracts/file_uploaded.pdf I don't show me the file, i got this : Page not found (404) Request URL: http://127.0.0.1:8000/admin/appname/productionrequest/1/change/contracts/file_uploaded.pdf/change/ How can I access to my file ? -
Heroku + GA, wrong city
I have Django app deployed on Heroku. When I analyse data on Google Analytics and use city dimension, I see a lot entries with "Ashburn" city. When I made a research, I found out this: Server info - Heroku.com Where is heroku.com hosted? IP: 54.243.150.141 Binary IP: 110010100001001001001100100100111101 Octal IP: 624111144475 Hexadecimal IP: ca124c93d Decimal domain: 110101 Registrar: MarkMonitor Inc. Country: United States City: Ashburn Latitude: 39.043701171875 Longitude: -77.487503051758 So as I understand Heroku passes its server location to GA. How I can get real user location? -
Javascript vs Python Django for web development
For a beginner who wants to start learning web development. What is the differences between Javascript and Python Django. I have a good background in Python. The main question is: can I do everything with Python Django or I may need Javascript later ? Which one should I start with? Thanks!