Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter Multiselect Field in django (Separate comma)
my Model class Dictionary(): ALLERGIES = ( (0, 'none'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'i'), (10, 'x'), (11, 'y'), (12, 'z'), ) ... allergies = MultiSelectField(default=0, null=True, blank=True, choices=ALLERGIES, max_choices=12) My first tried. dictionaries.filter( Q(allergies__isnull=False) & Q(allergies__icontains=pet_allergy)) example dictionaries data id allergies 1 "1,2,3,4" 2 "1,2,10" 3 "4,5,6,7,10" 4 "6,8,12 5 null pet_allergy = 1 I expected id 1 and 2 to be returned. However, id 1, 2, 3, and 4 returned contrary to my expectation. Because sql was called like %1%. My second tried class Dictionary(): ... def get_allergies(self): if self.allergies: return str(self.allergies).split(',') else: return None dictionaries.filter( Q(allergies__isnull=False) & Q(get_allergies__in=pet_allergy_id) ) >> Cannot resolve keyword 'get_allergies' into field. Is there any good way to solve this problem? P.S. My DB is mariadb. / django = v3.1 -
Which one is better structure for FK relation deletion in django?
class Address(models.Model): old_address = models.CharField(max_length=250) new_address = models.CharField(max_length=250) bjdongName = models.CharField(max_length=20) ... 1. class Listing(models.Model): title = models.CharField(max_length=25) address = models.OneToOneField(Address, on_delete=models.SET_NULL, related_name="listing") def delete(self, *args, **kwargs): address = self.address super().delete(*args, **kwargs) address.delete() 2. class Listing(models.Model): title = models.CharField(max_length=25) class ListingAddress(Address): listing = models.OneToOneField(Listing, on_delete=models.CASCADE) Q1. Which structure is better ? Q2. If I want to delete OneToOneField parent, override delete method or using signal post_delete. But are those performances same? Only when I need to delete_bulk, I need to use signal? Is there another reason using signal delete? -
how exclude an annotation from groups by (values) calculation - django
i'm try to show profit and loss, in a query which is group by date(TruncDay) , here is what im trying to implement class CustomerInvoice(models.Model): seller = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items_model = models.ManyToManyField(Item,through='InvoiceItem') created_at = models.DateTimeField(auto_now_add=True) class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=2) class Item(models.Model): item = models.CharField(max_length=40) quantity = models.IntegerField() buying_price = models.DecimalField(max_digits=30,decimal_places=2) i want to get the daily income, which is subtraction between price from InvoiceItemand buying price from Item if greater than 0 it will be income, but if buying price greater than price it should be loss, but for the entire day, sometimes happens in 10 invoice, we have only one item sold the buying price greater than the price, i want to count it, show that amount of money, but in the group by, in the 10 invoices for example income in 9 invoices are : 100, but in the other invoices which is sold which is buying price : 10, price:9 , it will show the income to 99, it shows nothing in the loss return InvoiceItem.objects.annotate(day=TruncDay('invoice__created_at')).values('day').annotate( paid_price=Sum( (F('price') * F('quantity')),output_field=DecimalField(max_digits=20,decimal_places=3)), storage_price=Sum( F('item__buying_price') * F('quantity'),output_field=DecimalField(max_digits=20,decimal_places=3)), income=Case( When(paid_price__gte=F('storage_price'),then=F('paid_price')-F('storage_price')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), ).annotate( loss=Case( When( storage_price__gt=F('paid_price'),then=F('storage_price') - F('paid_price')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), ).order_by('-day') but i … -
Django Model inheritance error "field ... clashes with the field"
I'm having a problem when using multi-table inheritance in Django and I didn't find something that solved it. I have these two models: class Person(models.Model): id = models.CharField(primary_key=True, max_length=12, default="") name = models.CharField(max_length=12, default="") birthday = models.DateField() class Parent(Person): work = models.CharField(max_length=70, default="") spouce_field = models.OneToOneField(Person, on_delete=DO_NOTHING, related_name="spouce_field") And I get this error when running python3 manage.py makemigrations: ERRORS: family.Parent.spouce_field: (models.E006) The field 'spouce_field' clashes with the field 'spouce_field' from model 'person.person'. Any idea what am I doing wrong? -
i want to reissue jwt token exp verify in python django
i am developing using django and python. im not using DRF. I want to extract the exp from the code below and make the token reissue within 7 days of the current date or past the current date. This is the encoded code homes_session = jwt.encode({'user_id': user.id, 'exp':datetime.utcnow()+timedelta(days=28)}, SECRET_KEY, ALGORITHM) This is the decoded code payload = jwt.decode(homes_session, SECRET_KEY, ALGORITHM) homes_session_exp=payload["exp"] if (now - homes_session_exp).days <= 7: In the decoded payload, when within 7 weeks of the current time or after the current time, I want to customize the jwt to be reissued. Am I not good at understanding jwt??? -
Add users to group in django
I am creating custom groups for different users in my application but I am torn between the two approaches i.e. whether it should be like the following : 1. class Group(models.Model): name = models.CharField(max_length=500, default=0) modules = models.ManyToManyField(GroupModels) accessible_companies = models.ManyToManyField(Company) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=500, default=0) groups = models.ManyToManyField(Group, blank=True) or 2. class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=500, default=0) class Group(models.Model): name = models.CharField(max_length=500, default=0) modules = models.ManyToManyField(GroupModels) accessible_companies = models.ManyToManyField(Company) employees = models.ManytoManyField(Employee, blank=True) What would be the ideal way to create the logic? -
How to include user's image in Post instance
I have a view that returns me every post, what I'm trying to do is include the user's avatar image with the post. Serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' View @api_view(['GET']) def getPost(request): post = Post.objects.all().order_by('-date_posted') serializer = PostSerializer(post, many=True) return Response(serializer.data) User Model class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) avatar = models.ImageField(default='default.jpg') Post Model class Post(models.Model): author = models.ForeignKey(User, on_delete=CASCADE) trade = models.CharField(max_length=100) trade_description = models.TextField(null=True) How can I make it so that when the view returns me the post, it also includes the associated user's avatar image as well? The User's avatar field just holds a link to an amazon s3 bucket that hosts the image -
ImportError: cannot import name force_text using the package nested_inline
I'm using python 3.9 and Django 4 .and when I try ti run migrate or runserver i get this error : Traceback (most recent call last): File "/workspace/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/usr/local/lib/python3.9/site-packages/django/utils/module_loading.py", line 57, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/nested_inline/admin.py", line 13, in <module> from django.utils.encoding import force_text I think it is about the package nested_inline despite it was working great. NOTE I'm running inside a dev container in VS-CODE -
How to print multiple HTMLCalendar built-in modules in Django
Actually, I didn't fully understand how HTMLCalendar, a built-in module provided by Django, works. I'm trying to print two Calendars on one page, both sides. The two Calendars each output different events. How to create two calendars that have the same function but output different events? First of all, the code below is modified code. But it throws an error. I tried to print two calendars, but four are printed and ('\n\n\n\n\n\n\n\n', ' is printed between the calendar tables. [event.html] <head> {% block title %} <title>Calendar</title> {% endblock %} </head> <body> {% block content %} <div class="row"> <h4>Calendar</h4> <span style="font-size:0.85em; float:right;"> <div style="display:inline-block;"></div> event1 &nbsp; <div style="display:inline-block;"></div> event2 &nbsp; <div style="display:inline-block;"></div> event3 &nbsp;</span> </div> <div> <br> <a class="btn btn-info" href="{% url 'leave:calendar' %}?{{ prev_month }}">Previous</a> <div style="float:right;"> <a class="btn btn-info" href="/leave/calendar/new/">Add</a> <a class="btn btn-info" href="{% url 'leave:calendar' %}?{{ next_month }}">Next</a> </div> </div> <div> {{calendar}} </div> <div> {{calendar_2}} ---> 'ADD' </div> {% endblock %} </body> [utils.py] from calendar import HTMLCalendar from .models import Leave from django.db.models import Q, F from django.db.models.functions import ExtractMonth class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, user=None): self.year = year self.month = month self.user = user super(Calendar, self).__init__() # formats a day as a td # filter events … -
Django - Annotate post query set data with if current user has "liked" the post
So I have this model model.py class Post(models.Model): uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) class LikePost(AbstractSimpleModel): creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="like_post") post = models.ForeignKey(Post, on_delete=models.CASCADE) class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) Then I also have this annotator for returning a bunch of data outside of the Post table annotator.py def query_to_full_post_data_serializer(post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), reply_count=Count('postreply', distinct=True), like_count=Count('likepost', distinct=True) ).prefetch_related( Prefetch('photo', Photo.objects.order_by('-created')), Prefetch('video', Video.objects.order_by('-created')) ) return FullPostDataSerializer(query_set_annotated, many=True) I'd like to return a field called "user_liked", which returns a boolean for each post in a query set that is True if the current logged in user has liked it. When the request comes in I get the current user making the request so I can get their uuid. I'd like to use that uuid to check if the user has liked a post in the query set. How do I check if the current logged in user has liked a Post object in a query set Django? -
How to include users image in model instance
So I have a custom user model class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) avatar = models.ImageField(default='default.jpg') lat = models.CharField(max_length=200, null=True) lng = models.CharField(max_length=200, null=True) and a post model class Post(models.Model): author = models.ForeignKey(User, on_delete=CASCADE) wanted = models.CharField(max_length=100) user_image = models.ImageField() How can I make it so that every time an instance of the Post model is created, the user_image is populated with the avater image for that associated user. Is that possible? -
how to delete forien-key Imagefield in django?
I am already using django-cleanup. But it works when imagefield was deleted. If imagefield is realted to a model like below. As long as I don't delete imagefield manually, It can't be working. from django.db import models class Listing(models.Model): title = models.CharField(max_length=25) class ListingImages(models.Model): listing = models.ForeignKey(Listing, default=None) image = models.ImageField() Listing can have many images which isn't fixed quantities. So I implemented like that. But now I have a problem with how I can find which image should be deleted. Lazy algorithm is just iterate every image data when post or put request. and delete not matched image which is related to Listing object. But it's too expensive I think. Is there any good solution? I was searching that 'delete foreign key image in django' this keyword. But there is no solution for me. -
Stop formset from rendering separate <form> tag - multiple forms one view Django
I am building a create a recipe page, with recipe details, ingredients and instructions. I have been trying to add a datalist to ingredient form for the last few days but now for some reason the recipe instruction form has started rendering inside it's own <form></form> tag and as such is not getting posted with the other recipe data on submit. I want to be able to submit all the recipe details, ingredients and instructions as one form, how can I stop the instruction formset from rendering tags? Inspect Image - notice recipe ingredients has no <form> tag even though it is rendered the exact same way: forms.py: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ['name', 'totalTime', 'calories', 'mainCategory'] class RecipeIngredientForm(forms.ModelForm): ingredientName = forms.CharField(required=True) def __init__(self, *args, **kwargs): super(RecipeIngredientForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Div(Field("ingredientName", placeholder="Chickpeas - only write the ingredient here"), css_class='col-6 col-lg-4'), Div(Field("quantity", placeholder="2 x 400"), css_class='col-6 col-md-4'), Div(Field("unit", placeholder="grams"), css_class='col-5 col-md-4'), Div(Field("description", placeholder="No added salt tins - All other information, chopped, diced, whisked!", rows='3'), css_class='col-12'), css_class="row", ), ) self.fields['ingredientName'].widget = ListTextWidget(data_list=Ingredient.objects.all(), name='ingredient-list') class Meta: model = RecipeIngredient fields = ['ingredientName', 'quantity', 'unit', 'description'] labels = { 'ingredientName': "Ingredient", "quantity:": "Ingredient Quantity", … -
How to serialize ManyToManyField
I want to serialize ManyToManyField but at the same time, I am looking for something which updates the same using ModelViewSet. I am able to serialize it but when I am updating it I am not able to. I know I can make a separate API for that but due to some requirements, I need to stick to one endpoint. Here is my code class ComponentSerializers(serializers.ModelSerializer): class Meta: model = coreModel.Component fields = '__all__' class MonitorSerializers(serializers.ModelSerializer): device = ComponentSerializers(read_only=True, many=True) class Meta: model = models.Monitor fields = '__all__' read_only_fields = ('id', 'created_at', 'updated_at',) and views.py is class MonitorViewSet(viewsets.ModelViewSet): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = models.Monitor.objects.all() filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter) filter_class = superFilter.MonitorFilters serializer_class = serializers.MonitorSerializers -
How fix "got an unexpected keyword argument 'content_object'" when creating object with generic relation
I have generic relations set up between Facility and Phone. class Facility(TimeStampedModel): name = models.CharField(max_length=200, db_index=True, unique=True) phone = GenericRelation("Phone", related_query_name="facility") class Phone(TimeStampedModel): value = models.CharField(max_length=15) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() However, when I try to execute: facility = Facility.objects.create(name=row["name"]) phone = Phone.objects.create(value=row["phone"], content_object=facility) I get an exception: Phone() got an unexpected keyword argument 'content_object' -
Not Found: /i18n/setlang/&c=jQuery112409010789662534471_1639045647507
I am trying to translate a Django app using the built-in i18n. When I switch the language with the form in index.html, I got an error like this. Not Found: /i18n/setlang/&c=jQuery112409010789662534471_1639045647507 [09/Dec/2021 15:57:40] "GET /i18n/setlang/&c=jQuery112409010789662534471_1639045647507?csrfmiddlewaretoken=hwhDPrPOYd4Jdp5ay6tcPDXy3Zmzc0fJDSIrovR4CofrOj8oZRYvKtJkGJAbmTEK&language=es&_=1639045647517 HTTP/1.1" 404 2552 I've also changed the USE_I18N to true in the settings.py file and added the following code into the urls.py file. urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('admin/', admin.site.urls), path('accounts/', include(accounts.accounturls), )+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I also defined a list of allowed languages in the settings.py, as instructed by the tutorial. Also created an HTML page for selecting the language. <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {{LANGUAGE_CODE}} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{language.code}}" {% if language.code == LANGUAGE_CODE %} class="active"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <button type="submit" value="Go">Go</button> </form> Can anyone say a solution for this error? -
serializer method to set the value of an attribute doesn't work in a post request. I am using Django Rest Framework
I have a model which has an attribute "transaction_id" which is a customized ID field and it's value has to be calculated in order to be saved in the database. I have a model: class Transaction(models.Model): field = models.IntegerField(default=0) transaction_id = models.UUIDField(unique=True) This is the seriaizer: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = '__all__' read_only_fields = ['id', 'transaction_id'] def set_tn_number(self): tn_number = "some_string/" #I have to perform some calculation in order to get the relevant value tn_number = tn_number + str(10) return tn_number Now in my post method of the view, i am performing the following: def post(self, request): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.tn_number = serializer.set_tn_number() serializer.save() message = {'message': "Transaction Created Successfully"} return Response(message, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But i am still getting integrity error: NOT NULL constraint failed: transaction_transaction.transaction_id Can someone please help me with this? Thank you for your time -
Task freezes Celery + django + supervisor + redis
I've a Django app served by Gunicorn with Celery using celery-beat that's being launched by Supervisord Celery task hangs sometimes(maybe once a week) Software versions: Redis server v=4.0.9 celery 5.1.2 django 3.2 django-celery-beat 2.2.1 I put configuration files here https://gist.github.com/SergSm/43a1554b57968c5e35776ad55fdcf0ab What I do Everytime task freezes I run celery -A app inspect active to see an id of a frozen task so then I run python manage.py shell in my django directory to see a state of the running task >>> from app.celery import app >>> from celery.result import AsyncResult >>> result = AsyncResult(id='9bf01312-c2ff-4b1e-9fd5-6fa6b0c458f2', app=app) >>> result.state 'PENDING' the task is pending and can't be finished even by executing sudo supervisorctl stop latest_conf_celery so I have to kill -9 all Celery processes I've a suspicion that the reason can be in the name of the worker spawned by gunicorn. I made this conclusion due to the fact when I execute ps -aux | grep celery I see: serg 8641 0.2 8.4 262284 84948 ? Sl 10:09 0:05 /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/python /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/celery -A app worker -P threads --beat -S django.schedule -l INFO serg 8643 0.0 7.6 185800 76804 ? S 10:09 0:01 /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/python /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/celery -A app worker -P threads --beat -S django.schedule -l … -
Django - trying to use a queryset to create a queryset on a different model
I want to create a queryset for my model Student. I then want to use the students from this queryset to create a new queryset for my model DoNotPick. models: class Classroom(models.Model): classroom_name = models.CharField(max_length=30) students = models.ManyToManyField(Student) def __str__(self): return self.classroom_name class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student_first = models.CharField(max_length=30) fullname = models.CharField(max_length=60) class Meta: ordering = ['student_first'] def __str__(self): return self.fullname class DoNotPick(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) do_not_pick = models.BooleanField(default=False) student = models.ForeignKey(Student, on_delete=models.CASCADE) The first queryset I create is: s = Student.objects.filter(classroom = some_pk) One thing I tried which didn't work is (from here in the docs): values = s.values_list('pk', flat=True) dontpick = DoNotPick.objects.filter(student__in=list(values)) On my development db, s returns 18 objects which is expected. However, dontpick seems to return all objects, it's not getting filtered. It returns all 26 objects in the db. I had some success with this view, I know that the donotpicks set is the correct size (18 objects): def donotpick(request, classroom_pk): classblock = get_object_or_404(Classroom, pk=classroom_pk) students = Student.objects.filter(classroom=classblock) dnp = DoNotPick.objects.all() donotpicks = set() for s in students: donotpicks.add(dnp.filter(student=s)) print(len(donotpicks)) DoNotPickFormSet = modelformset_factory( DoNotPick, fields=('do_not_pick',), extra=0) formset = DoNotPickFormSet(request.POST, queryset=donotpicks) if request.method == 'POST': formset = DoNotPickFormSet(request.POST, queryset=donotpicks) if formset.is_valid(): … -
ImportError: Could not import 'users.authenticate.jwt_response_payload_handler' for API setting
Set custom return error when using rest framework jwt token verification,ImportError: Could not import 'users.authenticate.jwt_response_payload_handler' for API setting 'JWT_RESPONSE_PAYLOAD_HANDLER'. users.authenticate def jwt_response_payload_handler(token, user=None, request=None): return { 'code': status.HTTP_200_OK, 'data': token, 'message': 'Success' } setting JWT_AUTH = { # Token失效时间 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7), # Token前缀 'JWT_AUTH_HEADER_PREFIX': 'JWT', # response中token的payload的部分处理函 'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.authenticate.jwt_response_payload_handler' } At that time commented out 'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.authenticate.jwt_response_payload_handler' can successfully run to obtain token Traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site- packages\rest_framework\settings.py", line 177, in import_from_string return import_string(val) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\lk\r\python\r\users\authenticate.py", line 4, in <module> from rest_framework_jwt.views import ObtainJSONWebToken ImportError: cannot import name 'ObtainJSONWebToken' from partially initialized module 'rest_framework_jwt.views' (most likely due to a circular import) (C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_jwt\views.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) … -
django 'Loginform' object has no attributes get_user
i have multiuser type app with usertype and usertype b i am trying to create a loginform where most of of login is and should be in form am getting this error forms.py class Loginform(forms.Form): username = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") try: user = models.User.objects.get(username=username) if user.user_a: if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError("Password is wrong.")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError("User does not exist.")) views.py class UseraView(LoginView): template_name = 'login.html' form_class = Loginform success_url = reverse_lazy("home") Note:There are some other stack post related to this which didn't help as those are for single type user here in my case it is multi user application so please dont provide any related links -
How I can check whether a user's email is verified or not in the Django template
I am using Django all auth, to implement email-based login, I am able to verify users with confirmation email but I want to render a conditional template for verified users, I tried this but it didn't work. {% if user.email_verified %} verified {%else%} not verified {%endif%} -
Sortable JS breaks upon htmx rendering a partial
I am trying to implement a drag and drop sortable list using SortableJS and htmx. I have it working once, but after dragging and dropping the first element (and the partial being re rendered) I can no longer use the drag and drop functionality. When a partial isn't rerendered the drag and drop functionality works as expected. I have tried using htmx.on("htmx:load",... as well as putting the script in the partial. I've used diff to check the differences between the html before and after the partial is rendered and as far as I can tell the only difference outside the reordered list is the csrf token. Any help would be appreciated! From views.py: def sort(request): event_pks_order = request.POST.getlist('event_order') events=[] for idx,event_pk in enumerate(event_pks_order,start=1): event = Event.objects.get(pk=event_pk) event.event_number = idx event.save() events.append(event) return render(request,'timing/partials/eventlist.html',{'events':events}) From eventlist.html: <form class="sortable list-group" hx-trigger="end" hx-post="{% url 'sort' %}" hx-target="#event-list"> {% csrf_token %} <div class="htmx-indicator">Updating...</div> {% for event in events %} <div> <input type="hidden" name="event_order" value="{{event.pk}}"/> <li class="list-group-item">{{event.event_number}} {{event.event_name}} </li> </div> {% endfor %} </form> From base.html: <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) htmx.onLoad(function(content) { var sortables = content.querySelectorAll(".sortable"); for (var i = 0; i < sortables.length; i++) { var sortable … -
Gunicorn Error when deploying python app on Contabo server unrecognized arguments
Dec 13 03:25:40 vmi720345.contaboserver.net systemd[1]: Started gunicorn daemon. Dec 13 03:25:41 vmi720345.contaboserver.net gunicorn[30601]: usage: gunicorn [OPTIONS] [APP_MODULE] Dec 13 03:25:41 vmi720345.contaboserver.net gunicorn[30601]: gunicorn: error: unrecognized arguments: -access-logfile /run/gunicorn.sock textutils.wsgi:appliction Dec 13 03:25:41 vmi720345.contaboserver.net systemd[1]: gunicorn.service: Main process exited, code=exited, status=2/INVALIDARGUMENT Dec 13 03:25:41 vmi720345.contaboserver.net systemd[1]: gunicorn.service: Failed with result 'exit-code'. root@vmi720345:~/projectdir# client_loop: send disconnect: Connection reset by peer -
Problem with response values with join in django query?
i have this models. class Product(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) PublicationDate = models.DateField() trend = models.IntegerField() class User_list(models.Model): product_id = ForeignKey(Product, on_delete=models.CASCADE) userid = models.IntegerField() i make a join query with select related data = User_list.objects.select_related('product_id') but the response don't get me Product fields value. it's get me only User_list values, like this "[{\"model\": \"app.user_list\", \"pk\": 1, \"fields\": {\"product_id\": 11916, \"userid\": 9}}]" What's the problem?