Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model class method using wrong `self`
When I navigate to the admin page or my generic view for this model Loan I get the following error: File "library_app/catalog/models.py", line 118, in __str__ return f'{self.book.title} ({self.id})' AttributeError: 'NoneType' object has no attribute 'title' I've managed to track this down to the __str__ function of my BookInstance class. class Loan(models.Model): book_instance = models.OneToOneField(BookInstance, on_delete=models.RESTRICT) user = models.ForeignKey(User, on_delete=models.RESTRICT) date = models.DateField( default=django_timezone.now, help_text='Date borrowed' ) due_back = models.DateField( default= django_timezone.now() + datetime.timedelta(30), help_text='Date due to be returned' ) returned_date = models.DateField(null=True, blank=True, help_text='Date book was returned') class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) book = models.ForeignKey(Book, on_delete=models.RESTRICT, null=True) LOAN_STATUS = ( ('m', 'Maintence'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book Availability' ) def __str__(self): return f'{self.book.title} ({self.id})' I'm guessing that in these pages it when the __str__ method is called the wrong self variable is being used. I have no idea how to fix this so any tips would be appreciated. -
Atomic transaction in django
I have a view which updates object in database. Should I make this view atomic ( @transaction.atomic)? I want to eliminate data races (for example two requests update value at the same time) My code: @api_view(["POST"]) @transaction.atomic def employee_increase(request): logger.info(f"Increase sallary: {request.data}") serializer = IdSerializer(data=request.data) serializer.is_valid(raise_exception=True) employee = get_object_or_404(Employee, pk=request.data["id"]) old_sallary = employee.sallary employee.sallary = int(old_sallary * (1 + int(request.data["increase_percent"]) / 100)) employee.save() -
Django requirements file package is not installed in the selected environment
I want to create a live chat project with Django and Nextjs and I'm running into a problem. I'm not sure why after installing channels and channels-redis , when I try to import the package inside the files in not getting recognized ( import channels.db could not be resolved ), and in my requirements.txt file those 2 packages show as package is not installed in the selected environment . And I'm getting this error WebSocket connection to 'ws://127.0.0.1:8000/' failed: (I've tried with ws://localhost:8000/ too) when my frontend tries to access the backend. Please let me know what can I do to fix this. Thank you! I've tried to create this project with virtualenv and poetry, and I get the same problem with both. This is the code I have for the chat : settings.py file: WSGI_APPLICATION = 'backend.wsgi.application' ASGI_APPLICATION = "backend.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", "6379")], }, } } asgi.py file import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django_asgi_app = get_asgi_application() # application = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) routing.py file … -
How to make constraints at the model level so that two model fields cannot be equal to the same?
I need a check at the model or database level that user_1 is not equal to user_2 That it's not the same user It is important for me that it is impossible to create such a record in the database class SomeModel(Model): user_1 = Foreignkey(...) user_2 = Foreignkey(...) I tried to look for various validators, but at the model level, I can only fetch the data of a specific field. I need something similar to UniqueConstraint but without the ability to create at least 1 such record -
character encoding when translating Django and pushing to bitbucket
Using Linux Fedora, and PyCharm both English versions 1, I am in the process of translating the content using the i18n built-in Django. When I write python manage.py compilemessages I get: 'latin-1' codec can't encode character '\u201c' in position 5: ordinal not in range(256) This '\u20ic' refers to Double quotes. The file to translate has double quotes. When I push to bitbucket, even though it does push it, I get this message xkbcommon: ERROR: /usr/share/X11/locale/iso8859-1/Compose:49:29: string literal is not a valid UTF-8 string I went to check the file encodings in PyCharm and was disgusted to see that it was not UTF-8 but some ascii variant. I changed to UTF-8 but nothing happened, I can't compile the messages in the .po file This is a snippet of the Django file that because it has double quotes, it can't be compiled #: scaffoldapp/templates/index.html:279 msgid "Life is life." msgstr "la vida es la vida" #: templates/account/account_inactive.html:5 #: templates/account/account_inactive.html:8 msgid "Account Inactive" msgstr "" I already explained above what I had tried -
django admin login CSRF verification failed. Request aborted
I am building an django application. Everything is working locally. But after uploading it to the production server with DEBUG=True. I am getting csrf error when trying to login to the admin panel. My site is serving on https://api.example.com. My settings.py: ALLOWED_HOSTS = ["*"] CSRF_TRUSTED_ORIGINS = ["https://*.example.com"] CSRF_COOKIE_DOMAIN = '.example.com' CSRF_COOKIE_SECURE = True What is the problem here? -
How to update widget attribute based on user role in Django
I have this custom widget: class RelatedFieldWidgetCanAdd(widgets.Select): def __init__(self, related_model, related_url=None, can_add_related=True, *args, **kw): self.can_add_related = can_add_related super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw) if not related_url: rel_to = related_model info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = 'admin:%s_%s_add' % info # Be cautious, as "reverse" is not allowed here self.related_url = related_url def render(self, name, value, *args, **kwargs): self.related_url = reverse(self.related_url) output = [u'<div class="d-flex">'] output.append(super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)) if self.can_add_related: output.append(u'<a href="%s?_to_field=id&_popup=1" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (self.related_url, name)) output.append(u'<img src="%sadmin/img/icon-addlink.svg" width="20" height="50" class="pb-2 mx-2" alt="%s"/></a>' % (settings.STATIC_URL, _('Add Another'))) output.append(u'</div>') return mark_safe(u''.join(output)) And this is how I'm using it in form.py: class LeaveForm(forms.ModelForm): ... leave_type = forms.ModelChoiceField( queryset=LeaveType.objects.all().order_by('-pk'), empty_label='--------', widget=RelatedFieldWidgetCanAdd( LeaveType, related_url='leave_type_add' ) ) Now, if I'm logged in as a superuser in my dashboard, I can see the + button to create a related object. That's fine, but when I'm logged in as a normal user, it allows me to add related data. I know it's because I've set can_add_related to True by default. I want to update it while rendering it by checking the user's is_superuser or is_admin attribute. I tried to access the Request inside the widget, but I don't have access to the Request object. So, I … -
MultiValueDictKeyError at
list_entries() save_entries() get_entry() above functions are pre defined at util.py file. This is views.py code for saving a new page. Defining function for Creating new page. def createNewPage(request): if request.method == "GET": return render(request, "encyclopedia/createNewPage.html") else: title = request.POST['title'] content = request.POST['content'] titleExist = util.get_entry(title) if titleExist is not None: return render(request, "encyclopedia/error.html",{ "massage": "The page you would like to add is already exist." }) else: util.save_entry(title, content) html_content = convert_md_to_html(title) return render(request, "encyclopedia/entry.html",{ "title": title, "content": html_content }) This is showing in Django MultiValueDictKeyError at /createNewPage/ 'title' Request Method: POST Request URL: http://127.0.0.1:8000/createNewPage/ Django Version: 4.2.4 Exception Type: MultiValueDictKeyError Exception Value: 'title' Exception Location: C:\Users\fayek\Desktop\Django\venv\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: encyclopedia.views.createNewPage Python Executable: C:\Users\fayek\Desktop\Django\venv\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\fayek\Desktop\Django\wiki', 'C:\Program Files\Python311\python311.zip', 'C:\Program Files\Python311\DLLs', 'C:\Program Files\Python311\Lib', 'C:\Program Files\Python311', 'C:\Users\fayek\Desktop\Django\venv', 'C:\Users\fayek\Desktop\Django\venv\Lib\site-packages'] I'm working on a project of CS50-Web course(Projet-01[wiki]). when I'm trying to save a new page it's leading me to this error. I couldn't figure it out why this error occurring. -
Show models.DateField value in django template
I have to render the value of models.DateField() in the django template for a countdown functionality. For the DateField I will add the value in the django admin and I need that value in the Front-End. I tried to access the value by writing obj.field(DateField) but it doesn't render the value. Please have a look at the code below, you will understand easily. Any help would be greatly appreciated. I have a model like this: class FeaturedProduct(BaseModel): type = models.CharField(max_length=255, choices=ProductTypeChoices.choices) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='featured_products') daily_deal_countdown = models.DateField(blank=True, null=True) class Meta: unique_together = ('type', 'product') def __str__(self): return str(self.product) + '-' + str(self.type) In the views context I passing the daily_deals like this: context = {'products': products, 'featured': featured_products, 'bestseller': bestseller, 'new_arrival': new_arrival, 'daily_deal':daily_deal, 'cartItems': cartItems, 'cartTotal': cartTotal} In the template I am rendering like this: {% for product in daily_deal %} <div class="daily-deal-countdown" data-countdown-date="{{ product.daily_deal_countdown }}"></div> {% endfor %} In the above template the value for the field daily_deal_countdown shows nothing even though my Back-End has the value. Please help me get through. -
table dashboard_data has no column named end_year in Django
admin.py from .models import Data admin.site.register(Data) models.py class Data(models.Model): end_year = models.CharField(max_length=150, blank=True, null=True) intensity = models.IntegerField( blank=True, null=True) sector = models.CharField(max_length=150, blank=True, null=True) topic = models.CharField(max_length=150, blank=True, null=True) insight = models.CharField(max_length=150, blank=True, null=True) url = models.CharField(max_length=150, blank=True, null=True) region = models.CharField(max_length=150, blank=True, null=True) start_year = models.CharField(max_length=150, blank=True, null=True) impact = models.CharField(max_length=150, blank=True, null=True) added = models.CharField(max_length=150, blank=True, null=True) published = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) relevance = models.IntegerField( blank=True, null=True) pestle = models.CharField(max_length=150, blank=True, null=True) source = models.CharField(max_length=150, blank=True, null=True) title = models.CharField(max_length=150, blank=True, null=True) likelihood = models.IntegerField(blank=True, null=True) def __str__(self): return self.id views.py import json import os from django.shortcuts import render from django.templatetags.static import static from Blackcoffer.settings import BASE_DIR, STATIC_URL from .models import Data def dashboard(request): ROOT_FILE = os.path.join(BASE_DIR, STATIC_URL, 'jsondata.json') # json_data = open(ROOT_FILE) # json_load = json.load(json_data) with open(ROOT_FILE, 'r', encoding="utf-8") as data: parsed_json = json.load(data) for result in parsed_json: Data.objects.create( end_year = result['end_year'], intensity = result['intensity'], sector = result['sector'], topic = result['topic'], insight = result['insight'], url = result['url'], region = result['region'], start_year = result['start_year'], impact = result['impact'], added = result['added'], published = result['published'], country = result['country'], relevance = result['relevance'], pestle = result['pestle'], source = result['source'], title = result['title'], likelihood = result['likelihood'], ) … -
How to filter models by currently authenticated user using ModelViewSet in DRF
I'm working on Django project with Django Rest Framework. I have a model called Server and I want to filter the queryset by the currently authenticated user, but only if "by_user=true" is provided in query params. I'm using ModelViewSet to create the API endpoints. I have overrided the get_queryset and it works fine. But when I return is using super().list(request, *args, **kwargs) it returns the queryset without filtering. Only way I found to return the filtered queryset is by using Response(serializer.data). But I want to use the super().list() method. Any help would be appreciated. Thanks in advance. Here is Server Model: class Server(Model): name = CharField(max_length=100) owner = ForeignKey( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="server_owner" ) category = ForeignKey(Category, on_delete=CASCADE, related_name="server_category") description = CharField(max_length=300, blank=True, null=True) members = ManyToManyField( settings.AUTH_USER_MODEL, related_name="server_members", blank=True ) def __str__(self): return self.name Here's Serializer: class ServerSerializer(ModelSerializer): class Meta: model = Server fields = "__all__" And Here's ViewSet: class ServerViewSet(ModelViewSet): queryset = Server.objects.all() serializer_class = ServerSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = ServerFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) by_user = request.query_params.get("by_user", False) if by_user: queryset = queryset.filter(members=request.user) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) # return super().list(request, *args, **kwargs) -
Multiple ManyToManyFields with same through table
I have an Organization model and a custom link table model linking it to User like this: class Organization(models.Model): name = models.CharField(max_length=255) class OrganizationUser(models.Model): organization = models.ForeignKey( Organization, related_name="organization_users", on_delete=models.CASCADE ) user = models.ForeignKey( "users.User", related_name="organization_users", on_delete=models.CASCADE ) link_type = models.CharField( choices=LinkTypeChoices.choices, max_length=64, default=LinkTypeChoices.MEMBER ) To make it easier to query through to User from Organization, I want to set up a ManyToManyField with through="app_name.OrganizationUser". However, it would be nice to automatically filter this queryset based on the value of OrganizationUser.link_type. Is there any reason why I shouldn't or can't set up two ManyToManyFields on Organization pointing to User through OrganizationUser with different limit_choices_to values filtering for different values of OrganizationUser.link_type? For example, I would like to be able to write Organization.owners.all() and Organization.members.all(), running both through the same link table, and get different results. -
How to add current user as foreign key in Django serializer
I am writing a Serializer for my log model which contain User as a foreign key. How can I add the current user in log Serializer. Here is my log model: class Log(models.Model): id = models.AutoField(primary_key=True, null=False) title = models.TextField(null=False) user = models.ForeignKey(User, on_delete=models.CASCADE) impact = models.IntegerField() ease = models.IntegerField() confidence = models.IntegerField() def __str__(self): return f"{self.title},{self.pk}" Here is my log serializer: class LogSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(source='user.id' ,queryset=User.objects.all(), many=False) class Meta: model = Log fields = ['id','user','title','ease','impact','confidence'] but this is giving validation error. "user": [ "This field is required." ] Here is my views: class logsApiView(APIView): def post(self, request, id=None,format=None): data = request.data serializer = LogSerializer(data=data) serializer.is_valid(raise_exception=True) print('hey') serializer.save() response = Response() response.data = { 'message': 'Todo Created Successfully', 'data': serializer.data } return response -
RemoteDisconnected from celery task on docker when calling long running endpoints
I have a Django application running on docker-compose. In one of my background celery task, I am calling a Cloud Run endpoint. This endpoint takes a long time to complete: 60-80 seconds. celery task -- request -> Cloud Run ... process ... celery task <- response - Cloud Run I have confirmed on Cloud Run that the time out is set to 300 seconds, but I am seeing that the Celery task is raising ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')). Even when the Cloud Run itself is returning 200, my task is raising this error. Checking the logs on the celery side, I see that this error is raised when 61 seconds has passed from when the request was made. Is there a configuration on some layer that is terminating my request? I checked that the requests module itself does not a timeout unless specified, so I am suspecting something else. -
Django - How to use the results of a Django view query as an input to a different Django view query
I am new to coding / Django and apologize in advance if this question has been asked before. I have searched StackOverflow and haven't been able to find the answer I'm looking for. I am building a Django application that allows a user to search for a property record via a unique identifier (referred to as APN in my Django model). In addition, the application is designed to deliver consumer population data for the state in which a given property is located (e.g. California, Florida, etc.) When a user submits their APN search query, the application generates a page that displays the Address, City, and State. The state field is meant to be linked to a separate page that displays the state-level population data described above. For example, if the State for a given property is "Colorado", the user should be directed to a page that displays population data for Colorado (as opposed to a different state) when they click the link. Here are my models: class AnnualPopulation(models.Model): State = models.CharField(max_length=2, blank=True, null=True) Population_2022 = models.IntegerField(blank=True, null=True) Population_2023 = models.IntegerField(blank=True, null=True) class PropDots2(models.Model): APN = models.CharField(max_length=250, blank=True) Address = models.CharField(max_length=250, blank=True) City = models.CharField(max_length=250, blank=True) State = models.CharField(max_length=250, blank=True) Here … -
Django error on fly io app: django.db.utils.OperationalError: no such table: django_session
I have a Django application deployed on fly.io Sometimes when I do a database operation like login, signup, or a CRUD operation, it returns the error "django.db.utils.OperationalError: no such table: django_session". I think it's important to note I'm using sqlite3 I logged in to the fly ssh console and executed the commands: python manage.py makemigrations python manage.py migrate But the error is still showing almost every time I do a database operation from the UI of my app -
have django models come with defaults
I have some Django models that my site relies on very heavily, it dose not even matter what is in the models just that there is something in them. 2 of my pages get markdown data from the models and then convert them to HTML and display it on the page. I tried messing around with the default parameters in some of the models but I still have to go by the admin dashboard to set things up. Is there a way that I can have the database come with pre-setup objects when I run python manage.py migrate? my models from django.db import models # Create your models here. class apikey(models.Model): key = models.CharField(default="") class video(models.Model): official_name=models.CharField(max_length=200) date = models.DateField() vid = models.CharField() thumbnail_url = models.CharField(max_length=1000) biblestudy = models.BooleanField() this is the models file from my other app from django.db import models # Create your models here. class message(models.Model): visitmessage = models.TextField(default="# hi") ourvision = models.TextField(default="# hi") -
What is wrong with the code? Register the product id and passwords
Work on a form django to register, which is the product ID, user name, password, and password confirmation. A message always appears that the product ID is incorrect, or the passwords do not match, even though all the entries are correct. def Registration(request): if request.method == "POST": productid = request.POST.get ("productid") username = request.POST.get ("username") password = request.POST.get ("password") re_password = request.POST.get ("productid") if password != re_password: messages. error (request, "Password is not Matching") return HttpResponseRedirect ("Registration") elif productid != ("05Md87fC36ya2B8i"): messages. error (request, "Product ID is not Correct") return HttpResponseRedirect ("Registration") else: act = Registrations () act. productid = productid act. username = username act. password = password act. re_password = re_password act.save() messages. success (request, "Your account has been successfully created") return HttpResponseRedirect ("company") else: return render (request,"Registration\Registration.html") ` <div class="card p-3 login-border"> <span class="text-center mt-3 text-pluse"><strong >Registration</strong></span> <form method="POST"> {% csrf_token %} <div class="input-group mb-2 mt-4"> <input type="password" class="form-control" name="productid " id="productid" placeholder="product Id" required> </div> <div class="input-group mb-2 mt-4"> <input type="text" class="form-control" name="username " id="username" placeholder="Your Username"required> </div> <div class="input-group mb-2 mt-4"> <input type="password" class="form-control" name="password" id="password" placeholder="Your password"required> </div> <div class="input-group mb-2 mt-4"> <input type="password" class="form-control" name="re_password" id="re_password" placeholder="Confirmation Your password" required> </div> <div class="form-check … -
Chained dropdown not working with HTMX and django
Hi guys I'm basically experimenting with HTMX and django to create a chained dropdown, the thing is that i don't really understand what's going on because I can't find the error in the code. from django import forms from django.shortcuts import render from ..models import UserLicense, CompanyInfo class PruebaForm(forms.Form): company = company = forms.ModelChoiceField( queryset=CompanyInfo.objects.all(), widget=forms.Select(attrs={"hx-get": "load_users/", "hx-target": "id_user"}) ) user = forms.ModelChoiceField( queryset=UserLicense.objects.none(), ) def locationview(request): form = PruebaForm () return render(request, 'template_de_prueba.html', {"form": form}) def load_users(request): company_id = request.GET.get('company') users = UserLicense.objects.filter(company_id=company_id) return render(request, 'users_dropdown_list_options.html', {'users': users}) At this point this peace of code should be bringing the data from the url "load_users/" when selecting the company but the thing is that it's not doing it and i don't understand why this is the template for the form {% extends "main_page_layout.dj.html" %} {% block content %} <form method="post"> {% csrf_token %} {{form.as_p}} </form> {% endblock %} this is the template for getting all the usernames {% for user in users %} <option value={{user.id}}>{{user.user_name}}</option> {% endfor %} and these are the two main models class CompanyInfo(models.Model): """Company information model.""" name = models.TextField(primary_key=True, blank=False, null=False) country = models.TextField(blank=True, null=True) contact_person = models.TextField(blank=True, null=True) contact_person_email = models.TextField(blank=True, null=True) def __str__(self): return … -
drf_spectacular schema annotation for optional serializer return type
I have a Django Rest Framework ModelSerializer with the following SerializerMethodField: def get_segments(self, obj): segments = models.Segment.objects.filter(obj=obj) if segments: return SegmentSerializer(segments, many=True).data I'm trying to use drf_spectacular's extend_schema_field to annotate the return type. @extend_schema_field(SegmentSerializer), is close, but my function can also return None, so I want to do something like @extend_schema_field(SegmentSerializer | None), which doesn't work. Is there a way to use a serializer type in extend_schema_field while marking it as nullable? -
Unique Constraint Failed: Authentication_authprofile.user_id, Anyone to help me
Am creating a user profile with custom model Fields. But am getting an error if l try to submit The form. UNIQUE constraint failed: Authentication_authprofile.user_id Am not seeing any error in my Code but anyone to help me and solve it. views.py def userprofile(request): url= request.META.get('HTTP_REFERER') if request.method == 'POST': user_profile = AuthProfile() if AuthProfile.objects.filter(user_id=request.user.id).exists(): avatar = request.POST.get('avatar') gender = request.POST.get('gender') country = request.POST.get('country') user_profile.avatar = avatar user_profile.gender = gender user_profile.country=country user_profile.user_id=request.user.id user_profile.save() return redirect('/') return render(request, 'authentification/auth-policy/user-dashboard.html') Models.py class AuthProfile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, unique=True) avatar=models.ImageField(default='avatar.jpg',upload_to='profile_avatar') gender =models.CharField(max_length=10, blank=True, null=True) country=models.CharField(max_length=50, blank=True, null=True) def __str__(self) -> str: return f'{self.user.username} Profile' @receiver(post_save, sender=User) def create_auth_profile(sender, instance, created, **kwargs): if created: AuthProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_auth_profile(sender, instance, **kwargs): instance.authprofile.save() l also attached a picture for error if I try to submit the form. [] The problem is that l can't update the user profile. anyone to help me -
i receive "TypeError: NetworkError when attempting to fetch resource." message while trying to fetch django server with "PUT" method
My fetch function const savePost = () => { fetch(`http://127.0.0.1:8000/api/posts/${id}/edit`, { method: "PUT", mode: 'cors', headers: { "withCredentials": "true", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", 'Access-Control-Allow-Headers': '*', "Access-Control-Request-Method": "PUT", 'Accept': 'application/json', }, body: JSON.stringify(post) }).catch(error => console.log(error)) In DJANGO settings.py INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['*'] I've already put CORS into my django settings.py and looked for a while to find how to solve this, but nothing helped. The main things i did is adding headers to fetch request and adding more CORS settings to django settings.py I don't know how to fix this error, if you could help me, I would really appreciate this -
The update on the address field isn't working
I'm working on a Python/Django project. In the update view, I'm encountering a very specific issue: When I try to update the bank_account field, the system updates it without any problems. However, when I attempt to update the address field, the address doesn't get updated. Here's the code: class DeveloperUpdateView(LoginRequiredMixin, UpdateView): model = Developer form_class = DeveloperForm template_name = 'developer/developer_form.html' success_url = reverse_lazy('backoffice:developer-list') def post(self, request, *args, **kwargs): object = Developer.objects.get(id=kwargs['pk']) developer_form = DeveloperForm( data=request.POST, instance=object, prefix='developer' ) bank_account_form = developer_bank_account_formset(data=request.POST) address_form = developer_address_formset(data=request.POST) if developer_form.is_valid(): developer = developer_form.save() if ( bank_account_form.has_changed() and bank_account_form.is_valid() ): existing_bank_accounts = DeveloperBankAccount.objects.filter( developer=developer ) if existing_bank_accounts.exists(): existing_bank_accounts = existing_bank_accounts.first() existing_bank_accounts.delete() bank_accounts = bank_account_form.save(commit=False) for bank_account in bank_accounts: bank_account.developer = developer bank_account.save() if ( address_form.has_changed() and address_form.is_valid() ): existing_addresses = DeveloperAddress.objects.filter( developer=developer ) if existing_addresses.exists(): existing_addresses = existing_addresses.first() existing_addresses.delete() addresses = address_form.save(commit=False) for address in addresses: address.developer = developer address.save() else: return render( request, "developer/developer_form.html", { "form": developer_form, "bank_account_form": bank_account_form, "address_form": address_form, "action": "update", "error": True, }, ) return HttpResponseRedirect(reverse('backoffice:developer-list')) def get_context_data(self, **kwargs): context = super(DeveloperUpdateView, self).get_context_data( **kwargs ) context['form'] = DeveloperForm( instance=self.object, prefix='developer' ) bank_account_form = developer_bank_account_formset() address_form = developer_address_formset() try: queryset = DeveloperAddress.objects.filter(id=self.object.address.id) address_form = developer_address_formset(queryset=queryset) address_form.extra = 0 except DeveloperAddress.DoesNotExist: address_form.queryset = … -
Django Haystack index.remove_object not working
I cannot get index.remove_object to actually follow through with removing the object. They continue to appear in the index even after deleting them. I have tried via the signal processor as well as manually in the shell. I get no error messages, but the object still shows up via SearchQuerySet. Here is the relevant code: ### search_index.py ### class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) id = indexes.IntegerField(indexed=False, stored=True, model_attr='id') ### shell ### from haystack import connections from haystack.query import SearchQuerySet from .models import Book book_object = Book.objects.first() SearchQuerySet().filter(id=book_object.id).count() --> 1 index = connections['default'].get_unified_index().get_index(Book) index.remove_object(book_object, using='default') SearchQuerySet().filter(id=book_object.id).count() --> 1 book_object.delete() # RealTimeSignalProcessor fires here, confirmed via print statement, no errors SearchQuerySet().filter(id=book_object.id).count() --> 1 I can even add a print statement to the signalprocessor that shows the code is firing, but for some reason the index itself isn't updating. The object does disappear if I run rebuild_index, but I don't want to have to do that each time I delete something. index.update_object is working just fine, and new values are reflected in the index. But remove_object does not. Any thoughts? -
Django pymongo update_many ''Cannot use the part (y) of (x.y) to traverse the element ({x: []})'}'
I have a collection like this with sample documents as: [ { "_id": { "$oid": "64b28bafb2ea43dd940b920d" }, "title": "Village Libraries", "keywords": { "bn": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b28badb2ea43dd940b920b" } } ], "en": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b28aacb2ea43dd940b920a" } } ] } }, { "_id": { "$oid": "64b676b3b2ea43dd940b9230" }, "title": "Folk Tales", "keywords": { "bn": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b67683b2ea43dd940b922d" } } ], "en": [ { "$ref": "mcoll_keywords", "$id": { "$oid": "64b676afb2ea43dd940b922e" } } ] } } ] I would like to run a multi update query on this collection (using Python (Django and pymongo)) like: db.collection.update({}, { "$pull": { "keywords.bn": { "$id": ObjectId("64b67683b2ea43dd940b922d") } } }, { "multi": true }) But running the update query: ... from pymongo import MongoClient ... print('q= '+str({'$pull': {'keywords.bn': {'$id': meta_bid}}})) # OUTPUT: q= {'$pull': {'keywords.bn': {'$id': ObjectId('64b67683b2ea43dd940b922d')}}} y= ent_col.update_many({}, {'$pull': {'keywords.bn': {'$id' : meta_bid}}}) results in the following error: full error: {'index': 0, 'code': 28, 'errmsg': 'Cannot use the part (bn) of (keywords.bn) to traverse the element ({keywords: []})'} I have tested the query in Mongo Playground (link) and it works fine there. So what am I doing wrong? Thank you in advance for reading …