Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my Foreign keys are not working they should be?
I am trying to write some queries which fetch average and count of ratings which are in my ConsumerServicerequestFeedback class Model. These rating should be based on some parameters such as BrandName, ProductName, ServiceCentre Names and Cities. I joined each of these models by Foreign keys but they aren't working they should be. Models.py from __future__ import unicode_literals from django.db import models class Brand(models.Model): bbrandid = models.BigAutoField(db_column='BrandID', primary_key=True) # Field name made lowercase. bbrandname = models.CharField(db_column='BrandName', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'brand' def __str__(self): return self.bbrandname class ConsumerProduct(models.Model): cpconsumerproductid = models.BigAutoField(db_column='ConsumerProductID', primary_key=True) # Field name made lowercase. cpconsumerid = models.BigIntegerField(db_column='ConsumerID', blank=True, null=True) # Field name made lowercase. cpbrandid = models.ForeignKey(Brand, on_delete=models.CASCADE, db_column='BrandID', related_name='cpbrand') # Field name made lowercase. cpproductid = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='ProductID', related_name='cpproduct') # Field name made lowercase. class Meta: managed = False db_table = 'consumer_product' def __str__(self): return str(self.cpconsumerproductid) class ConsumerServicerequest(models.Model): csrconsumerservicerequestid = models.BigAutoField(db_column='ConsumerServiceRequestID', primary_key=True) # Field name made lowercase. csrsource = models.CharField(db_column='Source', max_length=50, blank=True, null=True) # Field name made lowercase. csrconsumerid = models.BigIntegerField(db_column='ConsumerID', blank=True, null=True) # Field name made lowercase. csrconsumerproductid = models.ForeignKey(ConsumerProduct, on_delete=models.CASCADE, db_column='ConsumerProductID', related_name='csrconsumerproduct') # Field name made lowercase. csrsoldplanid = models.BigIntegerField(db_column='SoldPlanID') # Field name … -
django page_attribute in view.py
Hi i need get slug and others parameters of Django Page: In the template the matter is simple: {% page_attribute "slug" %} But I need get this value from the view.py How can I do it. Thank you for help. My views.py from django.shortcuts import render from django.shortcuts import render,render_to_response from django.template import RequestContext def index(request): return render_to_response('template.html', locals(), context_instance=RequestContext(request)) -
Installing python-ldap and django-auth-ldap on windows 10
Hi there I am trying to pip install python-ldap module and django-auth-ldap modules using pip I am using python version 2.7.12 I keep getting the following error: ...... \python-ldap\modules\errors.h(7) : fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\\Users\\donallane\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 Previously I was getting errors saying that I needed C++ Compiler for Python so installed that I did not get that error .. However, now I am getting the one above. Any suggestions on how to get around this would be great -
Django: Add queryset to inlineformsets
I want to make a queryset on a field in an inline formset.. I have Inovice and Product models and InvoiceDetails model to link the manytomany relation between them. here are the models: class Invoices(models.Model): """The Invoice Creation Class.""" invoice_number = models.CharField( _('invoice_number'), max_length=100, unique=True, null=True) .... class Products(models.Model): """Product Creation Class.""" company = models.ForeignKey(Company, default=1) barcode = models.CharField(_('barcode'), max_length=200, null=True) .... class InvoiceDetail(models.Model): invoice = models.ForeignKey(Invoices, related_name='parent_invoice') product = models.ForeignKey(Products, related_name='parent_product') quantity_sold = models.IntegerField(_('quantity_sold')) ... when crearting an invoice i have inline formsets for the products which create an invoice details for every product.. now i want to filter the products that appear for the user to choose from them by the company. i searched a lot on how to override the queryset of inline formsets but found nothing useful for my case. my forms: class InvoiceForm(forms.ModelForm): class Meta: model = Invoices fields = ('customer', 'invoice_due_date', 'discount', 'type') def __init__(self, *args, **kwargs): self.agent = kwargs.pop('agent') super(InvoiceForm, self).__init__(*args, **kwargs) def clean_customer(self): ..... def clean(self): ...... class BaseDetailFormSet(forms.BaseInlineFormSet): def clean(self): ...... DetailFormset = inlineformset_factory(Invoices, InvoiceDetail, fields=('product', 'quantity_sold'), widgets= {'product': forms.Select( attrs={ 'class': 'search', 'data-live-search': 'true' })}, formset=BaseDetailFormSet, extra=1) and use it in the views like that: if request.method == 'POST': invoice_form … -
Avoiding redundant write operations with Django ORM
I have a periodically running task that performs a lot of write calls to the database on existing data. In most cases, records that are written don't contain a change, so the update queries are redundant. The redundant write calls do put an unnecessarily high load on our database replication, though. This is roughly the algorithm: Fetch existing row from database Potentially modify a lot of fields based on parameters that were passed to the algorithm Save the updated row to database using instance.save() Since it's easier to scale our task processors than our database replication, I thought I'd shift some of the processing load towards code by doing this: if original_instance != possibly_updated_instance: possibly_updated_instance.save() Thing is: Django ORM's equality operator only seems to compare primary keys, so we'd incorrectly be dropping changes. Is there a better way to handle this? -
Post_save doesn't triggers when instance is changed and saved in Django admin site
My goal is to trigger some function, when object is changed via Django admin site. Here is my code: @receiver(post_save, sender=Business) def segment_biz_promoted_change(sender, **kwargs): from lib.segment_analytics import get_segment_api instance = kwargs.get('instance') if not instance: return dirty_fields = instance.get_dirty_fields() if dirty_fields.get('promoted'): segment_api = get_segment_api(instance) segment_api.merchant_promoted() This post_save works perfectly when I change Business object manually in my code with .save(), but it doesn't trigger when I change it via django admin site. Should I use something else then post_save? -
django how to automate functions inside views.py file
Well, this question will surely make the delights of the downvotes brigade and may be tagged as" too broad etc", but it is not!, but precisely because it requires "general" knowledge of how things work, I cannot find an answer in the books I have to ask it. Having my Django application, yes, I can make it interactive by means of the MVC flow. The issue that I have is when I have methods that are not in connection with an html page (that the user sees) but are methods that are supposed to be running constantly in the background. For example, just to illustrate, imagine a code snippet that queries a DB and sends an email with news every 2 hours. It is just not doing anything because I dont know how to "wake that code snippet up". I dont have that problem if I am writing a desktop application in just python without Django. If I right click and say, run this file, the code will running in the background alright. Yes, naturally I have heard of cron jobs etc, but so far I see that you can cron-tab a file but how do I crontab a method … -
Overriding render of RadioSelect in django forms gives unexpected results
I want to override the render for RadioSelect in django. (I have done a similar thing for checkboxes and I want both to look the same). The general workflow for this would be to write a custom renderer, and then change the render in the ChoiceInput, BUT when I copy the existing code and run it the html output is not safe and the escaped html string is shown. This is not making any sense as I didn't do any changes to the class yet, other than change the name: In my widgets.py: class ButtonRadioFieldRenderer(ChoiceFieldRenderer): choice_input_class = OtherRadioChoiceInput class OtherRadioChoiceInput(OtherChoiceInput): input_type = 'radio' def __init__(self, *args, **kwargs): super(OtherRadioChoiceInput, self).__init__(*args, **kwargs) self.value = force_text(self.value) @html_safe @python_2_unicode_compatible class OtherChoiceInput(SubWidget): """ An object used by ChoiceFieldRenderer that represents a single <input type='$input_type'>. """ input_type = None # Subclasses must define this def __init__(self, name, value, attrs, choice, index): self.name = name self.value = value self.attrs = attrs self.choice_value = force_text(choice[0]) self.choice_label = force_text(choice[1]) self.index = index if 'id' in self.attrs: self.attrs['id'] += "_%d" % self.index def __str__(self): return self.render() def render(self, name=None, value=None, attrs=None, choices=()): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else … -
How to know if a model form is among the submitted forms in Django
I have a situation where I make don't at all show a form when the settings.py specifies it. Now I need to handle this form being submitted with along with some other forms and not being there in the template at all. I wrote the logic as it is and did not get any errors at all even though I called myForm.is_valid() and myForm.save() But I'm afraid that this may lead to problems. This is the code in my template <form method="post" accept-charset="utf-8">{% csrf_token %} {{ threadForm|crispy }} {{ postForm|crispy }} {% if SHOW_WIKI %} {{ wikiFrom|crispy }} {% endif %} <input type="submit" class="btn btn-primary btn-sm" value="Submit"/> </form> This is my View for the form @login_required def createThread(request, topic_title=None): if topic_title: try: if request.method == 'POST': topic = Topic.getTopic(topic_title) threadForm = ThreadSUForm(request.POST, prefix='thread') postForm = PostForm(request.POST, prefix='post') show_wiki = getattr(settings, "REFORUMIT_ALLOW_WIKI_FOR_THREADS", False) and topic.is_wiki_allowed wikiForm = WikiCreateForm(request.POST, prefix='wiki') if threadForm.is_valid() and postForm.is_valid() and wikiForm.is_valid(): thread = threadForm.save(commit=False) post = postForm.save(commit=False) wiki = wikiForm.save(commit=False) thread.op = post thread.wiki_revision = None post.setMeta(request) wiki.setMeta(request) if is_authenticated(request): post.created_by = request.user wiki.author = request.user thread.save() wiki.wiki_for = thread wiki.save() post.save() thread.wiki_revision = wiki thread.save() return HttpResponseRedirect(thread.get_absolute_url) else: topic = Topic.getTopic(topic_title) threadForm = ThreadSUForm(prefix='thread', initial={"topic": topic}) … -
authenticate django built in user using custom field
I have model that has one to one relation with django's built in User model. Due to some reason i have added a custom field in my model with name "password_crypt" that supports "pbkdf2_sha512" which is longer than django's built-in field that is i guess 128. So i want to authenticate my user using my custom field but want the rest of the things to work in the same way django's built-in User provides. Token etc How can i authenticate model Object that has one to one relation with django built-in User using custom field "password_crypt" in new model. I am using python 2.7, django 1.10 -
Django / postgresql 'column "type_id" cannot be cast automatically to type integer'
I have an Django app that is working locally, but when I try to deploy it to production it fails with the following error: django.db.utils.ProgrammingError: column "type_id" cannot be cast automatically to type integer HINT: You might need to specify "USING type_id::integer". The main difference between my local setup and production is that I am using SQLite3 and production is using postgres The migration it fails on is migration 10, which looks like this. class Migration(migrations.Migration): dependencies = [ ('speakers', '0009_auto_20180117_1335'), ] operations = [ migrations.AlterField( model_name='speaker', name='type', field=models.ForeignKey(to='speakers.Type'), ), ] The preceding migration, its dependency and the last working migration look like this: class Migration(migrations.Migration): dependencies = [ ('speakers', '0008_auto_20180117_1309'), ] operations = [ migrations.CreateModel( name='Type', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ], options={ 'verbose_name': 'Type', 'verbose_name_plural': 'Types', }, ), migrations.RenameField( model_name='speaker', old_name='speaker_categories', new_name='type', ), ] To make things I'll also include the models (as they look at the end) class Type(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Meta: verbose_name = _("Type") verbose_name_plural = _("Types") class Speaker(models.Model): VIDEO_SRC_TYPES = ( ('yt', 'Youtube'), ('vm', 'Vimeo'), ) status = models.CharField( max_length=40, choices=STATUSES, verbose_name=_("Status"), default=DEFAULT_STATE) type = models.ManyToManyField(Type) (most fields from the 'Speaker' model have been removed to … -
Django REST: Passing extra fields from connected models
I need to add additional fields that are not part of my model to the json response. Is this possible? The models are connected using multiple tables, but do not have a direct connection. models.py class Message(models.Model): body = models.TextField(max_length=500, blank=False) sender = models.ForeignKey(User) timestamp = models.DateTimeField(auto_now_add=True) conversation = models.ForeignKey(Conversation) serializers.py class MessageSerializer(serializers.ModelSerializer): conversation = serializers.ReadOnlyField(source='conversation.id') sender = serializers.ReadOnlyField(source='sender.id') # task = TaskSerializer(source='conversation__task_worker__task.id') # This commented code above is not working, but this is what I need. class Meta: model = Message fields = '__all__' So what I need, is to pass the value of task, which can be found by going back a few tables. E.g. if the current model is Message, I need to: Message -> Conversation -> Task_worker -> Task (Get this) My current json response is: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "conversation": 1, "sender": 2, "body": "Hello There", "timestamp": "2018-01-31T17:48:19.680113Z" }, { "id": 3, "conversation": 1, "sender": 2, "body": "Can you do the task", "timestamp": "2018-02-01T09:39:24.797218Z" } ] } Ideally, I would like the following response: { "count": 2, "next": null, "previous": null, "conversation": 1, "task": 5, "any_extra_fields_key": 'value', "results": [ { "id": 1, "sender": 2, "body": "Hello There", … -
Django: Context processors for error pages (or request in simple_tag)
In my Django project, there are several django apps. I want to write custom error pages, and I want them to contain correct links to the application that the errors happened in, for example, if a 500-error happened in my app a, I want the error page contain a link to /a/index.html, and if a server error happened in app b, I want the page to contain the link to /b/index.html. And I want to create only one copy of each of the error page files, which means I need to get the name of the app from within the template. To that end, I have written a custom context processor that adds the app_name var to the templates. I tested it on my normal pages, but when I went on to test it on the error pages, turns out that the context processor isn't firing. Similarly, I have written a template tag app_aware_url which takes the name of the url pattern and tries to resolve it, but again, turns out that for the error pages the simple_tag(takes_context=True) receives a context that does not contain the request (which is needed for telling which app I am in). Is there a … -
Python-social-auth: do not reassociate existing users
I'm using python-social-auth to allow users to login via SAML; everything's working correctly, except for the fact that if a logged-in user opens the SAML login page and logs in again as a different user, they'll get an association with both of the SAML users, rather than switch login. I understand the purpose behind this (since it's what you can normally do to associate the user with different auth services) but in this case I need to enforce a single association (ie. if you're logged in with a given SAML IdP, you cannot add another association for the same user with the same provider). Is there any python-social-auth solution for this, or should I cobble together something (for instance, preventing logged-in users from accessing the login page)? -
django queryset: how to get items after a particular id in the queryset
I have a list of posts with id: I want to sort all the posts based on publish_date and get all the posts after an id. The following gives me queryset of all posts ordered in publish_date articles = Article.objects.all().order_by('-publish_date') After this how to get queryset with posts after a given id of post -
django api call from api saving into 2 different tables
So i have a function that do an API call from another django project and save the output into its own database. Table Django project 1 : makeapp Django project 2 : Schedule and BookAppt What i want to do is firstly after successfully make a Post request to makeapp API, it will save into Schedule table. And then save the output of makeapp API + Schedule.scheduleId into BookAppt. Is the way to declare a hard coded title using title = "new title" and then save it using "title": title, correct? model class Appointments (models.Model): patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) clinicId = models.CharField(max_length=10) date = models.DateField() time = models.TimeField() created = models.DateTimeField(auto_now_add=True) ticketNo = models.IntegerField() STATUS_CHOICES = ( ("Booked", "Booked"), ("Done", "Done"), ("Cancelled", "Cancelled"), ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="Booked") class BookAppt(models.Model): clinicId = models.CharField(max_length=20) patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) scheduleId= models.ForeignKey(Schedule, on_delete=models.CASCADE) scheduleTime = models.DateTimeField(blank=True, null=True) ticketNo = models.CharField(max_length=5) status = models.CharField(max_length=20) class Schedule(models.Model): scheduleId = models.AutoField(primary_key=True) userId = models.ForeignKey(MyUser, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=True, null=True) date = models.DateField() startTime = models.TimeField() views @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) … -
Daphne server command not available
I have created a django app using channels, and tested it with python3 manage.py runserver, which, as I understand, runs a Daphne server as part of the command. Now I just want to deploy the app by running a standalone Daphne server with some workers, etc. following the documentation. Problem is, I don't seem to have the daphne command available to me in the terminal. Running daphne my_project.asgi:channel_layer just results in my terminal telling me the daphne command isn't found. (Running Ubuntu 17.10, if it's at all relevant) Daphne was definitely installed when I installed the channels package using pip. When I run pip3 install daphne it says that I have all the relevant packages and the installation is up-to-date. Am I doing something stupid here? Seems like this just works for everyone else. How can I get the daphne command available to me so I can start a server with it? -
Django TypeError: 'int' object is not callable when trying save data in models
I am trying to save no of values that a question takes into my model the function to do so is listed below, and the no_value field in Models is IntegerField with default value of 0. def _no_value(): questions = Question.objects.all() for question in questions: regex = re.compile('(__[_]*)') no_value = (regex.findall(question.question)) if no_value: value = len(no_value) question.no_value(value) question.save() Please tell me how to fix this error. -
django_countries serializer in django rest framework
I am trying to get the django-countries serialized, but my json does not show all the available countries. I read here django_countries in django rest framework on what the possible solution is but im not getting the result back I should, or that I think I should. This is what my Serializer looks like. from django_countries.serializer_fields import CountryField class LocationsSerializer(serializers.ModelSerializer): country = CountryField() class Meta: model = Location fields = ('location_name', 'address', 'city', 'province', 'postal_code', 'country') And this is what my model looks like. from django_countries.fields import CountryField class Location(models.Model): location_name = models.CharField(max_length=100, default="None") address = models.CharField(max_length=100) city = models.CharField(max_length=100) province = models.CharField(max_length=100) postal_code = models.CharField(max_length=100) country = CountryField() def __str__(self): return self.location_name When I view the json only the saved value is shown and not all the available option to iterate over in my angularjs app. Any direction would be appreciated. -
Disappearing variables on the page after validation - django form
I have a problem with the page after validating the form. After pressing the "Send" button, validation appears - information on which field is required. However, there is no data at the top of the page, e.g. {{event.logo}} etc. Below is the code of my view. model.py class EventDetailView(DetailView, CreateView): model = models.Event form_class = forms.ParticipantForm context_object_name = 'event' template_name = 'events/event_detail.html' def get_success_url(self): return reverse('events:list') def get_initial(self): return {'event': self.kwargs['pk']} url (to view): url(r'^/(?P<slug>[-\w]+)/(?P<pk>[\d]+)$', views.EventDetailView.as_view(), name='detail'), template: {% block content %} <div class="content-item compact bg-mid-gray"> <!--start: event content-text--> <div class="event-container content-inner"> <div class="event-item"> <div class="event-item-date large-2 medium-3 small-12 columns"> <div class="event-time"> <span class="event-date">{{ event.date|date:'d' }}</span> <span class="event-period">{{ event.date|date:'M-d' }}</span> <span class="event-time">{{ event.event_from|date:'H:i' }} - {{ event.event_to|date:'H:i' }}</span> </div> {% if event.logo %} <span class="logo-item"> <img src="{{ event.logo.url }}" alt="logo-item"> </span> {% endif %} </div> <div class="event-item-description large-offset-1 large-9 medium-9 small-12 columns"> <h2>{{ event.title }}</h2> <span class="subtitle">{{ event.flag }}</span> <p>{{ event.text }}</p> </div> </div> </div> <!--end: event content-text--> </div> <!--start: Formular and Info-Box--> <div class="content-item event-form-container"> <div class="content-inner"> <div class="form-container large-offset-1 large-6 medium-7 small-12 columns"> <form id="send-form" class="form-default" action="{{ request.path }}" method="post" novalidate>{% csrf_token %} {% form form using "floppyforms/layouts/p_participant.html" %} <input type="submit" value="Send" class="btn btn-default bg-mid-gray" /> </form> </div> … -
How to add a custom form on django admin.py?
I'm trying to make few fields changeable like title, phone no. for my website. I want to change through admin interface. How can I do that? -
Postgres: display database
I'm using the Django Maybe I'm looking for something wrong or there is basically no such thing. But can someone knows the information about whether it is possible to show database dependencies. Like bdSchema app. Django Rest Framework can build api. I thought maybe there's something that can build a schema -
delete session of a specific user in django?
I am trying to delete the session of some specific user in Django.The code seems to run perfectly fine but I believe session is not deleted as the user is still logged in. The code I am using to delete session is:- user = User.objects.get(id=id) for s in Session.objects.all(): if s.get_decoded().get('_auth_user_id') == user.id: s.delete() -
getting a lot of TransactionManagementError in production servers
Lately getting a lot of errors likes this: An error occurred in the current transaction. You can't " TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. the exceptions are not in context of tests (like in other stack overflow questions). these exception comes from many different views and apis together at some point of the day. I'm running Django 1.7.1, Python 2.7, MySql 5.7 (Google Cloud Managed) Could it be related to Django DB Sessions? I see this code in SessionStore.save() (\django\contrib\sessions\backends\db.py) with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using) Could a Session save cause other requests to return TransactionManagementError this is the full stack trace: Traceback (most recent call last): File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view return view_func(*args, **kwargs) File "/opt/webapps/tinytap/tinytap-web/reports/api.py", line 573, in track_album_played albumStore = AlbumStore.objects.only('id').get(id=album_store_id) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 351, in get num = len(clone) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 122, in __len__ self._fetch_all() File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 966, in _fetch_all self._result_cache = list(self.iterator()) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 265, in iterator for row in compiler.results_iter(): File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter for rows in self.execute_sql(MULTI): File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) … -
global name 'DataFile' is not defined
class PageImages(models.Model): page = models.ForeignKey(Pages, on_delete = models.CASCADE) data = models.FileField(blank=True) image = models.CharField(max_length=100) count = models.IntegerField(default = 10) def __str__(self): return self.image def save(self, *args, **kwargs): super(DataFile, self).save(*args, **kwargs) filename = self.data.url I get error while submit form from django-admin. exception global name 'DataFile' is not defined