Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelForm not saving data that is added to request.POST or through form.save(commit=False)
I have django form that submitted to the view that displays it and want to add some data to it before saving it but it seems not be working. models.py: from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User) display_name = models.CharField(max_length=145, blank=True, null=True) bio = models.CharField(max_length=1000, blank=True, null=True) class Module(models.Model): name = models.CharField(max_length=45) semester = models.CharField(max_length=40) prof = models.ForeignKey('Profile', null=True, blank=True) forms.py: class ModuleForm(ModelForm): class Meta: model = Module fields = ['name', 'semester'] views.py: I have tried adding prof to request.POST before passing it to moduleform but it saves every other data submitted from the HTML except prof prof = Profile.objects.get(user=request.user) if request.method == 'POST': mtb = request.POST._mutable request.POST._mutable = True request.POST['prof'] = str(prof.id) request.POST._mutable = mtb moduleform = ModuleForm(request.POST) moduleform.save() I have also tried saving with commit=False but prof is still not getting added. moduleform.save(commit=False) moduleform.prof = prof moduleform.save() -
OpenAM oAuth 2.0 authentication for Django project
I am quite new to OpenAM, so I am having some problem to integrate oAuth authentication with my Django project. Please help. First I tried to authenticate with datastore by adding users in the subjects, and was able to authenticate the user by using REST APIs provided by openam for the same. But what I want to achieve is to authenticate using oAuth 2.0 (which I used in my Django project – reference). So I created a new module instance for oAuth 2 and filled the client id and secret and added authentication endpoint and access_token endpoint to the URL where Django server is hosted (i.e. localhost:8000/o/token/). But this didn’t work as per what I expected. Can anyone please show me the correct way and help me solve the problem. And is this possible to use authentication from my django project (which is protected by OpenAM) Thanks -
How to add additional fields to embedded documents without changing the original model
I want to add extra properties to a document before embedding that into other document, but I don't know how to do that. Here's my code and what I have tried so far: from mongoengine import * from datetime import datetime class User(Document): name = StringField(max_length=80, required=True) created_at = DateTimeField(default=datetime.now(), required=True) updated_at = DateTimeField(default=datetime.now(), required=True) meta = { 'collection': 'users' } def save(self, *args, **kwargs): self.updated_at = datetime.now() return super(User, self).save(*args, **kwargs) class Stream(Document): users = EmbeddedDocumentListField(document_type='User') created_at = DateTimeField(default=datetime.now(), required=True) updated_at = DateTimeField(default=datetime.now(), required=True) meta = { 'collection': 'streams' } def save(self, *args, **kwargs): self.updated_at = datetime.now() return super(Stream, self).save(*args, **kwargs) When I embed the user document to the stream's users EmbeddedDocumentListField, It will be added and look like this { "_id" : ObjectId("57e6123fe8c39b18b1a13431"), "users" : [ { "_id" : ObjectId("57e6123fe8c39b18b1a13432"), "name": "Rohit Khatri", "created_at" : ISODate("2016-09-24T11:12:23.182Z"), "updated_at" : ISODate("2016-09-24T11:12:23.301Z") } ], "created_at" : ISODate("2016-09-24T11:12:23.189Z"), "updated_at" : ISODate("2016-09-24T11:12:23.323Z") } Now I want to embed the User document with additional properties, like roles. Here's what I have tried:- user = User.objects.create(name='Rohit Khatri') user.roles = ['admin','writer'] stream = Stream.objects.create() stream.users.append(user) stream.save() But It doesn't add the roles field, It would be thankful if somebody can help me with this. Thanks -
Django 1.9 - IntegrityError on update
class Configuration(models.Model): configuration_key = models.CharField(max_length=100, unique=True) configuration_value = models.TextField() configuration_description = models.TextField("a brief description of this setting", blank=True) The above is my model. I am able to able to add configurations using the admin. I have not configured any customizations on the admin. It is a very basic admin.site.register(Configuration) When I update an existing configuration with admin, it throws an IntegrityError duplicate key value violates unique constraint "config_configuration_configuration_key_key" DETAIL: Key (configuration_key)=(SAMPLE_CONFIGURATION) already exists. My question: Shouldn't the admin know that an existing configuration is modified and handle this accordingly? Am I missing something? To be clear - SAMPLE_CONFIGURATION - there is only one such row in the table with that configuration_key. I am trying to edit the configuration_value for that row using the admin and it throws the Integrityerror. -
Where to inherit and override UserChangeForm if I want to enable password modification in the Django Admin area?
According to this answer, if I want to enable the ability to change user passwords in the admin area, I need to add/change some code in UserChangeForm. I understand this does not mean change the original UserChangeForm, but rather, I should inherit the class which contains the UserChangeForm method, and override the method. I don't understand where I am supposed to do this. Could someone please give me an example of where/how to override UserChangeForm? Assume I am using a custom user model which inherits AbstractBaseUser. This is the code (from the linked answer above) for modifying passwords which should go in UserChangeForm: password = ReadOnlyPasswordHashField(label= ("Password"), help_text= ("Raw passwords are not stored, so there is no way to see " "this user's password, but you can change the password " "using <a href=\"password/\">this form</a>.")) Note I am assuming this will actually display the correct form which will correctly change the password, but it's possible I'm being naive about that. Thank you. -
How are ModelFields assigned in Django Models?
When we define a model in django we write something like.. class Student(models.Model): name = models.CharField(max_length=64) age = models.IntegerField() ... where, name = models.CharField() implies that name would be an object of models.CharField. When we have to make an object of student we simple do.. my_name = "John Doe" my_age = 18 s = Student.objects.create(name=my_name, age=my_age) where my_name and my_age are string and integer data types respectively, and not an object of models.CharField/models.IntegerField. Although while assigning the values the respective validations are performed (like checking on the max_length for CharField) I'm trying to build similar models for an abstraction of Neo4j over Django but not able to get this workflow. How can I implement this ? Found a similar question but didn't find it helpful enough. -
Issues with installing python-devel in my virtual environment for django application
so I'm having issue downloading some packages into my virtual environment that i set up for my django application. The application is located in my virtual private server's home directory seperate from the var/www. The issue arises when I try to run env/bin/python manage.py runserver. Terminal returns a 'Error loading MySQLdb module: No module named MySQLdb' which I assume is because MySQL-python isn't in my virtual environment (it's in my root server however). When I try to download it by running env/bin/pip install MySQL-python, terminal returns ' error: command 'gcc' failed with exit status 1.' Now theres a issue with gcc which I searched online and tried downloading python-devel. But there's no way to download that into the virtual environment because it's done through yum install which the virtual env cannot access. So how am I able to access the MySQL database in my django app's virtual environment? -
Django: How to save the POST.get of a checkbox as false (0) in a DataBase?
I'm trying to save the value of a checkbox as true or false in a database. I have to use a model for this. If the box is checked the value of '1' is saved. However, if the box is not checked I get the error message: Django Version: 1.9.4 Exception Type: IntegrityError Exception Value: (1048, "Column 'completed' cannot be null") Currently my setup looks like this: In models.py I have: class myClass(models.Model): completed = models.BooleanField(default=False, blank=True) In views.py I have: def create_myClass(request): completed = request.POST.get('completed') toSave = models.myClass(completed=completed) toSave.save() and in the HTML I have: <label class="col-md-5" for="completed"> Completed: </label> <input id="completed" type="checkbox" name="completed"> I've tried to set required = False in the BooleanField as some other posts suggested but then get the error: TypeError: __init__() got an unexpected keyword argument 'required'. I've also tried to set 'completed' to False in views.py like: if request.POST.get('completed', False ): commpleted = False and completed = request.POST.get('completed') if completed == 'null': commpleted = False But neither work (not sure if my syntax is correct?) Any ideas or suggestions are greatly appreciated! -
Django cms add page and to add plugin ,when I Preview draft always show error 'NoneType' object has no attribute 'current_app'
this is my template app.html, I have choose the app_plugin to replace the placeholder app_placeholder_01 in the django cms. {% extends "frame.html" %} {% block base_content %} <div class="app_class"> <div class="ui_head_area app_head"> <span class="head_title">App Management</span> <hr> </div> {% placeholder app_placeholder_01 %} </div> <div class="ui_footer"> <span class="footer_text">iTMS | © Intel Corporation</span> </div> {% endblock %} -
Haystack with Solr's clustering component (carrot2)
I have Solr configured to do carrot2's STC clustering component (Solr 6) and can access results with the requestHandler=/clustering via Solr's web interface. However, we are using Haystack/Django (1.10) to access Solr and I cannot find anything online that indicates support in Haystack for this. Is it possible? If so, how? -
proxy websockets and http to the same (unix) socket
I've made a little nginx conf to proxy trafic to a unix socket listened by a daphne server (server used for django). According to the documentation : If you use Daphne for all traffic, it auto-negotiates between HTTP and WebSocket, so there’s no need to have your WebSockets on a separate port or path So I'd like to proxy both websockets and Http trafic to the same unix socket. Is it possible? How could I do? Here is what I tried thus far : upstream django_ws { server unix:///path/to/ws.sock; } server { listen 8082; server_name 127.0.0.1; charset utf-8; root /path/to/root; set $myroot $document_root; location / { proxy_pass http://django_ws; #proxy_http_version 1.1; #proxy_set_header Upgrade websocket; #proxy_set_header Connection upgrade; } } If I uncomment the lines in the location bloc, the page appears blank. If I don't, the pages appear but the websockets don't seem to work. How could I solve this? Everything works fine with the development server. -
Django tests slows after MacOS Sierra
I'm working on a Django project using Python 3 and Django 1.10 on Mac. Before update I was running 40 tests in 0.441s. Now after MacOS Sierra: Ran 40 tests in 5.487s I did some investigations and found this line to be the problem: response = self.client.post(r('subscriptions:new'), data) If I pass a empty dict instead of data, the tests run faster. Anyone have a clue why this is happening? -
Django form field initial strfrtime value not updating
I have a Django form field, for a time, where I set the initial value to the current time by using the time.strfrtime() function. Using this method, the field is initially populated correctly with the current time when I first load the Django app (by executing python manage.py runserver). However, subsequently if I reload the page, the form field fails to update the current time, instead repeatedly spitting back the time the app was first started. However, if I modify one of my Django files, such as forms.py or views.py, then the current time is correctly refreshed. In forms.py: class EventForm(ModelForm): end_time = forms.TimeField(label="Current time", initial=strftime("%I:%M %p")) In views.py: def index(request): event_form = EventForm() How do I get the end_time field's initial value to always update to the current time? -
missing required Charfield in django is saved as empty string and do not raise an error
If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. It does not seem to be the case. models.py: from django.db import models class Essai(models.Model): ch1 = models.CharField(max_length=100, blank=False) ch2 = models.CharField(max_length=100, blank=False) So I have two fields not allowed to be empty (default behavior, NOT NULL restriction is applied by Django at MySQL table creation). I expect Django to rase an error if one of the fields is not set before storing. However, when I create an incomplete instance, the data is stored just fine: >>> from test.models import Essai >>> bouh = Essai() >>> bouh.ch1 = "some content for ch1" >>> bouh.save() >>> bouh.id 9 >>> bouh.ch1 'some content for ch1' >>> bouh.ch2 '' >>> I would have expected Django to raise an error. If I force ch2 to None, however, it raises an error: >>> bouh = Essai() >>> bouh.ch1 = "some content for ch1" >>> bouh.ch2 = None >>> bouh.save() Traceback (most recent call last): (...) return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: test_essai.ch2 >>> bouh.id >>> bouh.ch1 'some content for ch1' >>> bouh.ch2 >>> Is this normal behavior? Did I miss something? Why is … -
Is there a function in Django to check if user was redirected because he was not logged?
I have to render a div in Django if user was redirected because he had to login before access a page. I know I can do this with JavaScript, but I was looking to do this in a "Django way". Just to clarify: User was in http://example/artist/album/janis-joplin/ Was redirected to login in [I want to show the div here] http://example/account/login/?next=/artist/album/janis-joplin/summertime And then he finally got to his destination http://example/artist/album/janis-joplin/summertime -
Django: Which way is better way to find(search) a equal data object?
I implement searching functions in Django and wonder which one is much better way. <1> def same_cart_item_in_cart(cart, new_cart_item): already_exist_cart_item = cart.cartitem_set.filter( Q(variation__product=new_cart_item.variation.product), Q(variation=new_cart_item.variation), Q(width=new_cart_item.width), Q(height=new_cart_item.height), ).first() return already_exist_cart_item # It can be None <2> Override CartItem's __eq__ first. class CartItem(TimeStampedModel): cart = models.ForeignKey("Cart") variation = models.ForeignKey(Variation) # 벽화 너비 width = models.PositiveIntegerField( default=1, validators=[MinValueValidator(1)], ) # 벽화 높이 height = models.PositiveIntegerField( default=1, validators=[MinValueValidator(1)], ) quantity = models.PositiveIntegerField( default=1, validators=[MinValueValidator(1)], ) class Meta: ordering = ('-created',) def __str__(self): return str(self.variation.product) + ' - ' + str(self.variation) def __eq__(self, other): return ( self.variation.product == other.variation.product and self.variation == other.variation and self.width == other.width and self.height == other.height ) and then, def same_cart_item_in_cart(cart, new_cart_item): for cart_item in cart.cartitem_set.all(): if cart_item == new_cart_item: return cart_item return None Need your advices. Thanks -
Why is my django form validating when I am not calling is_valid
I have a form which actions towards my home view, it contains two buttons, save and cancel. When run on the local dev server (manage.py runserver) this works fine. When I pushed this to production, the cancel button returns form validation errors, despite not calling the is_valid method. Here is the view: def home(request): #uses home.html if request.method == 'POST': #Figure out which button was pressed #Cancel Button - Back to home if request.POST.get("cancel"): #return HttpResponseRedirect(request.META.get('HTTP_REFERER')) footer = request lineitems = Budget.build(request.user) c = {'lineitems': lineitems, 'footer':footer,} return render(request, 'home.html', c) #Save button on config.html IncomeForm/Expenses Form if request.POST.get("config_save"): #ExpensesForm submitted if 'expenseName' in request.POST: form = ExpensesForm(request.POST) if form.is_valid(): form.save() else: temp = 'config.html' footer = 'Expense Form Invalid' c = {'form':form, 'footer':footer,} return render(request, temp, c) #IncomeForm submitted else: form = IncomeForm(request.POST) if form.is_valid(): form.save() else: form = IncomeForm(request.POST) temp = 'config.html' footer = 'Form Invalid' c = {'form':form, 'footer':footer,} return render(request, temp, c) #Use Budget Class to populate a table in template Budget.update_data({'months':12, 'user':request.user}) temp = 'home.html' footer = '* Line Modified' lineitems = Budget.build(request.user) c = {'lineitems': lineitems, 'footer':footer,} return render(request, temp, c) # if a GET (or any other method) we'll load the budget else: … -
Count vs len on a Django QuerySet when some results are filtered
A more general version of my question has already beek asked: Count vs len on a Django QuerySet My case is a bit different, though. It starts with something like this: messages = Message.objects.filter(foo=bar) To get error_message_count and other_message_count, which is better? error_message_count = len(message for message in messages if message.is_error) other_message_count = len(messages) - error_message_count or: error_message_count = messages.filter(is_error = True).count() other_message_count = messages.count() - error_message_count or even: error_message_count = messages.filter(is_error = True).count() other_message_count = messages.filter(is_error = False).count() I suspect that the first solution boils down to only one query, and the others in two. But perhaps Django and/or the DBMS make one of the second two more efficient? I'll accept 'profile it' as an answer, but I wonder if any of these solutions are considered best practice. -
Center bootstrap columns without stacking
I am using bootstrap to create some col-sm-4 elements in Django for every item that is queried for in the backend. The default behavior in bootstrap is to float all elements to the left, but since I don't know how many elements will be queried for in the backend, 1, 2, 3, etc., I am finding it very difficult to find a way to center the columns. for example if I only got two items from my backend query, I would want a 2 column wide gap on each side so the two two elements are perfectly centered but on the same row, or if there is only 1 item, than there will be a 4 column wide gap on each side to center the element. I tried using this a couple other stack overflow questions similar to this one, but in those cases they want all the columns to be centered and stacked on top of each other so there is only one element per row. Is there a simple way to accomplish this ? -
Django: Two projects from landing page
I am planning on a Django multi-project system, where I'll have a Django project hosting the landing page. Then I wish to have two links to two of the separate django projects (maybe that can grow to three in future). Now, I saw the apache config part in SO as well as in google. But I want to know, what should be the link be in the two buttons on the landing page, as in how would the url pattern be? -
Django ModelForm - Performance issue
I am using ModelForm to allow multiple rows edit at the same time. It is a very simple form that has series of yes_no columns. The model looks like: models.py class Yn(models.Model): yn_id = models.IntegerField(primary_key=True) description = models.CharField(max_length=30) def __str__(self): return ' '.join([ self.description, ]) class Meta: managed = False db_table = 'yn' class Invoice(models.Model): description = models.CharField(max_length=50) invoice_date = models.DateTimeField() ... invoice_sent_yn = models.ForeignKey('Yn', models.DO_NOTHING, db_column='invoice_sent_yn', related_name="invoice_sent_yn") confirm_receipt_yn = models.ForeignKey('Yn', models.DO_NOTHING, db_column='confirm_receipt_yn', related_name="confirm_receipt_yn") paid_yn = models.ForeignKey('Yn', models.DO_NOTHING, db_column='paid_yn', related_name="paid_yn") forms.py class InvoiceGridEdit(ModelForm): model = Invoice fields = ['description','invoice_date','invoice_sent_yn', confirm_receipt_yn', 'paid_yn'] def __init__(self, *args, **kwargs): super(JurisGridEditForm, self).__init__(*args, **kwargs) ... ... The forms works fine, get and post works, except, it takes a while (~30 sec) to retrieve and update. Using django-debug-toolbar, it looks like the yn columns retrieve separately for each column for each row (~2k rows). The Yn table only has 3 rows -1 - Unknown, 0 - No, 1 - Yes. I tried to search for work around to stop the craziness of Django hitting the DB 900 times per retrieval. I found something about caching but I have no idea how to do it. Thanks in advance. -
Need to create App to help sort google calendar
So I wanted to build an app that would make my life much easier by connecting to Google Calendar API but I don't know any coding and cannot hire someone. Basically I want to create a site which will pull API data and allow me to make changes within Google Calendar. It would be used to coordinate my calendar with that of colleagues and find the best time for us to have meetings where we all need to be present. Hopefully automatically set up the event within Google Calendar as well. Would this be something done with Python/Django? Can this be done with Javascript? Not sure where to or even how to start. Any direction is much appreciated. I am complete beginner. Thanks! -
Do you and should you rename a custom User model in Django 1.9?
I am creating a new User model for my Django project. I have been many people calling their custom user model, XXXUser and custom user manager, XXXUserManager. I was wondering if there is a reason for this. Can you just create a custom user and still call it User? Does this create conflicts in the code? -
Cannot find django.views.generic . Where is generic. Looked in all folders for the file
I know this is a strange question but I am lost on what to do. i cloned pinry... It is working and up . I am trying to find django.views.generic. I have searched the directory in my text editor, I have looked in django.views. But I cannot see generic (only a folder with the name "generic"). I cant understand where the generic file is . It is used in many imports and to extend classes but I cannot find the file to see the import functions. I have a good understanding of files and imports and i would say at this stage I am just above noob level. So is there something I am missing here. How come i cannot find this file? eg : from django.views.generic import CreateView Where is generic? -
How to refer to abstract model in other modules
I'm trying to alter an app I've created so that it is reusable. It's based around a single model which sites using the app will subclass. As it stands, my non-reusable version has the following kind of structure: # models.py class Document(models.Model): contents = models.TextField() date = models.DateTimeField() # views.py from .models import SiteModel # ... class MyView(ListView): def some_method(self, list_of_pks): model_vals = Document.objects.filter(pk__in = list_of_pks).values() def perform_action(request): obj_pk = request.POST.get('obj_pk') obj = Document.objects.filter(pk = obj_pk) MySignal.send(sender=Document, instance = obj) #etc, etc This works well enough. Based on reading the documentation on abstract base classes, I think I want to change it to something like # models.py for the app class BaseDocument(models.Model): contents = models.TextField() class Meta: abstract = True # models.py for a hypothetical site using the app class SiteDocument(myapp.BaseDocument): date = models.DateTimeField() # other site-specific fields What I don't understand is how to then reference the model in the app's views.py, forms.py, etc. I feel like doing BaseDocument.objects.all(), for example, won't return anything since it doesn't have a table. Conversely, I can't have Document.objects.all() because Document hasn't been created yet and is specific to each site.