Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Two Dimensional Array
Please guide please tell me how i can get a single value out for each of this multi dim array in python well i have tried to print out using for loop. [dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001']), dict_keys(['section_001']), dict_keys(['section_003', 'section_004', 'section_007', 'section_008', 'section_002', 'section_006', 'section_005', 'section_001']), dict_keys(['section_003', 'section_004', 'section_007', 'section_008', 'section_002', 'section_006', 'section_005', 'section_001']), dict_keys(['section_001', 'section_002', 'section_003']), dict_keys(['section_001', 'section_002', 'section_003'])] expect result should be: section_001 section_002 for each array -
How to use range slider with django-filter
How can I use a range slider (for example the jQuery one) with django-filter package? I've tried to use NumericRangeFilter with new field (I don't know how to overwrite the filter class from one specific field). class ProductFilter(django_filters.FilterSet): price = django_filters.NumericRangeFilter() class Meta: model = Product fields = '__all__' exclude = 'price' I wish to know how to use the field in the template to render a range slider and filter the results. I expect too to know how can I change the filter class of just one model field. -
Use data in foreign key model prior to saving in Django admin
I'm prototyping an estimating application. Each Estimate model will have one or more Part models. Here is the beginning of my models: class Part(models.Model): estimate = models.ForeignKey('Estimate', on_delete=models.CASCADE) description = models.CharField(max_length=255) class Estimate(models.Model): number = models.CharField(max_length=255, primary_key=True) customer = models.CharField(max_length=255, null=True, blank=True) description = models.CharField(max_length=255, null=True, blank=True) price = models.IntegerField(null=True, blank=True) stitch = models.BooleanField(null=True, blank=True) stitch_speed = models.IntegerField(null=True, blank=True) stitch_rate = models.IntegerField(null=True, blank=True) boxes = models.IntegerField(null=True, blank=True) freight = models.IntegerField(null=True, blank=True) overall_markup = models.IntegerField(null=True, blank=True) date_created = models.DateField(auto_now_add=True) def __str__(self): return self.number I have the Estimate model appearing in the admin with Part models in a StackedInline. class PartInline(admin.StackedInline): model = Part extra = 1 class EstimateAdmin(admin.ModelAdmin): model = Estimate inlines = [PartInline] list_display = ['number', 'description', 'customer', 'price'] Ideally, I would go into the admin, create a new Estimate, fill out its Parts, and then click Save. Ultimately, my Estimate model will need to use data from the Part model to perform calculations before saving to the database. For example, each Part will contain its own price. The price from each Part will need to be added to the total Estimate price. I'm having trouble figuring out how to send data from the Part model to the Estimate model … -
Is there any way to access the variable inside a function from another function within the same class in TemplateView of django
how to access the variable within a function from another function within the same class in django's TemplateView class add_question_main(TemplateView): template_name = 'add_question_paper/index.html' def get(self,request,*args,**kwargs): form = question_details_form() no_txt = request.GET.get('num') return render(request,self.template_name,{'form':form}) def post(self,request,*args,**kwargs): form = question_details_form(request.POST) return render(request,self.template_name,{'form':form}) I wonder how could I use the value of no_txt in function post? -
Django CreateView - created_by, modified_by mixin not working
I have followed spapas tutorial on CBV's and tried to apply a mixin on a create view. But looks like it doesn't evaluate correctly the if not form.invoice.requester for a user foreign key because it always says: RelatedObjectDoesNotExist and it points to the field evaluated in the if not line. What can be wrong? views.py class AuditableMixin(object, ): def form_valid(self, form, ): if not form.instance.requester: form.instance.requester = self.request.user form.instance.modified_by = self.request.user return super().form_valid(form) class NewOrderView(LoginRequiredMixin, PermissionRequiredMixin, AuditableMixin, generic.CreateView): permission_required = 'orders.add_order' form_class = NewOrderForm model = Order title = 'New Order' extra_context = {'title': title} forms.py class NewOrderForm(forms.ModelForm): class Meta: model = Order widgets = { 'order_details': forms.Textarea, } exclude = ( 'status', 'invoice', 'requester', 'modified_by', ) Thank you. -
Django URLS int returns with trailing slash
I am trying to take a primary key out of a url, e.g. site.com/content/1/ with urls.py like: urlpatterns = [ ... path('content/<int:pk>/', views.ContentView.as_view(), ] But when I access pk it has the / appended and is not an int. Is there a way to have django not pass the trailing slash? -
How to merge local branch with migrations created in docker
In my pet project I set up docker-compose for development. The issue is that I've create django migration inside docker and when I want to checkout to main brain and merge commits from sub branch I got an error: error: The following untracked working tree files would be overwritten by merge: apps/users/migrations/0002_auto_20190127_1652.py -
what is the best way/architecture to trigger celery calcualtion with many account?
I have my django/celery/sqs service ready for a set of calculations with one account. I would like to trigger calculations for many accounts. Currently, I am thinking two ways to do implement this: 1. upload accounts through a csv file, process these accounts and trigger the calculations one by one through rest api. 2. again, upload accounts through a csv file, but directly implement the service inside application, this might be a repeating work since I have the calculation for a single account already. Thanks for any suggestion. -
DRF Serializer sets provided field to None
i'm currently at a project where i want to test the validation of my serializers. I run into the problem that the Serializers set's a provided field to None in the process of validation which does not seem reasonable to me. Here more details (shorted for simplicity): models.py : class Contract(models.Model): start_date = models.DateField() end_date = models.DateField() serializers.py: class ContractSerializer(serializers.ModelSerializer): class Meta: model = Contract fields = "__all__" def validate(self, attrs): """ Object-level validation. Here we validate : start_date is, timewise, prior to end_date :param attrs: :return: """ if not attrs["start_date"] < attrs["end_date"]: raise serializers.ValidationError("Sample Error Message.") return attrs I use pytest for testing and pytest-django. My conftest.py : from pytz import datetime @pytest.fixture def valid_contract_json(): start_date = datetime.date(2019, 1, 1) end_date = datetime.date(2019, 1, 31) data = { "start_date": start_date, "end_date": end_date, } return data My test(s) looks like : test_serializers.py: from app.serializers import ContractSerializer class TestContractSerializer: def test_validation(self, valid_contract_json): ContractSerializer(data=valid_contract_json).is_valid(raise_exception=True) When running this Test it fails and show the following message: TypeError: '<' not supported between instances of 'datetime.date' and 'NoneType' I did some investigation on this: Comment the validate method out. Modify Test to : def test_validation(self, valid_contract_json): pprint.pprint(valid_contract_json) seri = ContractSerializer(data=valid_contract_json).is_valid(raise_exception=True) # Serialization won't throw exception … -
Django Migrate Operation Fails with error "the database system is in recovery mode"
I was migrating an old project, but for some reason the migration always failed at this file, i tried executing just this migration file, still same error. I have attached the command i used, the logs from the python terminal on the command and the logs from the database below. The command used python3 manage.py migrate content 0037_auto_20180618_1711 The Migration file # -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-06-18 17:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('content', '0036_trivia_original_description'), ] operations = [ migrations.AlterField( model_name='trivia', name='is_approved', field=models.CharField(blank=True, max_length=32, null=True), ), ] The logs from the migrate operation > File > "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", > line 65, in execute > return self.cursor.execute(sql, params) psycopg2.OperationalError: server closed the connection unexpectedly > This probably means the server terminated abnormally > before or while processing the request. > > > The above exception was the direct cause of the following exception: > > Traceback (most recent call last): File > "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", > line 244, in apply_migration > state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/migration.py", > line 129, in apply > operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File > "/usr/local/lib/python3.5/dist-packages/django/db/migrations/operations/fields.py", > line 215, in database_forwards > schema_editor.alter_field(from_model, from_field, to_field) … -
optimizing Django REST Viewset with 1k+ queries for a single object
I have a ViewSet with nested serializers which is making over 1000 SQL queries and taking over 15 seconds to load a single object. I feel I must be doing something catastrophically wrong to get such horrendous performance, but I'm having trouble pinning it down. Similar posts recommend select_related() and prefetch_related(), but their use has brought my SQL query count from 1066 to 1062 -- not even a start. ViewSet: class PostViewSet(DetailAndListViewSet, VoteMixin, SaveMixin, MarkdownToHTML): queryset = Post.objects.select_related('posted_in') \ .prefetch_related('comments') \ .select_related('author', 'author__user') \ .filter(is_visible=True) permission_classes = (IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly) authentication_classes = (TokenAuthentication,) serializer_class = PostSerializer detail_serializer_class = PostDetailSerializer lookup_field = 'slug' slug_field = 'slug' class DetailAndListViewSet(viewsets.ModelViewSet): def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super(DetailAndListViewSet, self).get_serializer_class() Serializer: class PostDetailSerializer(serializers.ModelSerializer, GetScoresMixin): author = AccountLimitedInfoSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True) posted_in = SubInPostDetailSerializer() num_comments = serializers.SerializerMethodField() user_upvoted = serializers.SerializerMethodField() user_downvoted = serializers.SerializerMethodField() score = serializers.SerializerMethodField() class Meta: model = Post read_only_fields = ('comments', 'body_html', 'url', 'slug', 'upvoted_by', 'downvoted_by', 'created', 'num_comments', 'score') fields = ('id', 'author', 'title', 'created', 'body_text', 'comments', 'url', 'link_url', 'image_url', 'posted_in', 'score', 'user_upvoted', 'user_downvoted', 'num_comments') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } -
How to instantiate a class one time and access it in views
I have a class that runs once, which I had in myapp/__init__.py, but each time django starts it would run twice. It also runs when I migrate models, when I don't need it to. I've read about the ready function https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready, but cannot access the instantiated class outside of apps.py Here is my current workflow: in init.py: from .my_module import ResourceHeavyClass resource_heavy_instance = ResourceHeavyClass() in my views.py from . import resource_heavy_instance This currently works, but I only want to load the module when the server starts, not when I make migrations. Appreciate any tips/advice. -
How to make composition query based on POST data
I'm stuck, can't find a way to solve this task. I have a simple search form with 4 fields, and can't do composite query based on it. form.py class ViewerForm(forms.Form): text_search = forms.CharField(required=False) birthday_search = forms.DateField(required=False) study_from_search = forms.DateField(required=False) study_to_search = forms.DateField(required=False) I tried to do things like that, but it doesn't work properly. view.py def viewer(request): if request.method == 'POST': form = ViewerForm(request.POST) if form.is_valid: persons_list = Person.objects.all() query = [] if len(request.POST['text_search']): text = request.POST['text_search'] query.append(persons_list.filter(Q(fio__contains=text) | Q(sex__contains=text) | Q(mobile_number__contains=text) | Q(group__contains=text) | Q(edu_organization__contains=text))) if len(request.POST['text_search']): birthday = request.POST['birthday_search'] query.append(persons_list.filter(Q(birthday_date__exact=birthday))) if len(request.POST['study_from_search']): study_from_search = request.POST['study_from_search'] query.append(persons_list.filter(Q(birthday_date__exact=study_from_search))) if len(request.POST['study_to_search']): study_to_search = request.POST['study_to_search'] query.append(persons_list.filter(Q(period_of_study_to__exact=study_to_search))) persons_list.filter(query) How to make query based on POST data, if data in a filed is exist then do some filter. -
How to preserve the order in serializing JSON via MultipleChoiceField
I have a pre-defined list of valid choice: allowed_choices = ['yes', 'no', 'I don't know'] I'm working on an API using the Django rest framework. To validate and serialize the inputs I'm using the Django Fields. For this purpose I have a chosen a MulitpleChoiceField. dataColumns = serializers.MultipleChoiceField( choices=allowed_choices, allow_blank=False, source="data_columns", ) I built afterwards a pandas data frame with the inputs as columns. It is important that they are preserved in the same order. How can I validate using the MulitpleChoiceField and get returned a set with the same order as the input? -
Django celery task that will execute every day from 00:00 to 02:00
I need to set up django celery task my_task that will execute every day from 00:00 to 02:00 with 5 minutes interval in this period. It seems it is unable to set up this task in admin via django-celery-beat. How to set it properly? I need something like celery_app.conf.beat_schedule = { 'my_task_1': { 'task': 'tasks.my_task', 'schedule': crontab(minute=5), 'start': crontab(hour=0, minute=0), 'expires': crontab(hour=2, minute=0), 'args': ("94"), }, } Thank you for your time. -
how to save user gps location in django
I need to track and save user location in my database to delever his order to the location from django.contrib.gis.utils import GeoIP -
Not able to verify SendGrid verification with Django
I'm currently reading a book on Django (for beginners) and I reached the point where I need to implement a password reset feature to the test website using SendGrid SMTP Relay. After creating an account and starting to create the SMTP relay I greeted with the following screen: Based on this page I added the following lines of code to my setting.py file: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = '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' EMAIL_PORT = 587 EMAIL_USE_TLS = True After running the website and trying to reset my password (the password of the superuser) I get the desired message with the reset link in my console but sadly nothing comes to my email. Thus I get the following error message when trying to verify integration. What I tried so far: I tried creating multiple different API keys to make sure nothing was wrong with the API key I created a new SendGrid account I tried removing EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' from the settings.py file (this only made things worst) I've been trying to solve this issue for over a day now, any help would be greatly appreciated! -
How do I write this piece of code in a clean way?
I am just starting out with Django right now and I am trying to display certain div's based on a field that is picked by a user. However this code looks really sloppy and I am repeating myself. I feel like this can be fixed with a loop, but I don't know how. Can someone help me out? <div class="pitch"> <div class="container-field"> <div class="box1"> <div class="pen1"> {% if page.primary_field_position and page.secondary_field_position == 'GK' %} <div class="pos" style="margin: 5px 15px;">1</div> {% endif %} </div> </div> {% if page.primary_field_position and page.secondary_field_position == 'LB' %} <div class="pos" style="margin: 70px 40px">2</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'LCD' %} <div class="pos" style="margin: 70px 116px">6</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'RCD' %} <div class="pos" style="margin: 70px 196px;">3</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'RB' %} <div class="pos" style="margin: 70px 270px">4</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'LM' %} <div class="pos" style="margin: 198px 40px">5</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'DM' %} <div class="pos" style="margin: 140px 153px">6</div> {% endif %} {% if page.primary_field_position and page.secondary_field_position == 'RM' %} <div class="pos" style="margin: 198px 270px">7</div> {% endif %} {% if page.primary_field_position and … -
Django template showing data of all users instead of one user
I am trying to retrieve information regarding a user's profile to display on a page. The issue is it retrieves the relevant information from every user instead of just the one logged in. I have tried requesting for only the user logged in at the time, but I unfortunately could not get it to work. HTML <!-- Bio --> <div> <span class="bold"> <p>Bio:</p> </span> <p> {% for profile in profiles %} {{ profile.bio }} {% endfor %} </p> </div> models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) level = models.CharField(max_length=255, choices=level_list, blank=True) preferred_language = models.CharField(max_length=255, choices=language_list, blank=True) time_zone = models.CharField(max_length=255, choices=time_list, blank=True) def __str__(self): return self.profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py def profile_page(request): form = ProfileForm profiles = Profile.objects.all() args = {'form' : form, 'profiles' : profiles} return render(request, 'student/profile_page.html', args) I am trying to get the profile_page view to display the relevant model information for only one user (the one currently logged in). -
After click button and refresh website all buttons are like selected on django detail view
I have app in django 1.11 and I have problem with voting up or down on comments on detail page of post. For each I would like to check if is voted up or voted down. Now if I click vote up - jquery code - change only this button on voted up, counter of votes also works ok, but after refresh website all vote up buttons of comments are like voted up. Below is my code class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextUploadingField() votes_up = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='up_votes') votes_down = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='down_votes') def __str__(self): return self.text def total_vote_up(self): return self.votes_up.count() def total_vote_down(self): return self.votes_down.count() class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') text = RichTextUploadingField() Below is my detail view with comments objects. class PostDetail(generic.DetailView, FormMixin): context_object_name = 'post' model = Post form_class = CommentForm def get_context_data(self, **kwargs): is_voted_up = False is_voted_down = False comments = self.get_object().comments.all() for comment in comments: if comment.votes_up.filter(id=self.request.user.id).exists(): is_voted_up = True if comment.votes_down.filter(id=self.request.user.id).exists(): is_voted_down = True context = super(PostDetail, self).get_context_data(**kwargs) context['comments'] = self.get_object().comments.all() context['form'] = CommentForm(initial={'post': self.get_object(), 'author': self.get_user()}) context['is_voted_up'] = is_voted_up context['is_voted_down'] = is_voted_down return context -
Keyerror: django BaseModelFormSet clean key error
i have build transiction formset i have want to validate so no double item preset in formset i have use clean for it it but it give error when there is empty form in present in formset.it is modelformset_factory error message is "KeyError at /saleformformset_update/1024 'item " class SaleTransictionFormSet(BaseModelFormSet): def clean(self): super().clean() """Checks that no two articles have the same title.""" if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return titles = [] for form in self.forms : title = form.cleaned_data['item'] if not title == '': if title in titles: raise forms.ValidationError(" %s in a set must have distinct titles." % title) titles.append(title) i want to clean to ignore form in formset if they are empty or if they are mark with delete -
Using Django Window Functions on a Filtered QuerySet
I ran into a surprising conundrum with Window Functions no Filtered QuerySets. Consider with models: mymodel and relatedmodel where there is a one to many relationship (i.e. relatedmodel has a ForeignKey into mymodel). I was using something like this: window_lag = Window(expression=Lag("pk"), order_by=order_by) window_lead = Window(expression=Lead("pk"), order_by=order_by) window_rownnum = Window(expression=RowNumber(), order_by=order_by) qs1 = mymodel.objects.filter(relatedmodel__field=XXX) qs2 = qs1.annotate(row=window_rownnum, prior=window_lag, next=window_lead) qs3 = qs2.filter(pk=myid) which returns a lovely result in for the object pk=myid I now now it's position in the filtered list and its prior and next and I use this to great effect in browsing filtered lists. Significantly len(qs1) = len(qs2) is the size of the list and len(qs3)=1 Alas I just discovered this break badly when the filter is less specific: window_lag = Window(expression=Lag("pk"), order_by=order_by) window_lead = Window(expression=Lead("pk"), order_by=order_by) window_rownnum = Window(expression=RowNumber(), order_by=order_by) qs1 = mymodel.objects.filter(relatedmodel__field__contains=X) qs2 = qs1.annotate(row=window_rownnum, prior=window_lag, next=window_lead) qs3 = qs2.filter(pk=myid) In this instance, qs2 suddenly has more rows in it that qs1!And len(qs2)>len(qs1). Which totally breaks the browser in a sense (as prior and next are not reliable any more). The extra rows are duplicate mymodel objects, wherever more than one relatedmodel object matches the criterion. I've traced this to the generated SQL. This is … -
Is there a way to define a Django form field as integer in such way, so it takes the number from the slider in the template?
I want to save a model attribute through from as a number from 1 to 10. models.py attr1 = models.IntegerField() index.html <div class="slidecontainer"> {{ form.attr1.label_tag }} {{ form.attr1 }} <br> <input type="range" min="1" max="10" value="5" class="slider" id="Scale1"> </div> Is it possible to somehow get the value from the slider, and put it to the IntegerField? Is there any better way to solve this issue? -
django cms breakes down after installing django-cms blog and python manage.py migrate
Immediately i install djangocms-blog, then add the djangocms_blog to INSTALLED_APPS i get errors on server restart RuntimeError: Model class cmsplugin_filer_image.models.FilerImage doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. When i remove the the cond from the setting.py its fine INSTALLED_APPS = ( 'djangocms_admin_style', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django.contrib.messages', 'cms', 'menus', 'sekizai', 'treebeard', 'djangocms_text_ckeditor', 'filer', 'easy_thumbnails', 'djangocms_column', 'djangocms_file', 'djangocms_link', 'djangocms_picture', 'djangocms_style', 'djangocms_snippet', 'djangocms_googlemap', 'djangocms_video', 'mptt', 'aldryn_bootstrap3', 'aldryn_background_image', 'djangocms_icon', 'djangocms_blog', 'web_nia' ) I expect this to set up and enable me put some blogs on my django cms site -
Django doesn't log to specified file from celery.py
I'm trying to figure out what to do when I want to log something outside project. I have a file celery.py in project/project/ directory. I'm trying to use logger automatic_actions which setting is specified in settings.py. Unfortunately, it doesn't log anything in it. logger = logging.getLogger('automatic_actions') @periodic_task(run_every=timedelta(seconds=5)) def export_properties(): logger.info('EXPORTING STARTED...') I suppose it is because when celery run this task, there is no Django environment setup. But when I try to setup Django: from project import settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() app = Celery('project',broker='redis://localhost') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() logger = logging.getLogger('automatic_actions') And run for example shell_plus: AttributeError: 'Settings' object has no attribute 'COMPRESS_ROOT' Do you know how to make it work?