Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Forms: Grouping fields from a CheckboxSelectMultiple
I am using Django 2.0.1, Python 3.6.4 and Bootstrap 4.0 models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey('self',on_delete=models.CASCADE) class AgeRange(models.Model): age_from = models.PositiveIntegerField() age_to = models.PositiveIntegerField() class Item(models.Model): text = models.TextField() category = models.ForeignKey('Category',on_delete=models.CASCADE) age_range = models.ForeignKey('AgeRange',on_delete=models.CASCADE) class Observation(models.Model): links = models.ManyToManyField('Item') forms.py from django.forms import ModelForm from django.forms.widgets import CheckboxSelectMultiple from .models import Observation class ObservationForm(ModelForm): class Meta: model = Observation fields = ['links'] widgets = {'links': CheckboxSelectMultiple} views.py from django.views.generic import CreateView from .models import Observation from .forms import ObservationForm class ObservationCreateView(CreateView): model = Observation form_class = ObservationForm This is meant to model data in the following structure: Category1 Subcategory1 AgeRange1 Item1 Item2 AgeRange2 Item3 Subcategory2 Subcategory3 AgeRange1 Item4 AgeRange2 Item5 Subcategory4 AgeRange1 Item6 AgeRange2 Item7 Category2 Subcategory3 AgeRange1 Item8 Item9 AgeRange2 Item10 Item11 [...] However, by default the form just displays a checkbox for each Item with the text field used as its label. There are potentially a large number of Item objects in the database and just displaying this list without the context of the grouping above would not be very user friendly. So what I am trying to achieve is a set of nested Bootstrap 4 accordians which replicate the … -
Django: Is it a good idea to track user like this?
Is it OK to save a user's(patient) phone number in session if they are not logged-in? I allow user's to book an appointment where they must also provide a mobile phone number which will be verified through OTP system. I am right now using that number to keep track of the user by storing that in session. Should I use that number to keep track of the user and show the appointments that number has against it? I think, it should allow me have a unique ID to track users. Is there a better way to do it if a user hasn't signed up? Are there any serious drawbacks for the user's data etc with what I am doing right now? -
Filter the queryset in the Serializer
I have a I18nField Model: class I18nField(models.Model): page_name = models.CharField(max_length=32) field_code = models.CharField(max_length=256) lang_type = models.CharField(max_length=32) field_lang = models.CharField(max_length=64) unique_together = ('page_name', 'field_code', 'lang_type', 'field_lang') ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) I have the model's Serializer: class I18nFieldListSerializer(ModelSerializer): page_name = serializers.CharField(write_only=True, allow_null=True, allow_blank=True) lang_type = serializers.CharField(write_only=True, allow_null=True, allow_blank=True) class Meta: model = I18nField fields = "__all__" You see, in the I18nFieldListSerializer, I have two serializer fields:page_name and lang_type, if them have value, I will filter from the queryset. I can query this in ListAPIView such as: def get_qeuryset(self): filters = {'{}__contains'.format(key): value for key, value in self.query_params.items() if value is not None} return I18nField.objects.filter(**filters) But whether I can get the list in the Serializer? -
Where to write Django custom validator
Where exactly I have to write the custom validators in Django folder? Below is the folder where I have my models /home/shrivatsa555/childrenGK/cgkapp/models.py I have to validate the question difficulty level in the range of 1, 2 and 3 only: class Questions(models.Model): Question_Number = models.AutoField(primary_key = True), Question_Text = models.CharField(max_length = 1000), Option1 = models.CharField(max_length=500), Option2 = models.CharField(max_length=500), Option3 = models.CharField(max_length=500), Option4 = models.CharField(max_length=500), Answer = models.CharField(max_length=500), Difficulty_Level = models.IntegerField(validators=[validate_number]) I have written a custom validator in the views.py but its not working. Kindly guide me.