Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - authentication only with the email
Im trying to make a custom authentication where I login only with the e-mail address without password. I searched over internet but I dont find a good answer. Im new in Django maybe this is the reason for why I cant find a solution. Can anyone help me with some source code? Thanks -
Django background tasks not taking new code into account
I am using django background tasks to run some code in background. My project has been deployed and I run the background tasks using cron. The problem is when I made changes to my code, the ones related to the background tasks are not taken into account. It seems the cron still using the old code. This is my crontab */5 * * * * /home/.../venv/bin/python /home/.../manage.py process_tasks [duration 299] I think i need to kill the cron command and allow the code to update before running it again. -
raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
I need create a group by queryset with Sum and Func utils from Django But when put all functions inside a annotate I have this error raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name)) django.core.exceptions.FieldError: Cannot compute Sum(''): '' is an aggregate I need to get something like this for the DRF serializer [ { 'quantity': '1520', 'employee__profile__empcod': 762, 'operation__baseqty': Decimal('480.0000000000'), 'duration': 14678.0, 'standar': '30,57' }, { 'quantity': '150', 'employee__profile__empcod': 589, 'operation__baseqty': Decimal('600.0000000000'), 'duration': 94070.0, 'standar': '95,68' }, { 'quantity': '150', 'employee__profile__empcod': 758, 'operation__baseqty': Decimal('720.0000000000'), 'duration': 5060.0, 'standar': '150,68' } ], This is the queryset to get all tasks tasks = TaskOperation.objects.filter(startdt__gte=start, startdt__lte=end, enddt__isnull=False, operation__baseqty__gt=0).order_by('employee_id') tasks = tasks.values('employee__profile__empcod', 'employee__profile__firstname') tasks = tasks.annotate( duration=Sum(Cast(Func('startdt', 'enddt', function='datediff', template='%(function)s(ss,%(expressions)s)'), FloatField())), standar= Sum(Case( When(duration__lte=0, then=0), default=Sum((F('quantity') * 100) / (F('duration') / F('operation__baseqty'))), output_field=FloatField() )) ) -
How to fix error trying to migrate manage.py
I am a beginner when it comes to python so i watch tutorials regulary. The Django framework tutorial i'm watching right now eventually had a step where i had to run the command python manage.py migrate i got the error django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. i know that there are other answers to this error but none work for me. does anybody have a fix? -
How to handle google authentication in django when app is in docker container?
I'm creating Django app and I'm using docker containers to put everything together and use the social-auth-app-django library to login through Google. Due to the principles of deployment in the organization I work for, it's necessary to have one nginx container that listen on 0.0.0.0:2000 and redirects traffic to container with django app on port 8080. I've done this (code to nginx conf file below) and everything works fine to this time, and addtionally set up proxy pass on my local computer to redirect traffic like this: erp.localhost.pl -> localhost:2000 What I've done: Set everything up in my Django files (code below); Created project in google developers console; Got oauth client ID and secret key; Added both http://erp.localhost.pl/complete/google-oauth2/ and http://dev.erp.app/complete/google-oauth2/ to authorized redirect URIs in Google dev console; Added Google+ API to my project in Google dev console. When I go to erp.localhost.pl/login and click on Login with Google I see this error: error while logging from erp.localhost.pl/login But when I'm doing same steps but with localhost:2000/login I see this error: error while logging from localhost:2000/login I have 4 containers in my docker-compose file: version: '3' services: dev_erp_postgres: container_name: dev.erp.postgres image: postgres:latest restart: "no" expose: - "5432" dev_erp_app: container_name: dev.erp.app … -
Field initial data does not display in a ModelSelect2Widget
I am building a django-filter FilterView, using ModelSelect2Widget for some of the filter form fields. It correctly work to select items, and build the right query params in URL, but when I reload the page, passing the filter instance in the context, the ModelSelect2Widget does not display the previously selected item. In template I checked that {{ filter.form.data }} effectively contains the selected data : it is OK. In the principle, the codebase is like this : class BookFilterSet(FilterSet): author = MethodFilter(widget=ModelSelect2Widget( queryset=User.objects.all(), search_fields=['username__icontains',] ), action = 'no_action' def no_action(self, queryset, name, value): """a neutral action""" return queryset class FilterView(FilterView): filterset_class = BookFilterSet template_name = "books.html" Do I need to override some method to display filter.form.initial in the ModelSelect2Widget ? -
i can not load my font on my page, Not allowed to load local resource ERROR
i'm using django for webdeveloping i get a template from https://materializecss.com and it worked well now i wanna change the font of page i write this code to my style.css @font-face { font-family: vazir-medium; src: url(C:\Users\HP\Desktop\uni_project\tutorial\static\font\Farsi-Digits\Vazir-Medium-FD.woff); } body, div, p, a, ul, li, span, i,b, strong, h1, h2, h3, h4, h5, h6, nav, footer { font-family: vazir-medium; } but it doesn't work and i get this error when i see inspect element in chrome Not allowed to load local resource: file:///C:/UsersHP%C3%9Esktopuni_projecttutorialstatic%0Font%C3%BArsi-DigitsVazir-Medium-FD.woff -
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?