Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve error code: RelatedObjectDoesNotExist
class Following(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='following', unique=False, verbose_name=('User'), on_delete=models.CASCADE) following_user = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=('Following'), related_name='following_user') created_on = models.DateTimeField(default=timezone.now) class FollowingSerializer(serializers.ModelSerializer): new_following = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),required=True,write_only=True) class Meta: model = Following fields = [ 'id', 'user', 'following_user', 'new_following', 'created_on' ] read_only_fields = ['following_user'] def create(self, validated_data): user = validated_data['user'] new_following = validated_data['new_following'] user.following.following_user.add(new_following) new_following.followers.following_user.add(user) return user.following class FollowingAPIView(mixins.CreateModelMixin, mixins.DestroyModelMixin,generics.GenericAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = FollowingSerializer def get_queryset(self): queryset = Following.objects.all() return queryset def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(self, request, *args, **kwargs) -
Django Azure Logout Session
Is there any formal way to log out of both Django + Azure AD B2C Session? Clicking "Logout" redirects to the default logout page. After that, clicking "log back in" or simply entering the home page in the url takes the user right back to the home page because the Azure session is not actually ended. Using django-oidc-provider + mozilla-django-oidc packages. Azure App Config Front Channel URL: https://my-site:myport/admin/logout Settings.py OIDC_SESSION_MANAGEMENT_ENABLE = True OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY = 'test' OIDC_OP_LOGOUT_URL_METHOD = "testmodule.auth.logout" logout function def logout(request): print("custom logout request reached") **# Never Reached** # I'm not sure if this is the correct token to be accessing id_token = str(request.COOKIES['csrftoken']) id_token_hint = f'id_token_hint={id_token}' redirect_url = "https://login.windows.net/my-tenant-id/oauth2/v2/logout?" redirect_url = redirect_url + id_token_hint + "&post_logout_redirect_uri=" + request.build_absolute_uri("/admin/logout/") print(f'redirect_url: {redirect_url}') return redirect_url urls.py class LogoutView(OIDCLogoutView): print("LogoutView Reached") def get(self, request): print("Get Call") **# Never Reached** return self.post(request) def post(self, request): print("Post Call") **# Never Reached** """Log out the user.""" logout_url = self.redirect_url #if request.user.is_authenticated: print("Reached Authenticated") **# Never Reached** # Check if a method exists to build the URL to log out the user # from the OP. logout_from_op = self.get_settings('OIDC_OP_LOGOUT_URL_METHOD', '') if logout_from_op: logout_url = import_string(logout_from_op)(request) # Log out the Django user if they were logged in. … -
Soap signature with JKS in Django
I am working on a project using Django and i need to send a soap request but i have to sign it using a 'JKS' file and it's password and alias. I've tried working with suds and zeep packages. But I can't find any example in python to help me understand how to do that. Can some one help me? -
Elastic Beanstalk Django app deployment 502 Bad Gateway Server not running (No module named: 'application')
I deployed an application to AWS via Elastic Beanstalk, and when I finished pushing the project to aws (Elastic Beanstalk), I am faced with perpetual 502 Bad Gateway errors (probably because the Django app server never actually started, and Nginx can't proxy us through). Looking at the logs, I found a weird error that seems very specific, and erroneous. It looks like so: Traceback (most recent call last): Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Dec 13 09:00:10 ip-172-31-35-65 web: worker.init_process() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Dec 13 09:00:10 ip-172-31-35-65 web: super().init_process() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Dec 13 09:00:10 ip-172-31-35-65 web: self.load_wsgi() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Dec 13 09:00:10 ip-172-31-35-65 web: self.wsgi = self.app.wsgi() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Dec 13 09:00:10 ip-172-31-35-65 web: self.callable = self.load() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Dec 13 09:00:10 ip-172-31-35-65 web: return self.load_wsgiapp() Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Dec 13 09:00:10 ip-172-31-35-65 web: return util.import_app(self.app_uri) Dec 13 09:00:10 ip-172-31-35-65 web: File "/.../python3.8/site-packages/gunicorn/util.py", … -
Django DATABASES settings
I understand if you connect to your MongoDB database via pymongo, you should remove the DATABASES section in your settings.py file, which I have done, but I get this: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Apparently, pymongo does not replace a relational database with MongoDB. It is simply a facility allowing you to access a MongoDB in addition to your regular database; meaning I still need my databases settings... I know my connection string and database name and collection name, but what should the DATABASES section look like in my settings.py file? On https://docs.djangoproject.com/en/2.0/ref/settings/#databases and a few other posts and articles, only settings for sqlite3 and postgresql and mysql and oracle are mentioned. I cannot seem to find the right setting for 'ENGINE': 'django.db.backends.mongodb' How can I use a MongoDB database then? What goes in the xxx.backends.xxx section? -
What is the proper method to pass data in class-based django views?
I'm looking for a proper or a basic method to pass the result of a filter in a class to another page which is in another class and temporarily use it for a purchase class home(View): def get(self, request): return render(request,'home.html') def post(self, request): # rm = room.objects.all().filter(#filter) class results(View): def get(self, request): rm #from home return render(request,'result.html',{'rm':rm}) def post(self, request): # -
How to use prefetch_related 2 times?
view.py def CompanyAdDetail(request, post_id): ad_detail = get_object_or_404(Ad_company, idx=post_id) is_display = ad_detail.is_display if is_display != '1': return redirect('/') ad_detail.hits += 1 ad_detail.save() if ad_detail.user_idx == request.user: #작성자가 글을보면 q = Q() q &= Q(project_idx = post_id) apply_list = Ad_company_apply.objects.filter(q).select_related('user_idx').prefetch_related('userportfolio').order_by('-idx') else: apply_list = None return render(request, 'project/company_ad_detail.html', {"ad_detail":ad_detail, "apply_list":apply_list}) model.py class Ad_company_apply(models.Model): idx = models.AutoField(primary_key=True) project_idx = models.ForeignKey( Ad_company, db_column='project_idx', on_delete=models.CASCADE ) user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE, ) content = models.TextField() date = models.DateTimeField(default=datetime.now, blank=True) budget = models.BigIntegerField() term = models.IntegerField() class UserPortfolio(models.Model): idx = models.AutoField(primary_key=True) user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) subject = models.CharField(max_length=255) client_name = models.CharField(max_length=255) client_service = models.CharField(max_length=255) client_category = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() content = models.TextField() write_date = models.DateTimeField(auto_now = True) update_date = models.DateTimeField(auto_now = True) is_file = models.CharField(max_length=1) class Meta: managed = False db_table = 'account_user_portfolio' I want to count apply list in users portfolio. but I think I need to use prefetch_related 2 times. and I did it. but Always showed error. is an invalid parameter to prefetch_related() How can I use this as good? -
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 …