Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django - Changing Model's attribute from "CharField" to "ForeignKey" fails migrations and everything on "unknown column XXX_id"
Say I had the following model: class greatModel(models.Model): attribute = models.CharField(max_length=100) and life was good. But then another dev tells me "hey, I actually have a whole model called attribute in another app HIS_APP on this project! Just make a ForeignKey. Sounds great, so I do: class greatModel(models.Model): attribute = models.ForeignKey('HIS_APP.attribute', on_delete=models.CASCADE) but now EVERYTHING I do with this model including migrations will fail on: django.db.utils.OperationalError: (1054, "Unknown column 'attribute_id' in 'where clause'") Any idea where I might be going wrong? I've tried dropping/remaking the model/table but that was of no use. -
Django and Nginx X-accel-redirect
I have been fumbling around with trying to protect Django's media files with no luck so far! I am simply trying to make it where ONLY admin users can access the media folder. Here is my nginx file. server { listen 80; server_name xxxxxxxxxx; location = /favicon.ico {access_log off; log_not_found off;} location /static/ { alias /home/{site-name}/static_cdn/; } location /media/ { internal; root /home/{site-name}/; } location / { this is setup and working. Didn't include Code though } My Url File urlpatterns = [ url(r'^media/', views.protectedMedia, name="protect_media"), ] And my view def protectedMedia(request): if request.user.is_staff: response = HttpResponse() response['Content-Type'] = '' response['X-Accel-Redirect'] = request.path return response else: return HttpResponse(status=400) This is producing a 404 Not Found nginx error. Does anything look blatantly wrong here? Thanks! BTW, I have tried adding /media/ to the end of the root url in the nginx settings. -
Django when I try to migrate migrations to posgresql it throws a exceptions psycopg2.ProgrammingError
I migrated to sqlite3 to postgresql database and i tried to migrate but it will always throw a exception I am also using drf. -
Django form not rendering in HTML
I have a form that isn't rendering and I can't figure out why. The only thing showing is submit button. I created the form having followed the methodology described here, here and here. I looked at solutions for the problem (listed below amongst others) but they havent helped. django-forms not rendering errors django form not rendering in template. Input fields doesn't shows up Django Form not rendering Django Form not rendering - following documentation The html is app_core/index.html which extends another- landing_page/base.html The html: {% extends 'landing_page/base.html' %} {% load i18n %} {% load staticfiles %} {% load static %} {% load bootstrap %} <div id="contactus" class="container-fluid"> <br> <div class="container text-center"> <div class="row"> <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2 text-left"> <center><h3>{% trans 'Contact Us' %}</h3> <p>{% trans 'We are at your disposal 365 days 24 hours a day. When you think of languages think of Milingual. Languages are not studied, they are lived!' %}</p></center> </div> </div> <div class ="row"> <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2 text-left"> <center><h1>Contact Us</h1><center> <form id="contactus-form" action="{% url 'contact' %}"method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <br/> <div class="form-actions"> <button type="submit" class="btn btn-primary pull-center">Send</button> </div> </form> <div> </div> </div> The Views.py … -
several inputs same name django form
I have a template that renders values through while a list. First of all, in the context of view i pass a hotel value that is filtered from a model of hotels. Second a loop iterates all the rooms that has this hotel. Each room has several forms. the customer would be select the qty of room desidred. These forms depends on the type of rate/policy. I made this forms directly in the template because i need that the inputs hidden of the form take a value renderized in the loop. like in the example: <form> <input type="hidden" name="hotel" value="{{ hotel.id }}" > <input type="hidden" name="room" value="{{ room.id }}" > <input type="hidden" name="policy" value="1" > <input type="hidden" name="rate" value="{{ r.tarifa }}" > <select name="qty" class="qty"> <option value="">Select...</option> <option value="1">1</option> <option value="2">2</option> </select> <input type="hidden" name="hotel" value="{{ hotel.id }}" > <input type="hidden" name="room" value="{{ room.id }}" > <input type="hidden" name="policy" value="1" > <input type="hidden" name="rate" value="{{ r.tarifa }}" > <select name="qty" class="qty"> <option value="">Select...</option> <option value="1">1</option> <option value="2">2</option> </select> <input type="submit" value="Send"> The problem is: The client can select for example two rooms of 10% discount, and other two of 15% discount. I need to send the data of post, and … -
"ImportError: Couldn't import Django" using heroku, but not while running locally
I'm running into a weird issue when trying to deploy my Django project using Heroku. I meticulously followed all of the steps, which can be found here: https://devcenter.heroku.com/articles/deploying-python#django-applications-on-heroku Right now, I'm at the last step of migrating my database. To do this, I run heroku run python manage.py migrate Which results in the exception error "Couldn't import Django" However, when I run python manage.py migrate everything works fine. I have absolutely no idea why Django is not importing using Heroku, and haven't resolved the issue after a few hours of troubleshooting. Here is the repo with my code: https://github.com/tonypedraza/luispedraza/tree/master/luispedraza Please let me know if I can give any more information. Thank you!!!! -
Push failed heroku
I need some help to solve this. I have others websites in another heroku account, but I 'm not getting in my empty account. I am using python3.5.0 (but I tried change python version without sucess) and Django 1.10. I have in my git repositore, runtime.txt, procfile.txt, but I'm having this problem: (terminal) Counting objects: 105, done. Delta compression using up to 4 threads. Compressing objects: 100% (97/97), done. Writing objects: 100% (105/105), 2.22 MiB | 113.00 KiB/s, done. Total 105 (delta 34), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.5.0 remote: ! Requested runtime (python-3.5.0) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to confiam2. remote: To https://git.heroku.com/confiam2.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/ How can I solve this? I tried to update heroku version, and change python version. Without sucess. Very thanks who can help me. -
Wkhtmltopdf (pdfkit) - QXcbConnection: Could not connect to display
I'm working on a Django project where we generate PDF files from HTML template. I use django-pdfkit to render PDF. On my Ubuntu 16.04 everything works correctly but when I deploy the project on DigitalOcean Ubuntu 16.04 server, it raises error: IOError at /render/doklad/ wkhtmltopdf exited with non-zero code -6. error: QXcbConnection: Could not connect to display I tried to install sudo apt-get install libxrender1 fontconfig xvfb Set WKHTMLTOPDF_BIN variable to correct path. Changed gunicorn user to root. pip install wkhtmltopdf Nothing helped, do you know what I can do to solve this? -
Vue js removing node when it shouldn't
I have a django project where text is annotated. Once the text is highlighted it should bring up a create button in order to actually create the annotations. The highlighting is done using js rects. This all works fine except when you select the first character of the entire body of text, then the button doesn't show up or is removed. You could highlight the first character or an entire sentence and as long as the first character is selected then the create button is either removed or doesn't show. I'm using vue.js to manipulate the buttons. From the debugging that I have done, it is being done in the vue.js source code but I am having a hard time figuring out whats triggering the node removal. Any ideas as to what could be causing this? Any ideas are greatly appreciated -
Conditionnal required one or another field with django-bootstrap
I have two Models linked using a ForeignKey (A requires a ref to B) and I am creating a form to add an element A. I already have a version with a listing of B elements using ModelChoiceField with some custom Select2 widget and I want to add the possibility to create a B element on the same page if the desired B does not exists yet. My question is: How do I validate on the client side that the user either filled the creation form or selected an existing B? <form method="post" autocomplete="off" class="form-contact"> {% csrf_token %} {% bootstrap_field add_form.B addon_after='<a id="show-add-B" class="btn btn-default bg-green"><i class="fa fa-plus white"></i></a>' addon_after_class='input-group-btn' %} <div class='hidden' id='addB'> {% bootstrap_field add_B_form.field1 %} etc… </div> <div class="col-md-12 text-center"> {% bootstrap_button btn_text button_type="submit" button_class="btn-primary" size="large" %} </div> <script type="text/javascript"> $("#show-add-B").on("click", function(event) { $("#addB").removeClass("hidden");}); </script> </form> The validation on the python side is quite clear for me (thanks to SO), but I want the javascript to validate this select/create required. For now I tried: setting both creation & selection required (on the python form declaration) which obviously fail :) deactivate required (python side again) which allow me to use the form but does not validate that the … -
Django filter queryset in reverse relation
Code I'm working with: class Message(models.Model): from_who = models.ForeignKey(User, related_name='sent') to = models.ForeignKey(User, related_name='recieved') text = models.CharField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) new = models.BooleanField(default=True) Can I display in template User.recieved messages when new is True when I'm using request.user not context? If yes, how? -
How can I access a specific field of a queryset in Django?
I have these models in my Django app: class Book(models.Model): title = models.CharField(max_length=50, unique=True) owner = models.CharField(max_length=30) price = models.DecimalField(max_digits=5, decimal_places=2, null=True) book_rating = models.ForeignKey('Rating', null=True) RATE_CHOICES = zip(range(1,6), range(1,6)) class Rating(models.Model): user = models.ForeignKey(User) this_book = models.ForeignKey(Book) rate = models.DecimalField(max_digits=2, decimal_places=1, choices=RATE_CHOICES) comment = models.TextField(max_length=4000, null=True) I am trying to access the Ratings of each instance of the Book model. Here is what I've tried so far in the shell: from django.contrib.contenttypes.models import ContentType >>> ctype = ContentType.objects.get_for_model(Rating) >>> ctype <ContentType: rating> >>> book_titles = ctype.model_class().objects.filter(this_book__title='My Test Book') >>> book_titles <QuerySet [<Rating: My Test Book - parrot987 - 3.0>, <Rating: My Test Book - 123@gmail.com - 5.0>]> How can I access the two rating values of each object (5.0 and 3.0) without all of this other data? Can this be done in such a way that I am able to average the numbers and return the final value? Thanks for your help! <3 -
Django unique field on a subclass level?
Let's say I have a base class Document that sublcasses into other document types. Currently every instance of Document subclasses has a unique name, meaning that a Receipt instance with the name of 'foobar' cannot exist if a Statement instance has that same name. class Document(models.Model): name = models.CharField(max_length=255, unique=True) date = models.DateField(default=None) place = models.CharField(max_length=255) project = models.ForeignKey('Project', on_delete=models.CASCADE) class Receipt(Document): currency = models.CharField(max_length=255) amount = models.DecimalField(max_digits=5, decimal_places=2) class Statement(Document): description = models.TextField() How can I set up my models so that name is unique on subclass level, in other words, where I can have both a Statement and a Receipt with the name of 'foobar', but not two Receipts or Statements with the same name. -
django form input hidden that take a value renderized in template
I have this django form: class Reserva(forms.Form): hotel = forms.IntegerField(widget=forms.HiddenInput()) room = forms.IntegerField(widget=forms.HiddenInput()) This two input hidden, have to take a value renderized in the template. The value is inside a loop. Any idea? Thanks -
How i can save into the data base a URL parameter with Django
I am trying to saving the URL parameter when someone has filled a form in my landing page. I want to save that parameter with the data that was in the form. How can i do that?? -
Possible more efficient alternative?
Is is possible to make this function more efficient and possibly more readable? In addition, Am I doing this right? I mean, it works, but would it be better to do a complex query (with annotations) or a simple query and then process the result with a "pure python" code-block? Here is the snippet: def save_model(self, request, obj, form, change): #Creates a list of dictionaries with the group name and role name roles = [{'group': group.name, 'role': role.name} for group in form.cleaned_data['groups'] for role in group.groupextended.role.all()] roles = sorted(roles, key=lambda k: k['role']) #Groups by the role name for role, group in itertools.groupby(roles, key=lambda k: k['role']): group_list = list(group) #Check if the role is in more of one group associated to the user if len(group_list) > 1: raise Exception('Exception test: {0}, {1}, {2}'.format(role, obj.username, group_list)) super(UserExtendedAdmin, self).save_model(request, obj, form, change) Thanks -
How to add standard Django models to fixtures output?
I try to test extended version of Django flatpages and need to create fixture for it. It's incredibly straightforward to create one for a custom model. For example, to create a fixture for a auth.User model, I should execute the following command in terminal: $ python manage.py dumpdata auth.User > /path/to/fixture.json How can I do the same thing for the django.flatpages module? (see the explanation below) I extended the django.contrib.flatpages.models.FlatPage model as follows: from django.db import models from django.contrib.flatpages.models import FlatPage class FooProject(models.Model): pass class FooFlatPage(FlatPage): project = models.ForeignKey(FooProject) The code above will create 4 tables in a database when I execute the migrate command (1 for FooProject, 1 for FooFlatPage and 2 for Django Flatpages). Now when I try to execute dumpdata for my module: $ python manage.py dumpdata my_module > /path/to/fixture.json ...I'll get dump of only 2 tables (except flatpages tables). The fixture.json file: [ { "model": "my_module.fooproject", "pk": 1 }, { "model": "my_module.fooflatpage", "pk": 1, "fields": { "project": 1 } } ] Question: How I can create a data dump for all (4) tables? When I try to add --verbosity argument: Error! Invalid flagged argument --verbosity=3. -
Django css static not load
I have read some similar question, but I can't solve my problem. The path of static directory is right. Static CSS Not Load. Why?? base.html {% load static %} .... <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> .... admin.py INSTALLED_APPS = [ .... django.contrib.staticfiles .... ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' I have tried to change the pat of the folder. I have also tried with DEBUG set on True and False. -
Django Ajax request not updating filefield with audio blob
I've got a bit of Ajax that takes a wav/audio blob that's assigned to an instance of FormData and should update the "sound" FileField in a form named 'UpdateAudio' through the view 'update_audio'. Here's the url for the view: url(r'^update_audio/(?P<pk>[\w-]+)$', views.update_audio, name='update_audio'), The view: def update_audio(request, pk): if request.method == 'POST': form = UpdateAudio(data= request.POST, files= request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') The form in the template: <form id='update_audio' enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="file" name="sound" id="id_sound" > <input class="btn btn-primary" type="submit" value="Save" /> </form> And finally, the function that calls the Ajax: function upload(event) { event.preventDefault(); var csrftoken = getCookie('csrftoken'); var data = new FormData(); data.set('sound', blob); console.log(data); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) … -
Why do I have a "TypeError: 'Command' object cannot be interpreted as an integer"?
I'm writing a management command to install some test data in a django app. One of my functions is giving me an error: TypeError: 'Command' object cannot be interpreted as an integer Here's the code that's causing it: import string from my_app.models import Customer from random import choice class Command(BaseCommand): def random_string(size=4, chars=string.ascii_lowercase + string.digits + " "): """ Creates a random string of letters and digits """ return ''.join(choice(chars) for _ in range(0, size)) def handle(self, *args, **options): c = Customer(firstname=self.random_string(), foo=bar) If I do pdb.set_trace() at the point where self.random_string() is called, I note that I can't call self.random_string() but doing ''.join(choice(string.ascii_lowercase) for _ in range(0, 4)) works fine. What's going wrong there? Full trace: File "/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/application/utils/management/commands/generate_test_data.py", line 263, in handle firstname=self.random_string(), File "/application/utils/management/commands/generate_test_data.py", line 64, in random_string return ''.join(choice(chars) for _ in range(0, size)) -
login with forms deons't work
so I'm making a login page with forms, the problem is it doesn't work :D this is my form forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: my views.py def user_login(request): if request.method == 'POST': login_form = UserForm(request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') raw_password = login_form.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('restricted') else: login_form = UserForm() return render(request, 'userlogin.html', {'login_form': login_form}) and my html <h2>Login</h2> <form method="post"> {% csrf_token %} {{ login_form.username }} <br> {{ login_form.password }} <br> <button type="submit">Login</button> </form> the restricted is a html that checks which user is logged in. and it works fine i'm not sure why it isn't working cuz it keeps redirecting me to the loginuser.html page instead of redirecting me to restricted page which only appears if a user is logged in. -
Using dynamic object filter
I am trying to access names of all the students having marks 100. def get_names(request): student_stream = Result.objects.filter(marks=100) student_name = [] for x in student_stream: student_name.append(x.student) for x in student_name: print (x.name) return render(request, 'exam/index.html', {'names': student_name}) When I run this view, 'Student has no attribute '__getitem__'' is displayed on the line print(x.name). I read something about dynamic object filter but cannot figure it out in this case. Model structure class Student(models.Model): name = models.CharField(max_length=20) stream = models.CharField(max_length=20) class Result(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) marks = models.IntegerField() -
How to properly throw a ValidationError in Django?
What's the appropriate way to throw a ValidationError exception in a Django form? There seems to be a few different mutually-exclusive ways to throw this exception. If I have a custom clean() method in a form, and the error doesn't refer to any specific field, then I have to throw it like: raise ValidationError({NON_FIELD_ERRORS: ["Something's wrong!"]}) However, if I do this inside a custom clean() method of an InlineFormSet, it breaks Django's validation framework and throws the error: AttributeError: 'ValidationError' object has no attribute 'error_list' If I instead change my code to: raise ValidationError("Something's wrong!") then it works just fine and I see a nice user-friendly red validation error on my web page. However, this syntax fails almost anywhere else, and confusingly throws the error 'ValidationError' object has no attribute 'error_list' if I don't use the raise ValidationError({...}) syntax. Why is this? -
Django Admin Page: Blank View
I've been trying to get Django working completely but I'm having issues with my admin page. It is only a blank view; no login, no title, no error... After setting up, I have run: python manage.py makemigrations python manage.py migrate Here is settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books.apps.BooksConfig', ] Here is urls.py: from django.conf.urls import url, include from django.contrib import admin admin.autodiscover() from books.views import hello, my_homepage_view, current_datetime, hours_ahead urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/$', hello), # url(r'^$', my_homepage_view), url(r'^time/$', current_datetime), url(r'^time/plus/(\d{1,2})/$', hours_ahead) ] Like I said, there is not a 404 or any type of error page when localhost:8000/admin/ is accessed, it is just a blank, white page. Any help would be appreciated! -
Know-how of utilizing trained model for web applications
I have trained my model in keras. And I am trying to deploy this model to my web applications. In such case, how do you guys deploy this model to web applications; like interactive chat applications. I think django is suitable because my model is in python. So what I want to know is that is there any know-how web pages or books of deploying trained model? I do not need to train online via web applications, just deployment.