Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: How do I correctly add the HyperlinkedRelatedField field to the serializer?
I want to make it possible for a json that gives all the model instances to go to a particular instance using the additional url field in the serializer. There is a view to display the list class DocumentsListView(viewsets.ViewSetMixin, generics.ListCreateAPIView): user = serializers.PrimaryKeyRelatedField(read_only=True,) queryset = Documents.objects.all() serializer_class = DocumentsSerializer permission_classes = [] def perform_create(self, serializer): serializer.save(author=self.request.user) urls.py router = DefaultRouter() router.register('', DocumentsListView) urlpatterns = [ url('', include(router.urls), name='files') ] serializers.py class DocumentsSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedRelatedField(view_name='???????') class Meta: model = Documents fields = ('id', 'filename', 'datafile', 'type', 'created', 'url') What value should I use for the required view_name field ? -
How to load fixtures for a LiveServerTestCase
I am attempting to write test cases in Django using Selenium. I want to use existent fixtures so my test database has test data for every test. I have some model test cases (just using the TestCase class) as follows; from django.test import TestCase from missions.models import Mission, MissionDataRecord from django.contrib.staticfiles.testing import LiveServerTestCase class MissionModelTests(TestCase): fixtures = ['myproject_common/fixtures/auth_initial_load.json', 'worklog/fixtures/worklogs_initial_load', 'missions_initial_load.json'] def test_object_name_is_mission_title(self): mission = Mission.objects.get(id=1) self.assertEqual(mission.title, str(mission)) def test_object_name_is_mission_title_again(self): mission = Mission.objects.get(id=1) self.assertEqual(mission.title, str(mission)) This works as expected when run like this (I get two test passes). However, for Selenium testing I need to use LiveServerTestCase instead of TestCase. The simple example above is a model test, but for illustrative purposes of the issue I'm facing with Selenium, if I simply replace "TestCase" with "LiveServerTestCase" the first test passes, but the second test fails, with the error django.db.utils.IntegrityError: Problem installing fixture '[...]/fixtures/auth_initial_load.json': Could not load auth.User(pk=1): UNIQUE constraint failed: auth_user.username This error occurs in the _fixture_setup of /django/test/testcases.py. This seems to suggests that my fixtures (specifically the auth_initial_load fixture) is attempting to load again ON TOP of existing data. However, from django docs reading this should not be taking place, because each test should run in its own transaction (which … -
IntegrityError In Django(NOT NULL constraint failed)
So, I was following this a Django tutorial series on youtube(thenewboston), While I was following this tutorial, the guy decided to do some weird stuff off-screen and decides to delete every single thing related to a function. I tried to delete everything of that certain function. And now I'm getting an integrity error of a statement that doesn't exist in my code. I've checked every single file and found no line related to the error. I know this is weird but it would be a huge help for me. The error is this: http://dpaste.com/29EKRY9 The Code Is At My Github: https://github.com/diayush/Django Thanks In Advance. -
django how to override an error page to a specific endpoint?
I'm trying to override the 500 error view https://docs.djangoproject.com/en/2.2/ref/views/ I have implemented 500.html but i want to ensure that any instance of a 500 gets redirected to my own custom specific endpoint (say my-error/) How do I accomplish this? -
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?