Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery doesn't process the task request in single hit?
I have set up a Django project with Celery and Redis. I am trying to send an OTP to a mobile number. The problem is whenever I try to execute the task by running sms_queue_processor.delay(phone, message) the celery worker doesn't receive the task. I tried the same executing from the shell but it doesn't receive at all. I tried to execute the statement from the shell at a rapid speed twice then the celery worker receives and I can able to receive the SMS. This is something weird and can't be trustable. What can be the problem? Django == 2.0.9 celery == 4.3.0 redis == 3.2.1 My Celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from django.utils import timezone from webapp.utils import send_sms os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webapp.conf.settings') app = Celery('webapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True, default_retry_delay=1 * 60) def sms_queue_processor(self, phone, message, func=None, metadata=None): countdown = 60 max_retries = 3 from webapp.conf import log obj = add_entry_to_celery_audit_tracker(queue_name=self.name, func=send_sms.__name__, executed_at=timezone.now(), metadata=metadata, status=False, celery_task_id=self.request.id) log.debug('sending sms data') try: response = send_sms(phone, message) except Exception as exc: raise self.retry(exc=exc, countdown=countdown, max_retries=max_retries) log.info('sms queue processed', response=response) update_celery_audit_tracker( celery_audit_tracker_object=obj, status=True, executed_at=timezone.now()) log.info('SMS Celery audit trail updated') def add_entry_to_celery_audit_tracker(queue_name, func, … -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL must be of the form 'app_label.model_name'
I have this code in my settings.py , did i miss something in my code that i am struggling on this error? i cant do python.manage.py makemigrations. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL must be of the form 'app_label.model_name' INSTALLED_APPS = [ 'Homepage', 'django_tables2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } AUTH_USER_MODEL = 'Homepage' ----> i am getting error from this line my file myproject |_Homepage |_models |_ ..... |_schoolsite |_settings.y this is the traceback -
Django templates - how to run a method on a variable?
I'm new to Django, so maybe my attempts are pure heresy ;) I'm trying to make a view which lists disponible conference rooms with its attributs, availability included. I have 2 models: Room and Reservation. I'd like in the view to have a column saying if the room is available the day the page is displayed. My models.py: from django.utils import timezone from django.db import models class Room(models.Model): name = models.CharField(max_length=255, unique=True) capacity = models.IntegerField() projector = models.BooleanField() class Reservation(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) date = models.DateField() comment = models.CharField(max_length=255) class Meta: unique_together = ('room', 'date',) my views.py: class ShowRoom(View): def get(self, request): rooms = Room.objects.all() time_now = timezone.now().date() context = { 'rooms': rooms, 'time_now': time_now } return render(request, 'rooms/list_rooms.html', context) My template: {% extends 'rooms/base.html' %} {% block block_title %} Home {% endblock %} {% block block_content %} {% if rooms %} <table class="table"> <thead> <td> Name </td> <td> Capacity </td> <td> Available </td> <td> Projector </td> </thead> <tbody> {% for room in rooms|dictsort:'capacity' %} <tr> <td> <a href="{% url 'rooms:detail_room' room_pk=room.pk %}">{{ room.name }}</a> </td> <td> {{ room.capacity }} </td> <td> Available? </td> <td> {{ room.projector|yesno:'yes,no' }} </td> </tbody> {% endfor %} </table> {% else %} <h1> You … -
Trying to install Django reversion
I'm trying to setup a Django project but Im getting this: python2.7 manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named reversion So I'm trying to instal reversion, but I'm getting this error message when trying to installenter code here it: Downloading/unpacking django-reversion Downloading django-reversion-3.0.7.tar.gz (67kB): 67kB downloaded Running setup.py (path:/tmp/pip_build_root/django-reversion/setup.py) egg_info for package django-reversion Traceback (most recent call last): File "<string>", line 17, in <module> File "/tmp/pip_build_root/django-reversion/setup.py", line 28, in <module> long_description=read('README.rst'), File "/tmp/pip_build_root/django-reversion/setup.py", line 19, in read with open(filepath, "r", encoding="utf-8") as f: TypeError: 'encoding' is an invalid keyword argument for this function Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/tmp/pip_build_root/django-reversion/setup.py", line 28, in <module> long_description=read('README.rst'), File "/tmp/pip_build_root/django-reversion/setup.py", line 19, in read with open(filepath, "r", encoding="utf-8") as f: TypeError: 'encoding' is an invalid keyword argument for this function ---------------------------------------- Cleaning up... … -
How to convert list into string
When I do a database query I am returned a result of [('2c1bfbcc99ba4bc6858110a8fee2dc7c',)] which contains the string I need.... However I need to remove the brackets, parentheses, and the comma. the above value is stored in a variable called result I have tried str(result) but that just returns "[('2c1bfbcc99ba4bc6858110a8fee2dc7c',)]" which does not help at ALL lol! I am looking for a way to parse out the brackets, parentheses, and the comma using just a few lines of python. If anyone can help it would be greatly appreciated! -
Django Choice Field options not showing
I'm using a choice field to allow users to be assigned to different tickets, but when choices are given, they don't appear on the webpage. forms.py class TicketAssignedForm(forms.Form): def __init__(self, ticket, *args, **kwargs): print(ticket.assignable()) super(TicketAssignedForm, self).__init__(*args, **kwargs) self.choices = { "assigned": ticket.assignable() } print(self.choices['assigned']) self.initial = { "assigned": ticket.assigned, } assigned = forms.ChoiceField(label="Assigned") The print statements both output: [<User: Bob>, <User: Jim>, <User: Jeff>] this being a list of User objects. views.py ticket_assigned_form = TicketAssignedForm(ticket) return render(request, 'view_ticket.html', {'ticket_assigned_form': ticket_assigned_form}) In theory I should have a select input with an option for each of the users, but instead it's just empty. Edit I've also tried to use the following list however I get the same result: [(1, 'Bob'), (2, 'Jim'), (4, 'Jeff')] -
Unable to override post method of Django UpdateView
I have a update view in django project. I need to override the post method because I am using multiple modelform. views.py: class EmployeeUpdateView(LoginRequiredMixin, UpdateView): """ Update a created a employee """ login_url = '/authentication/login/' template_name = 'employee/employee_update_form.html' form_class = EmployeeAddModelForm work_form_class = WorkExperienceForm education_form_class = EducationForm queryset = Employee.objects.all() #success_url = reverse_lazy('employee:employee-list') def get(self, request, *args, **kwargs): id_ = self.kwargs.get("id") employee_id = Employee.objects.get(id=id_) work_info = WorkExperience.objects.get(employee=employee_id) education_info = Education.objects.get(employee=employee_id) return render(request, self.template_name, { 'form': self.form_class(instance=employee_id), 'work_form': self.work_form_class(instance=work_info), 'education_form': self.education_form_class(instance=education_info) } ) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) work_form = self.work_form_class(request.POST, prefix='work_form') education_form = self.education_form_class(request.POST, prefix='education_form') # Check form validation if form.is_valid() and work_form.is_valid() and education_form.is_valid(): instance = form.save() work = work_form.save(commit=False) education = education_form.save(commit=False) work.employee = instance education.employee = instance work.update() education.update() return redirect('employee:employee-list') return render(request, self.template_name, { 'form': form, 'work_form': work_form, 'education_form': education_form } ) When I press update button of my form, error is giving showwing "This field already exist". It means when i update the form is post data as a new form not as a update form. Where is error in my post method? -
How to refresh foreign key drop downs on admin forms
I've got an app running on Django that allows configuration through the admin interface. One of the models has four different fields that point to a model that details a variety of metadata about dates. Most of the time, each field will refer to different details, but, sometimes, a user needs to have two of them pointing at one instance and the other two pointing at another instance. The default django admin form for the model has a handy-dandy drop down and add button for each of the four fields. If you add one of these date metadata objects, the other drop downs aren't updated. If you go to add that same constraint, you rightfully encounter a foreign key constraint error. In order to reuse these instances, you have to save the form and reload it. Is there a way to either have the form refresh the drop downs when a new instance is added and assigned or have a new creation perform a get-or-create rather than just a create? -
Django version 3.0.7, TemplateSyntaxError at /cart/ 'cart' is not a registered tag library
Error :- Request Method: GET Request URL: http://localhost:8000/cart/ Django Version: 3.0.7 Exception Type: TemplateSyntaxError Exception Value: 'cart' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz template tags > cart.py @register.filter(name='cart_quantity') def cart_quantity(product , cart): keys = cart.keys() for id in keys: if int(id) == product.id: return cart.get(id) return 0 and the error comes in my .html file which say {% load cart %} I have restart the Django development server -
how to customize django password reset context
For a website I'm using django's password reset feature with a custom template. I display some results from database that are obtained based on request.user data. So it means I need to pass the info to the template. I tried using ajax to load the content on page load but it was a bit too complicated. I wonder what's the best way to add more content to custom password reset context of django. -
Django can an appname be the same as its model name
For example, I have an app called Apple. Can the model inside its models.py be also called Apple? ex: class Apple(models.Model) (same case). Will I face any problems later on in referencing it or will django do? (any impossible to solve ones). -
Dynamic Fields in Django Admin Page
I'm trying to create an interface for the admin page of my app, where new fields are added to the template on input of the admin. For this purpose there should be an option " Add Text Question " or " Add Numerical Question". Afterwards the class TextQuestion or NumericalQuestion should appear, so that you can build a sequence of questions. Does Django offer such an option? Unfortunately I didn't find a possibility for it while surfing the internet. class QuestionAdmin(admin.ModelAdmin): fieldsets = [ ("General", {'fields': ['question','question_type']}), ("Text Question", {'fields': ['text_answer']}), ("Numerical Question", {'fields': ['numerical_answer_lower','numerical_answer_upper']}), ("Scheduling", {'fields': ['schedule']}) ] admin.site.register(M1_Question,QuestionAdmin) -
pytest-django tests are not running becuase Database access not allowed,
i created some using pytest and i added the pytest marker @pytest.mark.django_db but still the tests are not able to run as the access to db is not allowed, how i can fix this import pytest from tests.users.factories import UserFactory @pytest.mark.django_db class test_user_factory(): user = UserFactory() assert user.id assert not user.is_staff and not user.is_supreuser errors: venv/lib/python3.6/site-packages/django/db/models/query.py:1204: in _insert return query.get_compiler(using=using).execute_sql(returning_fields) venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1390: in execute_sql with self.connection.cursor() as cursor: venv/lib/python3.6/site-packages/django/utils/asyncio.py:26: in inner return func(*args, **kwargs) venv/lib/python3.6/site-packages/django/db/backends/base/base.py:260: in cursor return self._cursor() venv/lib/python3.6/site-packages/django/db/backends/base/base.py:236: in _cursor self.ensure_connection() E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. ==================================================================================================== short test summary info ===================================================================================================== ERROR tests/users/test_factories.py - RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -
Django calculations in models
While I was working in django models i tried to implement calculations part in django models. But it is showing error as inconsistent use of tabs and spaces in indentation (, line 72). line 72 is "def Extra_Payment(self):" ---Please Check the code image with error class Salarie(models.Model): Employee_Name = models.ForeignKey('Employee_Detail', models.DO_NOTHING,primary_key=True) Dept_Name = models.ForeignKey('Department', models.DO_NOTHING) Basic_Salary = models.IntegerField() Extra_Hours = models.IntegerField(default=0) @property def Extra_Payment(self): return self.Extra_Hours * 300 Bonous = models.IntegerField(default=0) @property def Total_Payment(self): return self.Extra_Payment + Basic_Salary + Bonous Paid_Date = models.DateField(null=True,blank=True) -
Can I run a Django project without Docker?
So, I found an opensource project on Django, in its README.md file, they mentioned something about to run the project in docker however we can run Django directly with 'python manage.py runserver', but can we also run those kinds(which contain docker) of projects without docker in our local machine. Thanks. -
Django model and field as requested by user
i have a lot of machines, each machine has own maintenace parameter to be checked so i want to create a machine asset management i want to create a form for a parameter of each machine to be checked and stored them to database. machine A temperature at inlet / 1 hour / number temperature at outlet / 1 hour / number vibration at inlet / 1 day / number machine B material color / 3 day / multiple choice temperature / 1 hour / number noise / 1 day / number the problem is all machine and all the paramater of checking list is defined by user. how can i make this model in django. -
CreateView not saving form Django
im new to Django. Im creating a bidding site, where users should be able to visit a page to create a new listing (item that they are going to put up).The form that they are required to submit has a few common fields and when valid, the said form should be saved. Problem is, my listingcreateview() is not doing that. I submit a correct form but it wont save, it just redirects to the same form page and No errors are shown. This because the submitted form is validated as invalid every time. I know this because of the two functions i added inside listingcreateview(), the second one is called. It was working properly before, dont know what changes messed it up. If i add in the admin interface information by hand, it is saved successfully. views.py: class ListingCreateView(CreateView): model = Listing fields = ['title', 'content', 'image', 'min_bid', 'categories'] def form_valid(self, form): form.instance.seller = self.request.user return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(reverse("index")) models.py: class User(AbstractUser): pass class Listing(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to='media') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) categories = models.CharField(max_length=25, choices = category) seller = models.ForeignKey(User, on_delete=models.CASCADE) ## min_bid = models.FloatField(blank=False) image_thumbnail = … -
Is there a silver bullet for validation in django-rest-framework?
While developing I often find myself needing some validation. Example: models.py class Survey(models.model): type=models.Charfield({...}) class Question(models.model): type =models.CharField({...}) survey = models.Foreinkey(Survey, {...}) Validation: Validate that every question saved to the DB has a question.type that is compatible with the module type. So, a survey of type Boolean could not be linked to questions of type Scale-1-to-5. My understanding of validation for this use-case is this (my assumptions might be wrong): Validate in the save() method --> Makes the save() method very convoluted for bigger apps Validate via field-validators on the models -> only gives access to the value and not the instance --> FK relations are hard to validate with this. Validate on Serializer fields --> Same problem as with the model fields and also doesn't translate to django-admin (rules will not be enforced on the admin). Validate in serializer methods like create() or update() works but is also not enforced on the admin, custom commands, etc. Validate as part of a pre_save() signal --> Makes it very hard to send an appropriate response to the user on error (I haven't actually tested this yet). Ideally, I would be able to have all my validation logic in one place but … -
Django-webpush: icon of the push didn't appear
Django 3.0.8 django-webpush==0.3.3 In my Post model class: def save(self, *args, **kwargs): super().save(*args, **kwargs) payload = {"head": "Welcome!", "body": "Hello World", "icon": "https://i.imgur.com/dRDxiCQ.png", "url": "https://www.example.com"} send_group_notification(group_name="all", payload=payload, ttl=60000) Problem Icon of the webpush doesn't appear: The url of the icon seems to be correct and really contain an image. Could you help me? -
Referencing a model field in another models class in Django
I have a choice list (CERTIFICATES) in my model class say, class Registration. I want to access the same choice list in another class say, class Admission without typing everything again. How do I go about it? I've commented out where I want to reference the choice list in the code below: from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Registration(models.Model): TITLE_CHOICES = ( ('Mr.', 'Mr.'), ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Rev.', 'Rev.'), ('Dr.', 'Dr.'), ) EDUCATIONAL_LEVEL = ( ('PR', 'Primary'), ('JHS', 'JHS'), ('SHS', 'SHS'), ('TR', 'Tertiary'), ('HR', 'Higher') ) PURPOSE = ( ('TN', 'Training'), ('PS', 'Personal studies'), ('GS', 'Group studies'), ('RH', 'Research'), ) title = models.CharField(max_length=5, choices=TITLE_CHOICES, default='Mr.') full_name = models.CharField(max_length=50, null=False, blank=False) age = models.IntegerField() address = models.CharField(max_length=100) phone_number = PhoneNumberField(max_length=10) occupation = models.CharField(max_length=50, default='Student') institution = models.CharField(max_length=150) educational_level = models.CharField(max_length=10, choices=EDUCATIONAL_LEVEL, default='PR') purpose = models.CharField(max_length=20, choices=PURPOSE, default='TN') def __str__(self): return self.full_name class Admission(models.Model): MARITAL_STATUS = ( ('SN', 'Single'), ('MA', 'Married'), ('DV', 'Divorced'), ) DISABILITY = ( ('NN', 'None'), ('PHD', 'Physical Disability'), ('VID', 'Visual Disability'), ('HRD', 'Hearing Disability'), ('MND', 'Mental Health Disability'), ('IND', 'Intellectual Disability'), ('LND', 'Learning Disability'), ) CERTIFICATES = ( ('BE', 'BECE'), ('SSW', 'SSCE/WASSCE'), ('DIP', 'DIPLOMA'), ('HND', 'HND'), ('DEG', 'DEGREE'), ('OT', 'OTHER'), ) PROGRAMMES = ( … -
Quering api calls
I have 2 models, user model and a blog post model. these are pretty generic. I just wanted to make an api call based on the user of the post. So for example a json representation of a post would be like this. { "id": 2, "title": "Audio Book", "body": "Boken hobbiten handasdasdsadasdasdsaler om en hobbit som er på et eventyr med en trollmann.", "created": "2020-07-16T13:52:08.911331Z", "user": { "id": 7, "user": 5 } } and i am trying to query this post based on the user id and not the post id? How do i do this? Any tips? -
How to import models frome one Django app to another?
i tried to import models from one app to another by using from ..appName.models import className also from appName.models import className but attempted relative import beyond top-level package error occured. My aim is to create a student management system. In one app i created the model and in another app i try to retrive data from that model but failed to do it.. Excuse my english -
DJANGO REST - CLASS BASED VIEW - POST,GET requests do not work as they are defined
I've set up a class-based view that handles all the requests views.py #Imports from django.shortcuts import render from .serializers import UserSerializer from rest_framework import viewsets from django.contrib.auth.models import User from rest_framework.decorators import api_view from django.http import HttpResponseForbidden from rest_framework.response import Response from rest_framework import status #Imports End class UserApiView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get(self, request, format=None): raise HttpResponseForbidden("Get Requests are not allowed here") def post(self, request, format=None): if request.is_ajax(): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: raise HttpResponseForbidden("You are not allowed to acess this page") this is the serializer class ( serializers.py ) from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username','email','password'] The urls.py are being handel by the DefaultRouter() from django.urls import include, path from rest_framework import routers from .views import UserApiView router = routers.DefaultRouter() router.register(r'user',UserApiView,basename="takis") urlpatterns = [ path('', include(router.urls)), ] I want the backend to handle the view just as said in the post and get request methods , but they do not seem to get executed. I can normally access the url , without a forbidden error and it accepts requests even if they are not ajax. -
Django ORM replacement for extra where
Here is a scenario that I currently plan solving with .extra(where=...) call: class CustomData(models.Model): data = models.CharField() target_type = models.ForeignKey(ContentType) target_object_id = models.PositiveInteger() target_object = GenericForeignKey('target_type', 'target_object_id') # list of tuples with object ID and mixed content type ID [(1, 15), (2, 15), (3, 11), (4, 12), ...] related_objects = get_list_of_objects(...) releated_custom_data = CustomData.objects.extra( where=['(target_object_id, target_type_id) in %s'], params=related_objects ) Based on django docs extra is getting deprecated in the future. (https://docs.djangoproject.com/en/2.2/ref/models/querysets/#extra). Is there a sensible alternative for making a value pair filtering with the ORM? -
How to save user but user.is_authenticate need to be false?
In my web application i send email to user to activate his account and when i redirect him to confirmed page from email menu items that should not be displayed are displayed because he is authenticate but doesn't login Views function to activate user: def activate_user_account(request, signed_user=None): user, signature = decoder(request, signed_user) if user and signature: user.email_confirm = True user.save() return render(request, 'email_verify_done.html', {'user': user}) And after that function user redirect to this template: {% if user.is_active %} {% if user.is_authenticated %} <p class="text-center">{% trans 'Your email address confirmed' %}</p> {% else %} <p class="text-center"> {% trans 'You can' %} <a href="{% url 'users:login' %}"> {% trans 'log in now' %}</a> {% trans 'or do it in your mobile app' %} </p> {% endif %} {% else %} <p>{% trans "Something went wrong." %}</p> {% endif %} Here the user passes both conditions and all menu items are displayed although they do not need to authenticate