Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a DateTime picker on clear django?
I need to have a picker for DateTimeField, but I dont realy know how to do it. Ive tried admin widget but I think I did it wrong. The closest thing to a solution was: models.py class MyModel(models.Model): myfield = models.DateTimeField() forms.py class MyModelForm(forms.ModelForm): class Meta: widgets = {'myfield': widgets.SplitDateTimeWidget( date_attrs={'type': 'date'}, tame_attr={'type': 'time'})} It shows me a working picker, but when i try to press a save button it says me an error about method 'strip' (forgot actual error, sry). -
HTML forloop - double
I am in my HTML file for my website. The first forloop checks to see what account the user is logged into and then only displays that user's data and it works perfectly on its own. {% for item in user.Doc.all %} The second forloop loops through all the data that "__stratswith"Title: " and displays it and this works perfectly on its own. {% for post in templates %} I am using Django and python to build the website and once running into this problem I have researched if there is any other way to loop through the forloops in a different location like my views.py file and I have had no luck. I need to do it in the HTML but when I write this... {% for item in user.Doc.all %} {% for post in item.templates %} {{ post.content }} {% endfor %} {% endfor %} It doesn't work. It indicated that there is data trying to be displayed because I have an if statement before the for-loops but no data is displayed. I need the proper way to write a nested forloop in an HTML file properly and I cant figure it out. The example I have should … -
Django - How to create ManyToMany relations with "through" and "to"?
I have 3 models to create a proper relation between a Genre and a Movie object. In addition I also have MovieGenre model to glue Movies and Genre model together: class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name=_("Genre"), blank=True, null=True, editable=False, unique=True, max_length=50) class Movies(models.Model): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) genre_relation = models.ManyToManyField(through='MovieGenre', to='Genre') class MovieGenre(models.Model): movie = models.ForeignKey(Movies, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) I have noticed that if I create new genre objects and there relations like so: def pull_genre(object_id): if genre_value: object_genre = genre_value.split(", ") for genre in object_genre: new_genre, create = object_id.genre_relation.get_or_create( name=genre, movies=object_id ) I get many times the same "name" under a different "id" at my "Genre" model where I basically only need the name once. For example name=Comedy is present under many different ID's ... Why that? I also tried unique=True at the name field but running into: django.db.utils.IntegrityError: (1062, "Duplicate entry 'Drama' for key 'App_genre_name_b25416d5_uniq'") How can I create the relation without this strange flaw? In the end I only need "name" at "Genre" model once and the relation between one "Movie" and multiple "Genre" trough the MovieGenre model. Thanks in advance -
Display a Boolean field result if it's True
I'm having trouble here to display the return of a boolean field in the template. I need to display the name of the field if it is true in the template. Any help will be welcome. models ´´´ class IEIS(Model.models): topo = models.BooleanField() ´´´ views def view_ieis(request, pk): ieis = IEIS.objects.get(pk=pk) return render(request, 'ieis/view.html', {'ieis': ieis,}) template.html <div table class="table table-reponsive"> <table class="table table-bordered"> <thead> <tr> <th scope="col">Tipo</th> </tr> </thead> <tbody> <tr> <td> {% if topo is True %} <p>Topo</p> {% endif %} </td> </tr> </tbody> </table> </div> -
AttributeError: type object ' ' has no attribute 'object'
I'm learning python and follow step by step the book "Learning python" Eric Metiz. I am so confused, I had checked the code a few times and it exactly the same as in the book. Could you help me out with this? in models.py from django.db import models class Topic(models.Model): # Тема, которую изучает пользовательн text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): # Возвращает строковое представление модели return self.text class Entry(models.Model): # Информация, изученная пользователем по теме topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if len(self.text) > 50: return self.text[:50] + "..." else: return self.text in views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): # Домашняя страница Learning_log return render(request, 'learning_logs/index.html') def topics(request): # Выводит список тем topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): # Выводит одну тему и все ее записи topic = Topic.object.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) The stacktrace: [21/Jul/2021 15:12:05] "GET / HTTP/1.1" 200 396 [21/Jul/2021 15:12:06] "GET /topics HTTP/1.1" 200 352 Internal Server Error: /topics/1/ Traceback (most recent … -
Django - Why is this TableView not ordering the queryset?
I have a TableView in a Django project which isn't properly ordering its queryset. I tried adding the ordering to the model Meta, overriding the view's get_queryset method, and don't know how best to tackle this. This doesn't happen in any other view, I have many views with many different models, and usually overriding the "get_queryset" method works fine, and I can order however I need there, but right now it isn't working in this particular view. The view looks like this: class ShippingCenterPricesTableView(PurchaseViewingPermissionMixin, PagedFilteredTableView): model = ShippingCenterPriceHistory table_class = ShippingCenterPricesTable template_name = 'purchases/shipping_center/shipping_center_prices_table.html' filter_class = ShippingCenterPriceFilter export_name = "PreciosCentrosDeEmbarque" formhelper_class = ShippingCenterPriceFormHelper paginate_by = 100000000 def get_context_data(self, **kwargs): context = super(ShippingCenterPricesTableView, self).get_context_data(**kwargs) context['allows_shipping_center_creation'] = self.request.user.purchases_permission == '2' return context def get_queryset(self, **kwargs): qs = super(ShippingCenterPricesTableView, self).get_queryset() qs = qs.order_by('-date') return qs The model looks like this: class ShippingCenterPriceHistory(models.Model): shipping_center = models.ForeignKey(ShippingCenter, on_delete=models.SET_NULL, null=True, blank=False, verbose_name='Centro de embarque') circular_price = models.FloatField(verbose_name='Precio circular sin I.V.A.', null=False, blank=False) differenced_price = models.FloatField(verbose_name='Precio diferenciado', null=False, blank=False) date = models.DateField(verbose_name='Fecha actualización', auto_now_add=True) observations = models.CharField(verbose_name='Observaciones', max_length=100, null=True, blank=True) current = models.BooleanField(verbose_name='Precio actual', default=True) @property def discount_percentage(self): return 1 - (self.differenced_price / self.circular_price) class Meta: ordering = ('-date',) And, in case it's relevant, the Table looks … -
ERROR RUN pip install -r requirements.txt when using docker-compose up
How should I create and install the requirements.txt file in order to be able to read it properly when running docker-compose up? Problems when running docker-compose up with the requirements.txt created via pip freeze > requirements.txt requirements.txt: certifi==2021.5.30 charset-normalizer==2.0.3 Django==2.2.5 django-cors-headers==3.7.0 django-rest-framework==0.1.0 djangorestframework==3.12.4 idna==3.2 psycopg2 @ file:///C:/ci/psycopg2_1612298715048/work python-decouple==3.4 pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work requests==2.26.0 sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work urllib3==1.26.6 wincertstore==0.2 I use anaconda and pip to install packages The Dockerfile for the backend of my app tries to RUN pip install -r requirements.txt rising the following errors. I could sense the @ packages arise error, but the strangest for me is the first one (#17 1.299) since it seems to be focusing on python-decouple==3.4 as just python. => ERROR [... 4/5] RUN pip install -r requirements.txt 1.8s ------ > [... 4/5] RUN pip install -r requirements.txt: #17 1.299 DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429). #17 1.345 Collecting certifi==2021.5.30 (from -r requirements.txt (line 1)) #17 1.515 Collecting charset-normalizer==2.0.3 (from -r requirements.txt (line 2)) #17 1.541 Could not find a version that satisfies the requirement charset-normalizer==2.0.3 (from -r requirements.txt … -
Django How to capture a C2B Transaction in Django
I want to capture transactions made to my till number directly (Not those paid via STK push) so that I can save them to database. How do I go about it. I am using django -
how can i delete my comment in with a delete function or class in Django?
how can I create a delete function or class to delete a comment with this detail? this is part of my comment model in the comment app class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') content = models.TextField() parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) this is part of my view in product app def product_detail(request, *args, **kwargs): selected_product_id = kwargs['productId'] product = Product.objects.get_by_id(selected_product_id) if product is None or not product.active: raise ("not valid") comments =product.comments.filter(active=True, parent__isnull=True) new_comment=None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_obj = Comment.objects.get(id=parent_id) if parent_obj: replay_comment = comment_form.save(commit=False) replay_comment.parent = parent_obj new_comment = comment_form.save(commit=False) new_comment.product = product new_comment.save() else: comment_form = CommentForm() -
Unable to use runserver_plus for django
I am using the command to run my python-django project on https "python3 manage.py runserver_plus 0.0.0.0:9999 --cert-file /path/to/cert/app" but I get the error File "/Users/xyz/django_dev_portal/django-api-1/app/manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I have django-extensions installed. Im unable to figure out whats going wrong as Im very new to Django and Python. Any help is greatly appreciated. Cheers, Sheetal -
attribute error in django. django.db.models has no attribute
I am trying to write the code so that a user in the system can view complaint registered by others on this page but not their own complaints. This is the code, but I don't understand what's wrong: views.py: class OtherPeoplesComplaints(TemplateView): model = Complaint form_class = ComplaintForm template_name = 'userComplaints.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["complaints"] = models.Complaint.objects.exclude( profile__user = self.request.user ) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}), … -
I am encountering an Apache error while deploying a Django site
Faced Apache error while deploying Django site with MySQL db. Without Apache, the site works perfectly, but when you enable it, this error is thrown. I can't figure it out for several days. This is what the logs give out: [Wed Jul 21 12:49:59.142758 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] mod_wsgi (pid=24588): Target WSGI script '/bigchina/django/bigchina/bigchina/wsgi.py' cannot be loaded as Python module. \[Wed Jul 21 12:49:59.142923 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] mod_wsgi (pid=24588): Exception occurred processing WSGI script '/bigchina/django/bigchina/bigchina/wsgi.py'. \[Wed Jul 21 12:49:59.144156 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] Traceback (most recent call last): \[Wed Jul 21 12:49:59.144210 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/django/bigchina/bigchina/wsgi.py", line 18, in <module> \[Wed Jul 21 12:49:59.144217 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] application = get_wsgi_application() \[Wed Jul 21 12:49:59.144257 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application \[Wed Jul 21 12:49:59.144263 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] django.setup(set_prefix=False) \[Wed Jul 21 12:49:59.144269 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup \[Wed Jul 21 12:49:59.144274 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] apps.populate(settings.INSTALLED_APPS) \[Wed Jul 21 12:49:59.144280 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/apps/registry.py", … -
Django not collecting all my static files
This my settings.py code, I have made a folder staticdie and copied all my static files in it. STATIC_URL = '/static/' STATICFLIES_DIRS = [ os.path.join(BASE_DIR, 'staticdie') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') When I put python manage.py collectstatic it creates a folder 'assets' and only displays admin files in it. Its not collecting all my static files from staticdie folder. I'm using travello template from colorlib. link(https://www.dropbox.com/sh/gf8x8xjwidq20cz/AABPlOsXmijnz0-yjxYj9ebsa?dl=0) What am I missing? -
How to redirect unauthenticated users to login page?
Im developing a web application using React and Django Sessions with Django Rest Framework for authentication. I have already configured sessions to be given to users on login. I am trying to find a way to redirect unauthenticated users to login page from any page in the web application. I have tried to obtain the value of the sessionid cookie seen here so that I can redirect users if the .length value == 0. if (getCookieValue('sessionid').length === 0) { return <Redirect to="/login" /> } However, since the sessionid cookie is an HTTP cookie, JavaScript is unable to obtain the value. Thus, it is always 0. How can I obtain the value of the HTTP cookie? Or, is there any other way to achieve my desired effect? -
assertEqual getting failed while values are same
I have below test case assert code self.assertEqual( response.data['results'], [ ('id', self.bookmark.id), ('title', self.bookmark.title), ('color', self.bookmark.color), ('user', self.bookmark.user.id), ('project', self.bookmark.project.id), ] ) response.data['result'] is : [OrderedDict([('id', 7), ('title', 'bookmark'), ('color', 'yellow'), ('user', 2), ('project', 1)])] compare list value is : [('id', 7), ('title', 'bookmark'), ('color', 'yellow'), ('user', 2), ('project', 1)] failure msg : AssertionError: [OrderedDict([('id', 7), ('title', 'bookma[52 chars]1)])] != [('id', 7), ('title', 'bookmark'), ('color[37 chars], 1)] can anyone please help? -
How pass multiple attributes to View on Button Click?
I am using Django as my web Framework. On my website there is a view that shows all "projects" of a user. Here the user has the possibility to leave the project or to add a user to the project. When a user presses a button, I want the respective action to be executed. To check if the share or leave button has been pressed i have added a button in my button: <form method="POST"> <button name="leave_project" type="submit" ...>...</button> </form> and can then check in the views: if 'leave_project' in request.POST: However, now I still need the ID of the project that was clicked on. How can I also pass the ID? I know that I could solve the problem by adding a new view with the ID in the url. But then the page would have to be reloaded which I would like to avoid. -
best article/resource for DJANGO + REACT stack
I've been learning Django and React separately for a long time. I want to use them together as a stack now. I know, there are so many articles/tutorials about this already. But everyone has their own method. Can someone plz tell me the BEST way to do so? Any article/video/or previously asked StackOverflow question will do me good. Thanks -
No Reverse error on updating an object in Django
Model: class HourCodes(models.Model): nummer = models.IntegerField() omschrijving = models.CharField(max_length=100) def get_absolute_url(self): return reverse("to_HourCodes") View: class UpdateHourCodes(UpdateView): template_name = 'hourcode_update.html' form_class = Update_hourcode_form queryset = HourCodes.objects.all() def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(HourCodes, id=id_) Url.py path('toHourcodes/', views.toHourcodes, name='to_hourcodes'), path('UpdateHourCodes/<int:pk>/', views.UpdateHourCodes.as_view(), name="update_hourcode"), iam getting the error NoReverseMatch at /UpdateHourCodes/44/ So the link seems to be right, in this case to HourCode nr 44. Anybody has a clue ? -
Django Cast DateTimeField to DateField splits over multiple days
I have a DateTimeField that I'm casting into a DateField so I can group by the date then perform some annotations. For some reason it's splitting a single timestamp for a specific date into two dates - I can't figure out why it's happening. For example in the following I should only get one grouping as I'm specifically filtering for May 5th but it's being split into two separate dates. orders = ( Order.objects .filter(paid_at__date='2021-05-01') .annotate(paid_at_date=Cast('paid_at', DateField())) .order_by('paid_at_date') .values('paid_at_date') .annotate(total=Sum('total')) ) <OrderQuerySet [{'paid_at_date': datetime.date(2021, 5, 1), 'total': Decimal('17852.30')}, {'paid_at_date': datetime.date(2021, 5, 2), 'total': Decimal('6895.30')}]> -
how i could filter items by their sex category
template <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="">default</option> <option value="price">price: $ - $$</option> <option value="-price">price: $$ - $</option> <option value="collection">collection</option> <option value="-collection">collection2</option> </select> <input type="submit" class="d-none" value="submit"> </form> view class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) ***context*** return context def get_ordering(self): return self.request.GET.get('orderby', ) how can i pass gender to template, if i just pass the value== collection it will be sort by collection names(women first then men and children) am i need a template tag for this? -
deleting model when foreignkey is deleted in django
So, I have a model something like this class Blog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) posted_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def delete(self, *args, **kwargs): # to do before delete super().delete(*args, **kwargs) I want to delete all Blog objects related to User when the User is deleted. It is working but its deleting object without calling overridden delete function. I want to delete the model through the overridden delete function coz i have something to do before actually deleting the object. If it is not possible, do suggest any other way to do it. -
Django choices field in form
I have two tables: class Career(models.Model): title = models.CharField(max_length=300) job_type = models.CharField(max_length=20, blank=False, default=None) location = models.CharField(max_length=200, blank=False, default=None) description = RichTextUploadingField(max_length=227, blank=False, default=None) class ApplyJob(models.Model): first_name = models.CharField(verbose_name=_('First Name'), max_length=100) last_name = models.CharField(verbose_name=_('Last Name'), max_length=100) email = models.EmailField(verbose_name=_('Email'), max_length=200) position = models.CharField(verbose_name=_('Position'), max_length=40) apply = models.ManyToManyField(Career, default=None, blank=True) And a ModelForm: class Meta: model = ApplyJob fields = ('first_name', 'last_name', 'email','position', 'message') widgets = { 'position': forms.Select(choices=CHOICES, attrs={'class': 'form-control'})} I want to add choices selection in position with values from Career table, so itried to query Career table to get all values. So i tried CHOICES = Career.objects.values_list('title', flat=True).distinct() but i got an Exception Error: too many values to unpack (expected 2) Any ideas on what the problem is about? Thank you! -
Django User Type Definition
In Django : From a Python OO perspective if I want different types of users shouldn't I have a "Teacher" Object Type AND "Student" Object" type extended from AbstractUser? Looks like all the solutions mention to just extend with all the fields required for both users and only use the fields required for a Teacher or Student at Form time. Just trying to stay with the OO method which makes sense to me from a newbie perspective. Having different object types would allow me to test the object for the type instead of looking at an attribute and have only the needed fields for each type defined in the object. Is there a correct way to do this so I have users of different object types? Could I just embed an object of type Teacher or Student as a field in the User Model? Just a guess? Let me know what you can and thanks for your expert polite response and patience. Is this a good solution? https://github.com/mishbahr/django-users2 This is the recurring theme I see on the internets... django best approach for creating multiple type users -
syntax error when importing django-sphinxsearch
I am trying to run the standard django migration commands, ex., python3 manage.py makemigrations, and continuously get a syntax error on module import with sphinxsearch. I know it's deprecated, but unfortunately I am working on small additions to the site and cannot move to elasticsearch yet. Python version : 3.5.3 System : Debian (AWS server) Sphinx version: 3.5.4 sphinxsearch version: 0.1 Error message: Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 669, in exec_module File "<frozen importlib._bootstrap_external>", line 775, in get_code File "<frozen importlib._bootstrap_external>", line 735, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/sphinxsearch/__init__.py", line 75 SPH_ATTR_MULTI = 0X40000000L ^ SyntaxError: invalid syntax I've tried updating the system and have changed sphinx … -
Django: Redirecting to same page after updating profile is not updating the user profile in database
I have this update view which updates the user's profile like first_name, last_name and DOB. @login_required def profile_view(request): user_obj = get_object_or_404(User, id=request.user.id) profile_obj = get_object_or_404(Profile, user=user_obj) print(user_obj.first_name) if request.method == "POST": user_edit_form = UserEditForm(data=request.POST, instance=user_obj) profile_edit_form = ProfileEditForm(data=request.POST, instance=profile_obj) if user_edit_form.is_valid() and profile_edit_form.is_valid(): user_edit_form.save() profile_edit_form.save() return HttpResponseRedirect(request.path_info) else: user_edit_form = UserEditForm(instance=user_obj) profile_edit_form = ProfileEditForm(instance=profile_obj) return render( request, "account/profile.html", {"user_edit_form": user_edit_form, "profile_edit_form": profile_edit_form}, ) The problem is when I redirect to the same page using HttpResponseRedirect(request.path_info) the values are not getting updated in the database. But if I redirect to some other page of my site say return redirect('account:home') instead of HttpResponseRedirect(request.path_info) the values are updating. This is my profile form {% extends "base.html" %} {% load static %} {% block content %} <h1> {{ request.user | capfirst }} Profile details</h1> <form method="post"> {% csrf_token %} <table class="table .table-striped"> {{ user_edit_form.as_table }} {{ profile_edit_form.as_table }} </table> <button class="btn btn-danger" type="submit"> <a style="text-decoration: none; color: black;" href="#">Update</a> </button> <button class="btn btn-danger"> <a style="text-decoration: none; color: black;" href="{% url 'account:log_out' %}">Log Out</a> </button> </form> {% endblock %}