Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to load model objects and model form while still allowing migrations on empty projects
I have a Django project. I need to generate choices dynamically, but because I'm reading from a model, it won't let me run manage.py migrate because it errors where it tries to read from a model that doesn't have a table, basically a circular reasoning. I don't want new people on the project to get confused and have to comment things out before running migrations. How can I fix the following code; I tried setting get_tag_choices() on the TagSelectForm as instance method but it complained about no such thing as self def get_tag_choices(): #reading tags to get all values tags = MyTag.objects.all()#collect tags CATEGORY_CHOICES = [('', '')]#default selection if tags: for tag in tags: CATEGORY_CHOICES.append((tag.name, tag.name)) return CATEGORY_CHOICES #---------------------------------------------------------------------------------------------------- #this class uses preformatted fields, like model, #just setting up structure of a multiple choice field class TagSelectForm(forms.ModelForm): class Meta: model = MyTag fields = ('name',) name = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=get_tag_choices() ) Any help appreciated, ty -
How do I filter values in a Django 1.7 form using ModelForm?
I am trying to use the ModelForm to add my data. It is working well, except that the ForeignKey dropdown list is showing all values and I only want it to display the values that a pertinent for the logged in user. These are my models: class productos(models.Model): user = models.ForeignKey(User) secciones = models.ForeignKey(secciones) name = models.CharField(max_length=50) image = models.ImageField(upload_to = 'productos') precio = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) descripcion = models.TextField(max_length=300, null=True,blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(productos, self).save(*args, **kwargs) def __unicode__(self): return self.name ##################################################################### class secciones(models.Model): name = models.CharField(max_length=50) user = models.ForeignKey(User) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(secciones, self).save(*args, **kwargs) def __unicode__(self): return self.name the form code: class AgregarProducto(forms.ModelForm): class Meta: model = productos And finally, the view code: def agregar_producto(request): if request.method == "POST": modelform = AgregarProducto(request.POST,request.FILES,user=request.user) print modelform if modelform.is_valid(): modelform.save() return redirect("/editar-perfil/") else: modelform = AgregarProducto() return render(request, "home/AgregarProducto.html", {"form":modelform}) How do I get the form to display only the subset of secciones where secciones.user equals the logged in user? -
How to create stripe_id on subscription?
I'm using the API stripe with django-allauth on my website, I want to create a stripe_id for new users who just subscribed, not long ago my code was working and today I got a new error that I have never encountered yet : stripe.error.AuthenticationError: No API key provided. (HINT: set your API key using "stripe.api_key = "). You can generate API keys from the Stripe web interface. When an user subscribes OR login in for the first time there is a callback in which I create a new stripe_id, the callback is called but the error raise when I create a Customer. See models.py : class Profile(models.Model): stripe_id = models.CharField(max_length=200, null=True, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) ... def stripeCallback(sender, request, user, **kwargs): user_stripe_account, created = Profile.objects.get_or_create(user=user) if user_stripe_account.stripe_id is None or user_stripe_account.stripe_id == '': new_stripe_id = stripe.Customer.create(email=user.email) #error occurs here user_stripe_account.stripe_id = new_stripe_id['id'] user_stripe_account.save() user_logged_in.connect(stripeCallback) user_signed_up.connect(stripeCallback) Am I missing something ? -
How to execute Python script using AJAX
I have executed PHP script using AJAX before but what if I wanted to work server side using Python? The following javascript file calls the python code which is supposed to send me an email. I ran the python code through command line and that seems to work. ANY HELP? JAVASCRIPT FILE errormessage.style.display="none"; var data=$("#contact-info").serialize(); <? exec("/static/python/get-message.py") ?> PYTHON FILE import smtplib print("DDFDDFD") content='example stuff here' #server and port mail=smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() #TLS MODE mail.starttls() mail.login('Varun.Rao095@gmail.com','****') mail.sendmail('Varun.Rao095@gmail.com','Varun.Rao095@gmail.com',content) mail.close() -
cannot reach static files Django 1.10
I am not getting any static files to show up in Django. The repo is located at git clone git@bitbucket.org:codyc54321/bookwormbuddy.git In settings.py I have STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' I have a static folder in the root directory I cannot reach any static files. The file in question right now is http://127.0.0.1:8000/static/images/bookshelf_background.jpg The load failing is in static/main.css: html { background-image:url('/static/images/bookshelf_background.jpg'); background-repeat:no-repeat; background-size:100%; background-attachment: fixed; } Using Django 1.10. Thank you -
Django adding multiple records with the same foreign key in ModelAdmin
Suppose I have the following two models task and person. Now each person can have multiple tasks (one to many relationship). Now in the admin app for a person I can only add one foreign key per record thus I'll have to create multiple records for a person having a different task but the same email and name fields. Is there anything I can do in personAdmin that would allow me to add multiple foreign keys for the same person and in the backend it would create multiple records ? class task(models.Model): description = models.CharField(max_length=100) class person(models.Model): task = models.ForeignKey(Author, on_delete=models.CASCADE) email =models.CharField(max_length=100) name = models.CharField(max_length=100) class personAdmin(admin.ModelAdmin): pass -
django-selectable populate AutocompleteSelectField on loading form
I succesfully implemented the django-selectable AutoCompleteSelectField in a simple form that lets you enter an note description and a corresponding domain category ( domain and foreign key picked from other Many-to-One relationship See: most relevant code: # MODEL class Note(models.Model): notetext = models.TextField(default='nota') domain = models.ForeignKey(Domain) def __str__(self): return self.notetext def get_absolute_url(self): return reverse('note:note_detail', args= [self.id]) # FORM class NoteForm(forms.ModelForm): domainselect = AutoCompleteSelectField(lookup_class= DomainLookup, label='Pick a domain category', required=True,) def __init__(self, *args, **kwargs): super(NoteForm, self).__init__(*args, **kwargs) domaintext = self.instance.domain.title self.fields['domainselect'].widget = AutoCompleteSelectWidget(DomainLookup , { 'value': self.instance.domain.title } ) def save(self, commit=True): self.instance.domain = self.cleaned_data['domainselect'] return super(NoteForm, self).save(commit=commit) class Meta: model = Note fields = ('notetext',) widgets = { 'domain' : AutoCompleteSelectWidget(DomainLookup), } # VIEW class EditNoteView(generic.edit.UpdateView): model = Note form_class = NoteForm success_url = "/note/" def get_queryset(self): base_qs = super(EditNoteView, self).get_queryset() return base_qs.filter() def get_object(self): object = get_object_or_404(Note,id=self.kwargs['id']) return object # TEMPLATE {% extends "base_sidebar.html" %} {%block content%} <form action="" method="post"> {{form.as_p}} <button type="submit">Save</button> {% csrf_token %} {% load selectable_tags %} {{ form.media.css }} {{ form.media.js }} </form> {%endblock%} Now, when an existing record is selected for editing via generic.edit.UpdateView in a Modelform, I want to populate the AutocompleteSelectField with the corresponding values ( domain description and id ) formerly … -
FORCE_SCRIPT_NAME is causing urls to resolve incorrectly; can I override this in different contexts?
I'm in the process of upgrading a django app from 1.9.10 to 1.10.5 and am finding that the URL is no longer resolving correctly because FORCE_SCRIPT_URL is set, and is being tacked onto ** everything ** now. I suspect that this is because of "an addition in django.setup() allows URL resolving that happens outside of the request/response cycle (e.g. in management commands and standalone scripts) to take FORCE_SCRIPT_NAME into account when it is set". (https://docs.djangoproject.com/en/1.10/ref/applications/#django.setup). If I set the FORCE_SCRIPT_URL, the site works locally on the browser, and I can login, go to different apps within this project, and they all seem to work ok for the most part. However, all of the view tests fail with a 404 error because the URLs are not resolving correctly, and all of my tests involving logging in are also failing (again, I think this is because the url is not resolving correctly). For example, previously, calling reverse(my_url_name) would return /my_path whereas now, it returns /subdomain/my_path. Are there any work arounds or things I am missing in this upgrade to fix this issue? I'd really prefer not to unset this setting, FORCE_SCRIPT_URL, as there are many things that seem to depend on this. … -
Warmup django application during uwsgi chain-raload
I'm using uwsgi + django and trying to make the fastest reloading. I've configured chain reloading (http://uwsgi-docs.readthedocs.io/en/latest/articles/TheArtOfGracefulReloading.html#chain-reloading-lazy-apps), but still there are couple seconds of latency while serving first request after worker reload. Is there any way to warm up the django application with uwsgi configuration to reduce waiting time? -
how to categorize sql inputs according to models in django
I want to learn django and I should categorize my sql inputs according to my models. For example I have some models like this: class Author(models.Model): authorName = models.CharField(max_length=30) def __str__(self): return self.authorName class Book(models.Model): author = models.ForeignKey(Authors, on_delete=models.CASCADE) bookName = models.CharField(max_length=60) downloadLink = models.FileField() downloadCount = models.IntegerField(default=0) def __str__(self): return self.bookName and I want to an output in my .html file like this; Sherlock Holmes A Study in Scarlet The Sign of the Four The Hound of the Baskervilles Suzanne Collins The Hunger Games Catching Fire Mockingjay I tried this code in my html file but it doesn't work <ul> {% for author in all_authors %} <h2>{{ author.authorName }}</h2> {% for book in all_books %} {% if book.author == author.authorName %} <li><a href="{{ book.downloadLink.url }}" download="{{ book.downloadLink.url }}">{{ book.bookName }}</a></li> {% endif %} {% endfor %} {% endfor %} </ul> Here is my view.py file; def books(request): return render(request,'../templates/library/library-template.html', { 'all_authors': Author.objects.all(), 'all_books': Book.objects.all(), }) How can I fix it? Or are there any different solution for fix this? Thank you.. :) -
Django form error: AttributeError: 'module' object has no attribute 'form'
Getting an error that I'm struggling with which I think is originating from my form class. In the traceback is says: File "/Users/Bwilburn/workSpace/python-dir/learning_site/learning_site/__init__.py", line 3, in <module> class SuggestionForm(forms.form): but in my forms.py file the file that my class inherits from is forms.Form and any attempt I try and make fails. Can someone help me out? Here is my traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Bwilburn/workSpace/python-dir/learning_site/learning_site/__init__.py", line 3, in <module> class SuggestionForm(forms.form): AttributeError: 'module' object has no attribute 'form' Getting this error when I try to display my form on the page. Here is my forms.py: from django import forms class SuggestionForm(forms.Form): name = forms.CharField() email = forms.EmailField() suggestion = forms.CharField(widget=forms.Textarea) views.py: from django.shortcuts import render from . import forms def suggestion_view(request): form = forms.SuggestionForm() return render(request, 'suggestion_form.html', {'form': form}) urls.py: from django.conf.urls import url from django.conf.urls import include from django.contrib import admin from . import … -
invalid literal for int() with base 10: when using foreignkey
I'm trying to create a private chat with channels, I'm encountering an issue when passing an username to the url. invalid literal for int() with base 10: 'username' This error probably occurs because I'm using a ForeignKey because everything worked well using a ChatField and I want to know how I can resolve this issue. models.py : class Room(models.Model): gig = models.ForeignKey(Gig, null=True) creator = models.ForeignKey(User, related_name='creator', null=True) views.py def new_room(request): try: #get the submited product object gig = Gig.objects.get(id=request.POST.get('inGig_id')) except Gig.DoesNotExist: return redirect('/') creator = request.user Room.objects.get_or_create(gig=gig, creator=creator) return redirect(commenting_room, gig=gig.id, creator=creator) def commenting_room(request, gig, creator): room = Room.objects.get(gig=gig, creator=creator) #error occurs here ... urls.py url(r'^room/(?P<gig>\d+)/(?P<creator>\w+)/$', views.commenting_room, name='commenting_room_detail'), Any suggestion on how I can resolve this problem ? -
Django - Load static files from another app
In app1 I am trying to load static files from app2. I set no STATICFILES_FINDERS in project settings.py, which means, Django will use default AppDirectoriesFinder when it finds static subdirectory inside app directory. Problem: In template files of app1, I can generate urls of static files for app1 very easily. But if I want app1 template files to generate urls for static files of app2, links are not working. How can I in app1 generate static files of app2? App1 template file: {% load static %} <img src="{% static "app1/example.jpg" %}"> <!-- ok --> <img src="{% static "app2/example.jpg" %}"> <!-- link broken --> HTML Output: <img src="http://localhost:8000/static/app1/example.jpg"> <img src="http://localhost:8000/static/app2/example.jpg"> -
Limiting the options of foreign key in ModelAdmin returns "Select a valid choice"
I am attempting to limit the option to a foreign key in the admin app for a specific user (The field that i am trying to limit is called school) . This is what my code looks like - Unfortunately there are two problems (mentioned below) when I attempt to edit a student (by clicking on their name). 1.The default value for school is -- 2.When I select the right school from the drop down and attempt to save I get the error on school field saying Select a valid choice. That choice is not one of the available choices. class modelStudentAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(modelStudentAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: schoolInstance = modelSchool.objects.get(user=request.user) qs = modelStudent.objects.filter(school=schoolInstance) return qs def formfield_for_foreignkey(self, db_field, request, **kwargs): if request.user.is_superuser: return super(modelStudentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) #Not superuser only staff if db_field.name == 'school': t = modelSchool.objects.filter(user=request.user).values_list("school_name",flat=True) kwargs['queryset'] = t return super(modelStudentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs) Now if I remove the method def formfield_for_foreignkey(self, db_field, request, **kwargs): everything works but then I cannot restrict the foreign key. Any suggestions on what I might be doing wrong ? -
The meaning of objects in Django
def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error':'Username has already been taken'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) login(request, user) return render(request, 'accounts/signup.html') else: return render(request, 'accounts/signup.html', {'error':'Passwords didn\'t match'}) else: return render(request, 'accounts/signup.html') In the following program, the line user = User.objects.get(username=request.POST['username']) is confusing me in some point. I know that if I have the dictionary d = {word1 : definition1, word2 : definition2}, then d.get[word1] will output definition1 (the id of word1). So User.objects is a dictionary, because of the structure dict.get(). I have a little problem with this part of the line. Could anyone be able to explain to me what is the meaning of objects? -
Where do I store GeoDjango LayerMapping definitions in Django project?
GeoDjango uses LayerMapping classes to define mappings from spatial data formats like shapefile to models. Where do I normally place those? Can they be used from a data migration? -
Arrange a list of dictionary by number
I have a GET query the format of it. ?title1=a&test1=b&title2=a&test2=b&..&titleN=a&testN=b The view contains just the code above def index(request): # This is my view print request.GET.items(): This is the result returned when I run the query : { 'title1':'a', 'test1':'b', 'title2':'a', 'test2':'b','titleN':'a', 'testN':'b' } I want to create a new list of dictionary. [{'title1' : 'a' , 'test1':'b'} , {'title2' : 'a' , 'test2':'b'}, {'titleN' : 'a' , 'testN':'b'}] As you can notice I want to arrange all the data by number and N here is a Number -
Serialization error: Incorrect type. Expected pk value, received Post
I'm trying to create an object with nested serialization so other objects that relate to it are also created. I've overridden the create() method for ModelSerializer and the main object is created successfully. def create(self, validated_data): post_data = validated_data.pop('post_set') big_post = BigPost.objects.create(**validated_data) // This works for post in post_data: e = PostSerializer(data=post) if e.is_valid(): e.save() else: print(e.errors) // Prints 'Incorrect type' error return big_post However, when trying to create the nested object (Post), I get this error: {'note': ['Incorrect type. Expected pk value, received Note.']} 'note' is a field of the PostSerializer as shown below: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'note', 'title', 'description') I am aware that default behaviour of ModelSerializer is to create PrimaryKeyRelatedField for any related fields of the model. But, I don't know why an instance is being created when the data submitted is just a PK like so: {"note":3, ....} -
Python "'dict' object has no attribute 'savetofile'"
py, two.py One.py two.savetofile(profil) two.py def savetofile(profil): print profil Profil is here {'jozeef': {'stredaz': None, 'utorokz': None, 'pondelokz': '22', 'stvrtokz': None, 'utorokk': None, 'pondelokk': '22', 'stvrtokk': None, 'sobotaz': None, 'piatokk': None, 'nedelak': None, 'sobotak': None, 'nedelaz': None, 'piatokz': None}} What is the wrong Please ? -
Alternative for pylibmc cache backend in django 1.7
I have recently migrated from django 1.6 to 1.7 which has the following changes: If you instantiate cache backends directly, be aware that they aren’t thread-safe any more, as django.core.cache.caches now yields different instances per thread. Since I use uwsgi in production with threads, I've started getting errors from pylibmc (which is not thread-safe). I want to ask if there is any substitution for pylibmc backend. I know there is another backend served with django (python-memcached), but i've read that it is not suitable for highload solutions since it's quite slower than pylibmc. -
Django: How to show field HTML in manage.py shell
I am trying to get a better understanding of how django works in the background to accomplish tasks, so I am playing with the shell, as I figure that will help me understand the structure better. Right now, I am trying to figure out, on a component level, how a form field is populated. For instance, if I have a field of: first_name = forms.CharField(max_length=50) How would I, in the manage.py shell, populate that field with a specific user, and show how it is rendered in the template? For instance, if I have: employee = Employees.get(pk=1) How do I then get employee.first_name in the first_name field, and then show the HTML it would display to the template? In other words, how do I get from having these two things, to having the prepopulated field that would show in an UpdateView. -
Inherited models in Django and better way to query them
I have base model Resource and several inherited models, for example Switch, Port, and so on. Every related model can have it's own additional fields and i must be able to query by them. I need common way to be able to query all types of models via base Resource model and get typed results. For example: result_qs = Resource.objects.filter(attr1=val) #-> [Resource, Switch, Resource, ...] result_qs = Switch.objects.filter(attr1=val) #-> only Switch here [Switch, Switch, Switch, ...] My current solution. I have Resource model and ResourceOption model, linked via foreign key. Inheritance done using django Proxy models and custom manager (ResourcesWithOptionsManager). class Resource(MPTTModel): """ Generic resource representation. Support for search by ResourceOptions. """ parent = TreeForeignKey("self", blank=True, db_index=True, null=True, related_name='children') content_type = models.ForeignKey(ContentType) name = models.CharField(default='resource', db_index=True, max_length=155) status = models.CharField(max_length=25, db_index=True, .... objects = ResourcesWithOptionsManager() class ResourceOption(models.Model): """ Resource options. Resources is able to have different options and client can search by them. """ resource = models.ForeignKey(Resource) name = models.CharField(max_length=155, db_index=True) value = models.TextField('Option value') journaling = models.BooleanField(default=True) ... # Proxy model example class SwitchResource(Resource): """ Physical switch resource. """ class Meta: proxy = True @property def label(self): return self.get_option_value('label', default="no label") @label.setter def label(self, value): assert value is not … -
Reverse for 'url_name' with arguments '()' and keyword arguments '{}' not found
I'm getting this error after redirecting on a form submit and I don't understand why it happens, I know that posts about this subject aren't missing but after reading dozens of them I'm still not able to fix this issue. Reverse for 'url_name' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['room/(?P\d+)/(?P[-\w\d]+)/$'] Here is what my code looks like : views.py if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): save_it = form.save(commit=False) ... save_it.save() return redirect(reverse('commenting_room_detail')) urls.py url(r'^room/(?P<gig>\d+)/(?P<name>[-\w\d]+)/$', views.commenting_room, name='commenting_room_detail'), template/room.html <form method="POST" action="{% url 'commenting_room_detail' room.gig.id request.user %}">...</form> If someone could explain to me why this error is appearing on this specific code It would help me avoid this common error for the next times, because everything seems correct, thanks. -
How to fix "plural forms could be dangerous" django error?
I don't get it. If I set it to any other language (de, pl, es) or even something that doesn't exist (like xxs), the app doesn't spit out this error. Here's the stack trace: Traceback (most recent call last): File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\core\han dlers\exception.py", line 39, in inner response = get_response(request) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\core\han dlers\base.py", line 244, in _legacy_get_response response = middleware_method(request) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\middlewa re\locale.py", line 29, in process_request translation.activate(language) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr anslation\__init__.py", line 161, in activate return _trans.activate(language) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr anslation\trans_real.py", line 238, in activate _active.value = translation(language) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr anslation\trans_real.py", line 227, in translation _translations[language] = DjangoTranslation(language) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr anslation\trans_real.py", line 129, in __init__ self._add_installed_apps_translations() File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr anslation\trans_real.py", line 176, in _add_installed_apps_translations translation = self._new_gnu_trans(localedir) File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr anslation\trans_real.py", line 156, in _new_gnu_trans fallback=use_null_fallback) File "C:\Python35\lib\gettext.py", line 426, in translation t = _translations.setdefault(key, class_(fp)) File "C:\Python35\lib\gettext.py", line 162, in __init__ self._parse(fp) File "C:\Python35\lib\gettext.py", line 297, in _parse self.plural = c2py(plural) File "C:\Python35\lib\gettext.py", line 76, in c2py raise ValueError('plural forms expression could be dangerous') ValueError: plural forms expression could be dangerous I have plural-forms set up correctly in my django.po file: "Plural-Forms: nplurals=2; plural=(n != 1);\n" Why does this happen and how to fix it? -
Django How to Store HTML files in Amazon S3
I have a question regarding HTML files and Django. Can the django views file serve html files that are not stored locally and stored on amazon s3? For example instead of: def index(request): return render(request, 'index.html') have something like: def index(request): return render(request, 'http://bucket.s3.amazonaws.com/file.html') Obviously its currently appending the url link to the folder it things html are served from. Is this sort of thing even possible? Thanks