Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError:No module named 'howdy' in Django
ModuleNotFoundError : No module named 'howdy' from howdy.models import Login Project Structure Image -
"Commands out of sync; you can't run this command now" while running paginator on django model
As I am backfilling some of the model entries & queryset is large. I used paginator on model. It working fine when It run once. If I execute the script again it gives me "Commands out of sync; you can't run this command now". I am aware it happens when there are shared connections / connections ain't closed/committed. for i in paginator.page_range: current_page = paginator.page(i) for txn in current_page: pass -
Error during using interator loop in Jinja2/Django/ How to use interator loop?
I want to print the index of this list 'seq1' seq1[0],seq1[1] etc. But in the Jinja2, I can note use index of list to find positions. But I would like to put this in a loop, I need to manipulate these index!! **I would like a similar code like this:** {% for item in seq1 %} {{seq1.item}} {% endfor %} It works: {{seq.1}} Someone can help me? I need to use html tags to color this list -
How to add multiple lines of the Formset?
i work on the form for users. They have to add many model objects in the appropriate form. one line is displayed when entering the GET method, they will type in input name = "add-rows-number" the number should be displayed the number of forms in the formset I tried with formset and with model formsetfactory class AddCostCenters(View): def __init__(self, *args, **kwargs): super(AddCostCenters, self).__init__(*args, **kwargs) self.FormSet = modelformset_factory(CostCenter, form=CostCenterAddForm, extra=self.get_form_size) def get_form_size(self, request): extra_rows_num = 1 if 'add-rows' in request.POST: extra_rows_num += int(request.POST.get('add-rows-number')) return extra_rows_num def get(self, request, proceeding_id): costcenter_model = CostCenter.objects.filter( participation__provider__user=request.user, participation__proceeding=proceeding_id ) return TemplateResponse(request, 'costcenteradd.html', context) def post(self, request, proceeding_id): costcenter_model = CostCenter.objects.filter( participation__provider__user=request.user, participation__proceeding=proceeding_id ) # if 'add-rows' in request.POST: # try: # rows_to_show = int(request.POST.get('add-rows-number')) # except ValueError: # rows_to_show = 0 # self.extra_rows_number += rows_to_show if 'save_form' in request.POST: new_cost_centers = [] post_formset_data = self.FormSet(request.POST) if post_formset_data.is_valid(): instances = post_formset_data.save(commit=False) new_cost_centers.append(instance) # do something else: post_form = post_formset_data context = { 'form': post_form, } return render(request, 'costcenteradd.html', context) form class CostCenterAddForm(forms.ModelForm): # helper = CostCenterAddFormSetHelper() def __init__(self, *args, **kwargs): super(CostCenterAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False for field_name, field in self.fields.items(): field.help_text = None class Meta: model = CostCenter fields = ( 'id', … -
AttributeError at / 'OrderedDict' object has no attribute 'register' in Django REST framework from quickstart documentation
I am trying to work with Django REST framework but I am getting the AttributeError at / 'OrderedDict' object has no attribute 'register'. I think I have followed the documentation properly Can someone help with this. Link to the tutorial: https://www.django-rest-framework.org/tutorial/quickstart/ I have already used Django now I am trying to work with the Django REST framework but following the quickstart tutorial is resulting in: AttributeError at / 'OrderedDict' object has no attribute 'register'. tutorial.py/urls.py from rest_framework import routers from quickstart import views from django.contrib import admin router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] tutorial/quickstart/serializers.py from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name'] tutorial/quickstart/views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer tutorial/settings.py import os # Build paths inside the project like this: … -
Choosing column to search by in django-rest-framework
I am writing a Django REST Framework-based app and I want to choose the field to search with in the API DB model definition: class Log(models.Model): """Define staging Log format""" fkhistory = models.ForeignKey(History, on_delete=models.CASCADE) sequence = models.PositiveIntegerField() log = models.TextField() logdate = models.DateTimeField(auto_now_add=True) Serializer: class LogSerializer(serializers.Serializer): """Defines log table""" fkhistory = FkHistorySerializer(required=False, read_only=True) sequence = serializers.IntegerField(read_only=True) log = serializers.CharField(read_only=True) I am able to query the table with /api/log/<id> but I would like to query it with /api/log/<fkhistory> Anyway to do it without reinventing the wheel? I have tried reading the documentaiton but I found no answers. Thanks -
Linking a select option in Angular to a charfield choice in Django
I get data from Django, populate a form with this data, I then want to edit it and update it with a PUT request. I have got the PUT request working with normal inputs. But it doesn't work with my select options. I have checked the network tab and can see that it sends the data in the PUT request. I have tried setting the value attribute of the option to both the key and value of the choice, and I have tried setting the option text to both the key and value of the choice as well. None of these have been able to change the stored value yet. Component HTML: <div class="form-group"> <label for="pt-select">Type</label> <select class="form-control" id="pt-select" [(ngModel)]="project.Type" name="Type"> <option>Civil/Structural</option> <option>Demolition</option> <option>Asbestos Removal</option> <option>Integrated</option> <option>Piling</option> </select> </div> Models Python: CHOICES = [ ('CS', 'Civil/Structural'), ('DM', 'Demolition'), ('AR', 'Asbestos Removal'), ('IN', 'Integrated'), ('PI', 'Piling') ] Type = models.CharField(null=True, blank=True, max_length=2, choices=CHOICES) I am expecting the PUT request to work as the other parts have and to override what is currently stored. The PUT request is being sent with what I think is the correct data but it is not overriding. No error messages. -
Django manage concurrency without redundancy and table locks
I have an Account model and a Transaction model. the balance of an account is calculated by subtracting all withdrawals from all deposits of an account. and I don't want to have a "balance" field on the model and update it whenever a new transaction is created, because of redundancy problems later. To ensure that you don't withdraw more than your account balance, I check the withdrawal amount against the account balance on Transaction pre_save. the problem is, more than one withdrawal request might happen at the same time thus resulting in inconsistent data. I could lock the table while a Transaction object is being created but that would be too costly. how do I handle that? class Account(models.Model): name = models.CharField(max_length=255) @property def balance(self): all_deposit = self.transactions.filter(is_deposit=True).aggregate(Sum('amount'))['amount__sum'] all_withdrawal = self.transactions.filter(is_deposit=False).aggregate(Sum('amount'))['amount__sum'] if all_deposit is None: all_deposit = 0 if all_withdrawal is None: all_withdrawal = 0 return all_deposit - all_withdrawal class Transaction(models.Model): amount = models.PositiveIntegerField() is_deposit = models.BooleanField() account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="transactions") @receiver(pre_save, sender=Transaction) def check_balance(sender,instance, **kwargs): if instance.is_deposit: return if instance.account.balance < instance.amount: raise Exception("Under Balance") -
Which is better: Django or Flask?
Tell me please, Pros and Cons of these two frameworks?) Which is better for web`a?) Thanks) -
Django email sending, but not received
I know this has gotten asked a hundred times, I've gone through most of the past questions and still cannot email to send from Django. The send-email folder has a copy, meaning all of the test emails are sending, but they never reach my gmail account. I turned access to less secure websites on my gmail account, so it should work, but does not seem to. Here is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER Not sure, why it's not working. -
Wagtail RichTextField preview shows the HTML
I am currently trying to implement wagtail CMS to my django project. I have built models for a page, which includes: body = RichTextField() content_panels = Page.content_panels + [FieldPanel('body'),] However, when i enter text and try and do any alterations within the wagtail admin panel for this page, the preview brings through HTML. I have tried to change this in many ways. When using models.TextField instead of RichTextField, I do not have any issues with html coming through. Preview page returns: < h1 >Title Here < /h1 > < p> Some text here < /p > If anyone knows why this may be occurring and how it can be resolved, I would be very grateful. -
Making URL to accept parameters as optional. Non Capturing
I want to make my url to accept the optional parameters only when given. I am unable to make the parameters optional/non-capturing. re_path(r'^users/(?:(?P<slug:sort_by>))', views.UserListView.as_view(), name='user_list'), I want this url to accept a slug field only when provided to the view. How can I do this? -
Django same instance has two different field values
I have a model A which has a foreign key to another model B. There is an instance's field I have of interest on my B model - B.field returns False. However, I have an instance of A whose fk field is this same instance of B, yet when I do A.B.field, it returns True. I can't figure out why these values differ. This is when I access the variables in a Django shell b = B.objects.get(id=1) a = A.objects.get(id=1) a.foreign_key == b # returns True b.field # False a.b.field # True I'm led to believe that a.foreign_key and b are the same instance of the B model, yet they can't be since their fields differ. Is this defined behaviour in django? -
Django 2.x: Is using the Primary Key of a Model in the URL pattern a security concern?
The id (PK) of a model/ DB can be passed to and used in the URL pattern. Everyone, including hackers, would be able to piece together some information about my DB from this and the actual data in the template. My questions are kind of general at this point. I would just like to understand how the info above could be used to compromise the data. Or if someone could point me to some further reading about this topic I would appreciate it. This is a general question as I am trying to gain more understanding into securing Django sites. I have read several articles but nothing's satisfied the question. Code: Where the href passes the blogs id to be used in url matching and ultimately pulling data from the DB in the views/ template: <a href= "{% url 'details' blog.id %}"> and urlpatterns = [ path('<int:blog_id>/', views.details, name = 'details'), ] And the URL being: domain/appname/blog_id/ TL;DR: Can you hack my site with the few pieces of information I am freely giving away concerning the backend? -
How do I display the result of the beautifulsoup4 parser in django templates?
I'm working on a web application that collects jobs for programmers. It uses django 2.2 and beautifulsoup4. I try to display the results of parsing on the screen after clicking the button in the form redirects to the page of the result of parsing (None). There may be an error in parser or views.py, I can't figure it out. Logic: 1. Django displays the form on the main page 2. The user presses the button in the form 3. Parser collects data 4. Parsing result is displayed on the screen workua.py - scraper import requests from bs4 import BeautifulSoup def clean_description(s): return s.split('\n')[1] def get_html(url): r = requests.get(url) return r.text def get_data(html): bs = BeautifulSoup(html, 'lxml') job_list = bs.find('div', id='pjax-job-list').find_all('div', class_='card card-hover card-visited wordwrap job-link') for item in job_list: title = item.find('h2', class_='add-bottom-sm').text company = item.find('b').text d = item.find('p', class_='overflow').text descr = clean_description(d) url = 'https://www.work.ua' + item.find('h2', class_='add-bottom-sm').find('a').get('href') data = {'title':title, 'company':company, 'descr':descr, 'url':url} # print(data) def main(): pattern = 'https://www.work.ua/ru/jobs-kyiv-python/?page={}' for i in range(0, 3): url = pattern.format(str(i)) get_data(get_html(url)) views.py from django.shortcuts import render from .workua import * from .forms import PageForm def index_page(request): form = PageForm(request.GET) return render(request, 'page/index_page_form.html', context={'form':form}) def workua_result(request): result = main() return render(request, … -
Improving efficiency of QuerySet filter by most recent record of a certain "type" (attribute)
I'll try and keep this as condensed as possible. I have the following query: organisation_survey_results = OrganisationSurveyResult.objects.filter( user=user ).order_by('survey', 'created_date') In the above, I filter according to the user match. All is good. I have returned the 5 records for that user. Now, as mentioned, each record comes with the following attributes and attribute "(chains?)": Unique slug attribute: organisation_survey_result.organisation_survey.survey.slug Immutable (non-changing, write once on creation) created_date attribute: organisation_survey_result.created_date For the five records, if I loop over them, I have: django_1 | food django_1 | 2019-08-12 15:45:49.384071+00:00 django_1 | drink django_1 | 2019-08-12 15:45:49.390939+00:00 django_1 | politics django_1 | 2019-08-12 15:45:49.397714+00:00 django_1 | money django_1 | 2019-08-12 15:45:49.406612+00:00 django_1 | food django_1 | 2019-08-13 11:26:55.831903+00:00 As you can see, I have two records where the attribute organisation_survey.survey.slug with food appears twice. For a given user, this is fine. Records can, and will, supersede each over other time. My question: Is there a way whereby I can filter these records out on the Query? (for performance efficiencies)... I'd like to be able to perform this on the QuerySet level to perform a less stressful serialization of the data. Versions: `Django==2.2.1` `djangorestframework==3.9.3` Database Engine: `PostgreSQL` -
Django Graphene Relay order_by (OrderingFilter)
I have a Graphene interface with Relay and filters. It works pretty well but I would like to add the order_by options. My objects look like: class FooGQLType(DjangoObjectType): class Meta: model = Foo exclude_fields = ('internal_id',) interfaces = (graphene.relay.Node,) filter_fields = { "id": ["exact"], "code": ["exact", "icontains"], } connection_class = ExtendedConnection class Query(graphene.ObjectType): foo = DjangoFilterConnectionField(FooGQLType) ExtendedConnection should not be relevant but: class ExtendedConnection(graphene.Connection): class Meta: abstract = True total_count = graphene.Int() def resolve_total_count(root, info, **kwargs): return root.length This allows me to query like foo(code_Icontains:"bar"). According to the Graphene documentation I should be using the OrderingFilter in a FilterSet for that. I find it a bit annoying since the filters are supposed to be automatic but if I do: class FooGQLFilter(FilterSet): class Meta: model = Foo order_by = OrderingFilter( fields=( ('code', 'code'), ('lastName', 'last_name'), ('otherNames', 'other_names'), ) ) I get an error that I need to provide fields or exclude: AssertionError: Setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed. Add an explicit 'Meta.fields' or 'Meta.exclude' to the FooGQLFilter class. So if I add a fields = [] to silence it, it compiles. However, when I use it in: foo = DjangoFilterConnectionField(FooGQLType, filterset_class=FooGQLFilter) … -
Django: How can I inject a jinja2 variable into a template tag to then return the output
I'm trying to pass a jinja2 variable to a function as a parameter but I am unsure of the syntax or method to do so. I've tried including the reference in the jinja2 function call but this has not worked. I've tested the function and it works with a simple string "test" and the value is render in the page. HTML SECTION ... <tbody> {% for test in test_records %} <tr> <td class="trGrey"> {{ test.id }} </td> <td class="trGrey"> {{ test.testname }} </td> <td class="trGrey"> {{ test.created }} </td> <td class="trGrey"> {{ test.recordtype }} </td> <td class="trGrey"> {{ {{ test.recordtype }}|my_function }} </td> </tr> {% endfor %} </tbody> ... PYTHON FILE from django import template register = template.Library() def my_function(value): if value: return value return '' register.filter('my_function', my_function) I'd expect the input variable to be rendered to the page. Any suggestions will be helpful thanks! -
In AbstractUser does not work ordering in meta
I try when sort with id, first_name, ... but does not work in Meta class into AbstarctUser. ordering = ['id'] does not work but other models working this property. In this code I have set comment for ordering. In under file in User class and nested class Meta, ordering property not working. models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth import get_user_model from django.contrib.auth.models import ( BaseUserManager, AbstractUser ) class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, password, **extra_fields): """ Create and save a user with the given phone number, and password. """ # if not username: # raise ValueError('The given username must be set') # email = self.normalize_email(email) # username = self.model.normalize_username(username) user = self.model(**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, password=None, **extra_fields): extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(password, **extra_fields) def create_superuser(self, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(password, **extra_fields) class User(AbstractUser): email = models.EmailField( verbose_name=_('email address'), max_length=125, null=True, blank=True, ) username = None phone_number = PhoneNumberField(unique=True, verbose_name=_('phone number')) token_sms = models.CharField(verbose_name=_('token_sms'), max_length=125) token_limit = models.IntegerField(verbose_name=_("token limit"), default=0) … -
How to release code for automatic update in django
I have a question. How can I implement the function and where exactly in django so that it automatically checks the user if the end of the premium account approaches. If the date of today coincides with the premium date, then let it turn off the premium account. -
How can I use two consecutive pks in Django URL?
I need to define path for two consecutive primary keys. I have some old version of code with url. Here it is: url(r'^([0-9]+)/(?P<pk>[0-9]+)$' Can someone translate this to path code? -
How to count the number of keys in a django jsonfield
I would like to make a queryset filter to identify all model instance that have a given number of keys in a jsonfield of the model. I have tried to create a custom lookup (#1) to extra the keys in the json field, and would like to aggregate those into an array and use the __len lookup of the array to make my filter. Unfortunately, I am stuck at the aggregation that doesn't seem to work (#2). 1 class JsonKeys(Transform): output_field = TextField() lookup_name = 'keys' function = 'jsonb_object_keys' 2 qs = qs.annotate(keysArray=ArrayAgg("myJsonField__keys")) The error that I get is: HINT: You might be able to move the set-returning function into a LATERAL FROM item. Anyone has already tried to perform this task ? -
How to make groups of all the Customers, Admins and Staff Members and render accordingly in same template based on URL hit?
I am trying to show all the Customers, Superusers and Staff members in a same template. How can I do this? I have a running code like this class GroupListView(UserPassesTestMixin, ListView): model = User template_name = 'admin_app/group_list.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) group_name = (self.kwargs['group']) if group_name == 'admin': context['user_list']= User.objects.filter(is_superuser=True, is_staff=True) elif group_name == 'staff': context['user_list'] = User.objects.filter(is_staff=True) else: context['user_list'] = User.objects.filter(is_superuser=False, is_staff=False) return context def test_func(self): return self.request.user.is_superuser and the urls which produce hits are like this <a href="{% url 'admin:group_list' group='admin' %}"><i class="fa fa-adn"></i>Admin</a> Template is big so there is no need to post that. This is producing results but is there a better way to do this? How can I make Groups and then render the data? NOTE- How can I just make a link and view that will sort all the Users according to the link clicked. (same way in Django- Admin) -
saving hall id .... Error: NOT NULL constraint failed
I try to do hall booking app. I Have set up every things. the model and Serializer view set and urls. I have EndPoint that let user booking the halls. But when i try to booking hall it give me error. I lock at the problem 'NOT NULL constraint failed' after adding to models.py. they suggest to put null in the filed. But in my case i must save the hall id otherwise I can not know the hall the user is booking (it save null in the hall) at the beginning it show this Error: NOT NULL constraint failed: api_bookingmodel.user_id and I solve it by putting in the function perform_create ... serializer.save(user=self.request.user) This is my Code.... Model classes class HallModel(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hall_owner') name = models.CharField(max_length=100) price = models.FloatField() phone = models.CharField(max_length=9, blank=True) size = models.CharField(max_length=50) region = models.CharField(max_length=100) state = models.CharField(max_length=100) image_1 = models.ImageField(upload_to='halls_image') image_2 = models.ImageField(upload_to='halls_image') image_3 = models.ImageField(upload_to='halls_image') created_at = models.DateTimeField(auto_now_add=True) class BookingModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_booking') hall = models.ForeignKey(HallModel, on_delete=models.CASCADE, related_name='hall_owner') time_date = models.DateTimeField(auto_now_add=True) booking_method = models.IntegerField() Serializer class HallSerializer(serializers.ModelSerializer): booking = serializers.SerializerMethodField() class Meta: model = HallModel fields = '__all__' def get_booking(self, obj): booking = BookingSerializer(obj.hall_owner.all(),many=True).data return booking def perform_create(self, serializer): … -
List of Users ordered by the rank of their Posts reviews
I want to make an API End Point so the user can get a list of the users in his city ordered by their post reviews I have defined a method in the post model to calculate the total review (up vote and down vote), all is needed to do is to groupBy user_fk in the post and orderBy sum(count_review()), but I don't know how to do it in django Post Model class Post(models.Model): title = models.TextField(max_length=255, default='Title') post_owner = models.ForeignKey(MyUser, on_delete=models.CASCADE) description = models.TextField(max_length=255) city = models.ForeignKey(City, related_name='location', on_delete=models.CASCADE) longitude = models.CharField(max_length=255) image = models.CharField(max_length=255, default='https://www.eltis.org/sites/default/files/styles/web_quality/public/default_images/photo_default_2.png') latitude = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def count_reactions(self): likes_count = Reaction.objects.filter(post=self.id, is_like=True).count() dislikes_count = Reaction.objects.filter(post=self.id, is_like=False).count() return likes_count - dislikes_count def owner(self): return self.post_owner MyUser Model class MyUser(AbstractUser): phone_number = models.BigIntegerField(blank=False, unique=True) city = models.ForeignKey(City, related_name='city', on_delete=models.CASCADE) address = models.CharField(max_length=255) def owner(self): return self The expected result is to get the ordered list of the users by their posts reviews but only the users in the same city (city field in MyUser model)