Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Requirements.txt causes an error when I'm deploying my Django app to the Azure web app service
I've got a Django app hosted on the Azure web app service. I recently removed the skipPythonDeployment file, so that I can add custom packages from my requirements.txt file. At first this worked fine, when I added just the crispy forms package, but after that I wanted to update my Django installation to 1.11 (the default version in the app service is 1.9.4). So this is what my requirements.txt looks currently: django<2 django-crispy-forms==1.6.1 Now, when I try to push my commits to the server (git push azure master) I get the following deployment log: Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 308 bytes | 0 bytes/s, done. Total 3 (delta 1), reused 1 (delta 0) remote: Updating branch 'master'. remote: ............................................. remote: Updating submodules. remote: Preparing deployment for commit id '763167dc3c'. remote: Generating deployment script. remote: Running deployment command... remote: Handling python deployment. remote: Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. remote: Detecting Python runtime from site configuration remote: Detected python-2.7 remote: Found compatible virtual environment. remote: Pip install requirements. remote: An error has occurred during web site deployment. remote: remote: Error … -
Django - alter post data in CreateView
I am trying to change a value in a post request but am getting the following error: IntegrityError: null value in column "owner" violates not-null constraint DETAIL: Failing row contains (30, 123, G, null) <--> (index, number, type, owner) The form itself: <form method="post"> {% csrf_token %} {{form.number}} {{form.type}} <input type="hidden" value="{{variable}}" name="owner"> <button type="submit">Save</button> </form> The request.POST data: <QueryDict: {'csrfmiddlewaretoken': ['TN3yNiGcvAso6V1UYZDHpyIQ1sNTMqDICPSqX2sftVpZfX6drambOkzoGBECLKcN'], 'number': ['123'], 'type': ['G'], 'owner': ['']}> To modify the data: class NodeCreateView(CreateView): model = Node form_class = NodeCreateForm ... def post(self, request, **kwargs): request.POST = request.POST.copy() request.POST['owner'] = 2 return super(NodeCreateView, self).post(request, **kwargs) The updated POST data: <QueryDict: {'csrfmiddlewaretoken': ['TN3yNiGcvAso6V1UYZDHpyIQ1sNTMqDICPSqX2sftVpZfX6drambOkzoGBECLKcN'], 'number': ['123'], 'type': ['G'], 'owner': [2]}> Where am I going wrong? -
Test machine Postfix setting to Django
I am working django application with the development server(no domain). And I can't send the mail from Django password reset function. There are no lines about mail in syslog and mail.log. I have no idea if it is because I don't have a domain. my settings.py is following. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'Admin <ubuntu@localhost>' But I can send a mail from python shell. from django.core.mail import send_mail send_mail('Test', 'Test mail from the server', 'ubuntu@localhost',['xxxxxxxx@gmail.com'], fail_silently=False) What is the problem? Please let me know. -
Can't get owner as foreign key to my model -- django
I'm trying to do a form so a user can upload a video, the problem is i can't get current user or it's id as a foreign key on my video model Error: IntegrityError Exception Value: (1048, "Column 'owner_id' cannot be null") How can i solve the problem please, i looked at django documentation but doesn't find answer. My models.py: class Videowtm(models.Model): name = models.CharField(max_length=50, blank=True) description = models.CharField(max_length=255, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) video = models.FileField(upload_to='videos/') My forms.py: class VideowtmForm(forms.ModelForm): class Meta: model = Videowtm fields = ('name', 'description', 'video', ) My views: @login_required def model_form_upload(request): if request.method == 'POST': form = VideowtmForm(request.POST, request.FILES) form.owner = request.user if form.is_valid(): form.save() return redirect('home') else: form = VideowtmForm() return render(request, 'model_form_upload.html', { 'form': form }) -
can't set attribute while assigning data to a POST form field
I am getting values after I submitted the form so Before storing database I get output like this name = self.form['name'].data now name is showing on debugging name =u'sadas' so I want to assign that to self.form['subtitle'].data=name which gives on debugging name= u'' so what I should do now as on assigning It is giving can't set attribute error. And I want to update value. full tracback of error Request Method: POST Request URL: http://127.0.0.1:8002/maps/new/ Django Version: 1.7.1 Exception Type: AttributeError Exception Value: can't set attribute Exception Location: /home/oneclout/Desktop/Projects/mapport-acm-new/mapport/src/mapport/maps/views.py in new, line 411 Python Executable: /usr/bin/python2.7 Python Version: 2.7.12 Python Path: ['/home/oneclout/Desktop/Projects/mapport-acm-new/mapport/src', '/home/oneclout/Desktop/pycharm-145.597.11/helpers/pydev', '/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg', '/home/oneclout/Desktop/Projects/mapport-acm-new/mapport/src', '/home/oneclout/Desktop/pycharm-145.597.11/helpers/pydev', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Tue, 22 Aug 2017 16:29:28 +0000 And my view is like this def new(self): self.map = Map() self.form = self.map.form(self.request.POST) # if self.map.id!=None: name = self.form['name'].data print name # name = slugify(name) self.form['subtitle'].data=name self.save_form_if_appropriate('map') self.map.id=self.map.pk; if self.map.id!= None: return self.redirect('mapport.maps.one', self.map.id) else: return self.render('mapport/maps/show.html') -
Djangallauth is not using my signup form
I use custom signup form for setting users first name and last name and setting a profile for a user, but django-allauth still uses its default SignupForm. In settings.py: ... ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_AUTO_SIGNUP = False ACCOUNT_SIGNUP_FORM_CLASS = 'accounts.forms.SignupForm' ... Custom signup form: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() models.BasicProfile.objects.create(user=user) Django-allauth version - 0.33.0 -
best way to implement multiusers chat application in websites with django
what is the bast way to implement a powerful multiusers chat application in websites i am using django as backend. -
Django - Image crop using a widget as a field in the form
I have a Product Model and Image Model with a Foreign key to the product model. So in a form for Product creation I will have/need multiple Image File Upload inputs. I want to replace the default Image file-upload form field with a Image (like a plus sign, like add a new image, using a widget). When the user click on a add a new image a pop-up will apear with a javascript crop. I need to get the data(coordinates) from the javascript crop back to Django, use Pillow to crop and fill the Image Model field. What is the best approach for this mechanism for the form field(will not be a real upload) ? , maybe a link to a tutorial (I know there are some Django package that do something like that but are really what I want regarding crop control) -
Django dont save my form after signup
I make a simple website with userena for user registration and a custom form to fill after the signup. But when the account is created and the form submit datas are'nt stored. After ~1min if i refresh the form and resubmit everything work, but not after a fresh signup/signin There is my code models.py from cms.models.pluginmodel import CMSPlugin from django.db import models from django.contrib.auth.models import User class Game(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=50) def __str__(self): return self.name class Tournament(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=50) game = models.OneToOneField( Game, on_delete=models.CASCADE, verbose_name="related game", ) def __str__(self): return self.name class TeamMember(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Team(models.Model): name = models.CharField(max_length=100) official = models.BooleanField(default=False) tournaments = models.ManyToManyField(Tournament, blank=True) user = models.OneToOneField(User, related_name='created_by') team_member = models.ManyToManyField(TeamMember, blank=True) def __str__(self): return self.name forms.py class TeamRegistrationForm(forms.ModelForm): team_member_1 = forms.CharField(widget=forms.TextInput, label="Team member 1") team_member_2 = forms.CharField(widget=forms.TextInput, label="Team member 2") team_member_3 = forms.CharField(widget=forms.TextInput, label="Team member 3") class Meta: model = Team fields = [ 'name', ] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(TeamRegistrationForm, self).__init__(*args, **kwargs) def save(self): data = self.cleaned_data team = Team(name=data['name']) team.user = self.user team.save() team.team_member.get_or_create(name=data['team_member_1']) team.team_member.get_or_create(name=data['team_member_2']) team.team_member.get_or_create(name=data['team_member_3']) team.save() If someone have an idea? thanks a lot -
Can someone help me in setting up daphne server
enter image description here Can some helpme in solving Worker server failed to respond within time limit.Daphne. Getting this error while running django server -
Django get count of each age
I have this model: class User_Data(AbstractUser): date_of_birth = models.DateField(null=True,blank=True) city = models.CharField(max_length=255,default='',null=True,blank=True) address = models.TextField(default='',null=True,blank=True) gender = models.TextField(default='',null=True,blank=True) And I need to run a django query to get the count of each age. Something like this: Age || Count 10 || 100 11 || 50 and so on..... -
Disable caching in django-views with imported json api
I have imported json from an api into my views. It now works perfectly fine but somehow if I go onto the website, somehow django is caching the values given by the api and therefore does not display the recent values. I've tried to use "never_cache" and "cache control" but it didn't work. Is there a solution I can do with django or Apache? My views from __future__ import unicode_literals from django.shortcuts import render from urllib import urlopen import json from django.views.decorators.cache import never_cache, cache_control euro = json.loads(urlopen('http://api.fixer.io/latest').read()) usdollar = euronen['rates']['USD'] #@never_cache @cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True) def home(request): return render(request, "index.html", {"usdollar":usdollar}) -
How to create a filter queryset on an array so that all search terms are required?
I have a Photo model with tags. I want to be able to create a query such that only photos having all search tag terms will be returned. The current behavior (using the view code below) returns photos having any of the tags being searched on. @list_route(methods=['post']) def tags(self, request): """ search for entities by tags they contain :param request: :return: Response """ tags = json.loads(request.data['tags']) photos = Photo.objects.filter(tags__name__in=tags, owner=self.request.user).distinct() page = self.paginate_queryset(photos) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(photos, many=True) return Response( data=serializer.data ) Here is the model class: class Photo(TimestampModerated): owner = models.ForeignKey('auth.User', related_name='photos', on_delete=models.CASCADE) uuid = models.UUIDField(default=uuid4, editable=False) slug = models.SlugField(max_length=80, editable=False) title = models.CharField(max_length=80, blank=False, null=False) description = models.TextField(verbose_name='description of entity', blank=True, null=True) photo = models.ImageField(upload_to=user_directory_path, height_field="height", width_field="width", blank=True) height = models.IntegerField(blank=True) width = models.IntegerField(blank=True) tags = TaggableManager(blank=True) hash = models.CharField(max_length=64, unique=True, null=True) class Meta: verbose_name_plural = "photos" def __str__(self): return self.title def delete(self, using=None, keep_parents=False): default_storage.delete("{}".format(self.photo)) super().delete() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Photo, self).save(*args, **kwargs) I'm using django-rest-framework to create the views and django-taggit for the tagging. -
Django: Filter combined columns with tuple
How do I generate this type of where clause using the Django ORM? where (datetime, id) < (%last_datetime, %last_id) Background I have a model like this: class Messages(models.Model): # Implicit "id" serial primary key datetime = models.DateTimeField(db_index=True) message = models.CharField(max_length=1024) I sort the messages by datetime and use the id as a tie breaker for consistent sorting when multiple messages have the same datetime with: Messages.objects.order_by('datetime', 'id') Now I need to filter out messages that were ordered before a given known message. -
Django REST framework serialize last log
I use Django rest framework in a website, and it works well. But I just meet a speical problem, just like this: models.py: class User(models.Model): uid = models.IntegerField( primary_key=True, ) account = models.CharField( max_length=15, unique=True, blank=False, ) password = models.CharField( max_length=40, blank=False, ) class LoginLog(models.Model): sn = models.AutoField( primary_key=True, ) user = models.ForeignKey( to=User, ) time = models.IntegerField( null=False, ) serializers.py: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' How can I serialize the last LoginLog in UserSerializer? Just return json data like this: { "account": "admin", "uid": 1, "last_login_time": 1503414665 } -
Gettign data from django views to html snippet and update every 5 seconds
I'm trying to build a page that gets bitcoin prices from different exchanges and update price to a set interval. I managed to get the prices from API's and make them display to page but prices don't get update unless I manually refresh the page. After few googles I found that I have to use AJAX to update prices to a set interval. The problem is JavaScript looks too hard for me at the moment so that I can understand how to make a get request trough AJAX. I google it for few days now but still I can't understand. Yes I know I have to learn JavaScript but for now I want to build this small project. OK so why I posted this? I may be a lazy bastard :D and I'll ask for someone to provide me the code that I have to place it between script tags in my html file so that I can make the request to server and update prices every 5 seconds.I'll post alot of code so this may help someone to help me. I hope will work.. Thx. views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse … -
Django migrations not applying to Heroku postgres
I've been attempting to deploy my django project to Heroku but am struggling massively with getting the database sorted. I use makemigrations locally and push them to heroku, and then run heroku run python manage.py migrate with the following output: Operations to perform: Apply all migrations: account, admin, article_viewer, auth, cities_light, contenttypes, home, sessions, sites, socialaccount, taggit, user_profile, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying taggit.0001_initial... OK Applying wagtailimages.0001_initial... OK Applying wagtailcore.0001_squashed_0016_change_page_url_path_to_text_field... OK Applying wagtailimages.0002_initial_data... OK Applying wagtailimages.0003_fix_focal_point_fields... OK Applying wagtailimages.0004_make_focal_point_key_not_nullable... OK Applying wagtailimages.0005_make_filter_spec_unique... OK Applying wagtailimages.0006_add_verbose_names... OK Applying wagtailimages.0007_image_file_size... OK Applying wagtailimages.0008_image_created_at_index... OK Applying wagtailimages.0009_capitalizeverbose... OK Applying wagtailimages.0010_change_on_delete_behaviour... OK Applying wagtailcore.0017_change_edit_page_permission_description... OK Applying wagtailcore.0018_pagerevision_submitted_for_moderation_index... OK Applying wagtailcore.0019_verbose_names_cleanup... OK Applying wagtailcore.0020_add_index_on_page_first_published_at... OK Applying wagtailcore.0021_capitalizeverbose... OK Applying wagtailcore.0022_add_site_name... OK Applying wagtailcore.0023_alter_page_revision_on_delete_behaviour... OK Applying wagtailcore.0024_collection... OK Applying wagtailcore.0025_collection_initial_data... OK Applying wagtailcore.0026_group_collection_permission... OK Applying wagtailimages.0011_image_collection... OK Applying wagtailimages.0012_copy_image_permissions_to_collections... OK Applying wagtailimages.0013_make_rendition_upload_callable... OK Applying wagtailimages.0014_add_filter_spec_field... OK Applying wagtailimages.0015_fill_filter_spec_field... OK Applying wagtailimages.0016_deprecate_rendition_filter_relation... OK Applying wagtailimages.0017_reduce_focal_point_key_max_length... OK Applying wagtailimages.0018_remove_rendition_filter... OK Applying wagtailimages.0019_delete_filter... OK Applying wagtailcore.0027_fix_collection_path_collation... OK Applying wagtailcore.0024_alter_page_content_type_on_delete_behaviour... OK Applying wagtailcore.0028_merge... OK Applying wagtailcore.0029_unicode_slugfield_dj19... OK Applying wagtailcore.0030_index_on_pagerevision_created_at... OK Applying wagtailcore.0031_add_page_view_restriction_types... OK Applying wagtailcore.0032_add_bulk_delete_page_permission... … -
Custom filters in Django API
I have a requirement in my project where I have to implement filtering strategy for GET requests in following way: /books?filterBy=(customdate eq 2016-05-01) AND ((pages gt 20) or (pages lt 10)) where customdate and pages are fields in the books table. What are the possible ways to parse this parameter and create a Django ORM query from the passed parameter. The only way I know of is to write custom logic for parsing the filterBy manually and then constructing the ORM query. I was wondering if there is a better way to go about. Thank you. -
Django - Best way to define a url with querystring from APIView
so i need to define a URL with 4 parameters: 2 chars, one int and one float. what is the most correct way to do that? (on urls.py) -
Foreign Key in nested serializers
It's the first time I work with nested serializers, I have a model Order having a foreign key referencing another model Client , and a many to many relationship with a modal Products. I want the Order api to enable creating a product instance as well as a client instance when creating an order. After researches I found that I should opt for nested serializers, I have found a way to create products when creating the order but couldn't find out how to do it with th modal client. modals.py class Client(models.Model): first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) email = models.EmailField( verbose_name=_('Email address'), max_length=255, unique=True, primary_key=True ) class Product(models.Model): sku = models.CharField( verbose_name=_('SKU'), unique=True, max_length=120, primary_key=True ) name = models.CharField( verbose_name=_('Name'), max_length=150 ) url = models.URLField( verbose_name=_('URL'), blank=True, null=True ) class Order(models.Model): client = models.ForeignKey(Client) origin = models.CharField( verbose_name=_('Origin place'), max_length=120, null=True, blank=True ) destination = models.CharField( verbose_name=_('Destination place'), max_length=120, null=True, blank=True ) products = models.ManyToManyField( Product, related_name= "orders", null=True, blank=True, ) serializers.py class ProductSerialiser(serializers.ModelSerializer): class Meta: model = Product fields = ('sku', 'name', 'url') class ClientSerialiser(serializers.ModelSerializer): class Meta: model = Client fields = ('email','first_name', 'last_name') class OrderSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.email') client= ClientSerialiser() products=ProductSerialiser(many=True) class Meta: … -
when i use urllib on Python it gets me error
every time i try to import urllib and use urlopen it gets me: http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found -
Django: lookup for many to many relation
I have following models: class Name(models.Model): name = models.SlugField(max_length=100) primary = models.BooleanField() project = models.ForeignKey( Project, null=True, blank=True, on_delete=models.DO_NOTHING, related_name="names") class Robject(models.Model): project = models.ForeignKey(to=Project, null=True, blank=True) names = models.ManyToManyField( "Name", related_name="robjects", limit_choices_to= limit_name_choices, blank=True ) [...] I'm looking for Name filter lookup, which gives me only names that have no relations to any robject. Thanks in advance! -
Django doesn't support MySQL Group Replication
I'm using Compose for MySQL which uses MySQL 5.7 Group Replication When trying doing DB tests with Django 1.11.4 i get errors regarding the rollback_test (because it doesn't hold the requirement of Primary Key) and transaction-write-set-extraction!=OFF requirement for creating SAVEPOINTS. django.db.utils.OperationalError: (1290, 'The MySQL server is running with the --transaction-write-set-extraction!=OFF option so it cannot execute this statement') Everything works well besides the tests. Is there any way to tell Django that it's a Group-Replication MySQL DB and avoid these specific tests? -
Show an initial value for file/image upload in rendered Django form
So Im uploading an image and a document. The problem is two fold, first in the rendered form it is showing the label but not the initial value or even a picture so its hard for anyone to realise that they have to upload anything. Secondly, upon uploading its not showing the document/image that has been uploaded so you end up thinking it didn't work. I've attached a picture below showing the issue. How do I fix this? showing the bank spots in the form from forms.py profile_image = forms.ImageField(initial="choose a profile image", required=True, label="Profile Picture") cvv = forms.FileField(initial='upload a CV', required=True, label="CV") from models.py models.ImageField(upload_to=teacher_directory_path, null = True, blank=True, default='/perfil.png') cvv = models.FileField(upload_to=teacher_directory_path, null=True, blank = True, verbose_name="CV") I must add, in the models when in admin everything is showing fine but when rendering then I dont see anyvalue. -
how to set no initial value on CheckboxSelectMultiple
I don't want any check box selected on a CheckboxSelectMultiple widget render. How do I make sure that no check box is preselected ? All the examples I found were showing how to select a particular value.