Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send information on my email from django form? - Django 2
How to send information on my email from django form. Now I can see information only in my console output on my cmd template: {% extends 'base.html' %} {% load widget_tweaks %} {% block title %} Contact Us {% endblock %} {% block content %} <h2 class="mt-4 ml-4">Contact Me</h2> <form method="post"> <div class="container mt-4"> {% csrf_token %} <div class="col-md-4"> {{ form.subject.label }} {% render_field form.subject class+="form-control" %} </div> <div class="col-md-4"> {{ form.email.label }} {% render_field form.email type="email" class+="form-control" %} </div> <div class="col-md-4"> {{ form.message.label }} {% render_field form.message class+="form-control" rows="4" cols="6" %} </div> <div class="form-actions"> <button type="submit" class="btn btn-primary mt-2 ml-3">Send</button> </div> </div> </form> {% endblock %} forms.py: from django import forms class ContactForm(forms.Form): email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=False) views.py: from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def emailView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['yarik.nashivan@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message. <p>You will be redirected to … -
How to set up communication between two apps in Django?
I am currently trying to build a web app Todo task manager with Django as I find that the best way to learn is to get your hands dirty but I have come across a problem and I don't really know what is the Django way of doing it.. At the moment I have two apps in my project, one is 'lists' and the second is 'tasks', and my problem is that on the frontend, I need to show the different lists and associate them the tasks that are related to each list. So far I have managed to get the result visually by giving a list id to my tasks using a foreign key and importing the 'Task' model to the 'lists' views.py to then do the Querrry for tasks within the views.py of the lists app so that I can loop through them on the frontend but I feel like I'm making a frankeistein app now as they are both interdependent How would you guys handle the situation? ps: here an excerpt of my code for context from tasks.models import Task def lists_view(request): lists = List.objects.all() tasks = Task.objects.all() print("The request: ", request) context = { 'lists': lists, … -
Many to many queryset eroor
I am using ManyToManyField in my in Model. But when i am using custom queryset on field it is giving me validation error Select a valid choice. 2 is not one of the available choices. Because of this line: self.fields['user_groups'].queryset = Groups.objects.filter(group_company=self.user_company) but when i am using it without above line it is working perfectly fine. Forms.py class ManagerProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_company', 'user_groups'] def __init__(self, *args, **kwargs): self.user_company = kwargs.pop('user_company', None) super().__init__(*args, **kwargs) self.fields['user_groups'].queryset = Groups.objects.filter(group_company=self.user_company) Model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_groups = models.ManyToManyField(Groups,related_name='user_groups') -
django_celery_beat - "no such table: main.django_celery_beat_solarschedule__old" while updating "django_celery_beat_periodictask"
I'm using django + celery, when running django devserver I'm getting exception django.db.utils.OperationalError: no such table: main.django_celery_beat_solarschedule__old and callstack tells that it occured while doing insert into table django_celery_beat_periodictask Database is sqlite3. Calling code: `def register_task(task, interval=DEFAULT_TASK_INTERVAL): logger.info("Registering periodic task %s with interval %s", task, interval) name = "Default {}".format(task) schedule, _ = IntervalSchedule.objects.update_or_create( every=interval, period=IntervalSchedule.SECONDS) PeriodicTask.objects.update_or_create( name=name, defaults={ "interval": schedule, "task": task })` Actual traceback: File "/home/zab/Git/overview-server/overview-server/src/basis/tasks/shedule.py", line 21, in register_task "task": task File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django_celery_beat/managers.py", line 14, in update_or_create obj, created = self.get_or_create(defaults=defaults, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 489, in get_or_create return self._create_object_from_params(lookup, params) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 521, in _create_object_from_params obj = self.create(**params) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/zab/venv/overview/lib/python3.5/site-packages/django_celery_beat/models.py", line 316, in save super(PeriodicTask, self).save(*args, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 880, in _do_insert using=using, raw=raw) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 1125, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1285, in execute_sql cursor.execute(sql, params) File … -
How can I add static files without using Djstatic and Whitenoise?
I was trying to use Whitenoise and Djstatic to server Django static files on Heroku to me I feel they are quite complicated does anyone have an alternative -
use base64 to upload image to nginx+uwsig+django,when image size larger than 2M,the request can't get it
I'm using base64 to upload image to django, when image size larger than 2M,the server can't get the image I set up the uwsgi and nginx conf, make the upload size 75M ,but it didn't work image1 = base64.b64encode(open(file_path, 'rb').read()) r = requests.post(url, data={"image": image1}) =============== server: result = request.POST.get("image") -
How to solve return outside function in Django
I have this code but it displays return outside function error Am I doing something wrong. How do I fix it? class vote(request,question_id): question = get_object_or_404(Question,pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesnotExist): return render(request,'polls/detail.html', { 'question':question, 'error_message':"You didn't select a choice.",}) else: selected_choice.votes +=1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args=(question.id,))) -
django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie"
After make migrations , i tried to do migrate, but i am getting the django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie" from django.db import models import date time from django.contrib import admin class Movie(models.Model): CHOICES_MOVIE_TYPE = ( ("SF", 'Short-Film'), ("P", "Promo"), ("OT", 'Other'), ); CHOICES_LANGUAGE_TYPE = ( (" ", ''), ); CHOICES_ORIGINAL_OWNER_TYPE = ( ("OT", 'Other'), ); CHOICES_REMARK_TYPE = ( ); _id = models.AutoField(primary_key=True) name = models.CharField(max_length = 50, blank = False) Movie_Type = models.CharField(max_length = 2, choices = CHOICES_MOVIE_TYPE, default = "OT", blank = False) language = models.CharField(max_length = 5, choices=CHOICES_LANGUAGE_TYPE, default = "OT", blank = False)enter code here tags = models.TextField() original_owner = models.CharField(max_length = 2, choices = CHOICES_ORIGINAL_OWNER_TYPE, default = "OT", blank = False) Partner = models.CharField(max_length = 10) acquisition_cost = models.DecimalField(max_digits = 5, decimal_places = 4, blank = True) release_date = models.DateField(("Date"), default = datetime.date.today) -
Django How to present user values on built-in EditProfileForm
My form is like at the photo . I want to show user's data like name , lastname , phone number ... https://imgur.com/a/5qgvNC1 in my forms.py i edit the EditProfileForm as CustomEditProfileForm . I am trying to give user's data in value part (value':User.Accounts.name) . I dont know how to pull the data from accounts model. class CustomEditProfileForm(EditProfileForm): name = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','value':User.Accounts.name})) middlename = forms.CharField(widget=forms.TextInput(attrs={'value':'username'})) lastname = forms.CharField(widget=forms.TextInput(attrs={'value':'username'})) highschool = forms.CharField(widget=forms.TextInput(attrs={'value':'highschool'})) college = forms.CharField(widget=forms.TextInput(attrs={'value':'college'})) citystate = forms.CharField(widget=forms.TextInput(attrs={'value':'citystate'})) -
Mocking form in class based view not using the MagicMock
I've been fighting with mocking a form class to replace an instance of it in a class-based view. But it looks like that because the form is in a class attribute, it happens before I replace the form class with my mock. Case in point: app/views.py from app.forms import SomeForm # For some reason, this _is_ my mock... class SomeViewClass(View): form = SomeForm # ... while this is the _real_ SomeForm def post(self, request): form = self.form(request.POST, request.FILES) # Hacked around with pdb here # (Pdb) self.form = SomeForm <-- Force the mock into the object # (Pdb) form = self.form(request.POST, request.FILES) # (Pdb) form.is_valid() is now True # (Pdb) continue <--- Test finishes, and asserts are OK. if form.is_valid(): # This fails, as I'm running the real code # code, code, code app/tests/test_views.py from mock import MagicMock, patch from django.tests import Client, TestCase @patch('app.views.SomeForm') def test_post_valid_form_should_pass(self, mocked_form_class): """ Replacing SomeForm in SomeViewClass to pas the is_valid test """ form_instance = MagicMock(spec=SomeForm()) form_instance.is_valid.return_value = True mocked_form_class.return_value = form_instance self.client.login(**self.credentials) # code, code, code As you can see in the inserted comments in app/views.py, I forcefully reloaded self.form and redefined the variable form using pdb, which made my test pass. It … -
Django: How to get the list of month within a daterange in django query
Suppose I have query: ExampleModel.objects.filter(some_datetime_field__gte=start, some_datetime_field__lte=end) How do I get the list of all months present within "start" and "end" in the above mentioned query. For example: IF start= 1/10/2018 and end=10/1/2019 Then the output will be: OCTOBER NOVEMBER DECEMBER JANUARY Anyone any idea how to perform this? Thank you in advance -
Django: stream an image file right into template using requests
Using requests I am fetching an image from a server. Instead of writing this file out and then using it to load into the template, I am trying to parse the contents onto the view (image data inline or another method). Below is the partial output from r.contents: b'/x89PNG/r/n/x1v/n/x0e/x20/x20/rIHDR/x00/x00/x22/xdb/x00/x00/x01/xad/x08/x06/x00/x00/x00/xc7/xe3/xb8/xe9/x10/x00/x00/x06bKGD/x00/xff/x00/xcf/x00/ Since its bytes, I tried to encode using base64 and then pass into the image data-url but haven't been able to render. Below is the partial output: <img id="now" style="max-width: 100%; width: auto;" alt="" src="data:image/png;base64,b&#39;iVBSDFSGcANSUhEUgAAAtsAAAGtCAYAAADH47jpAAAABmJLR0QA/wD/AP+gvSDFsfgsbfbvdsdsbdgndfnOy9eZwcV3nv/autt+mWRqPVY2ksCckWljXacAggexQvQK4NiXHEa1+JsbdfghgcEEOwlBwvHNIL8xvpFmwpIABl8I2HEYzJ4bY48AAzbyaEG2Lxfg463dR/Xpqaqufeuq6uf7+fSnu6vq1HOe012nTv3qqecABEEQBEfgdrcgbQBEEQBEEQBEEQBEEQBEEQfgdfgEEQBEEQAMA1 Is there a way to get this to work? Below is the sample view code in use, the code is meant to give an idea of this question: def graph(request): unix_time = int(time()) r = requests.get(f'http://192.168.1.10/graph.php?type=multi-port_bits_duo_separate&idb=393,204,132,31,36,214&to={unix_time}', auth=(USERNAME,PASS), stream=True) r.raise_for_status() # the write to file method, works but trying to stream contents into view #with open(f'{unix_time}.png','wb') as fd: # for chunk in r.iter_content(chunk_size=50000): # fd.write(chunk) context = {'context': r.content} return render(request, 'live_graph.html', context) -
response data in ApiRequestFactory() _ djangoRestFramework
I need to access the content of response in UnitTesing and API testing in Django rest framework. class AuthTest(APITestCase): def setUp(self): self.factory = APIRequestFactory() def test_get_token(self): """ checking if api works fine for getting tokens """ request = self.factory.get('regenerate-token/') response = views.regenerate_token(request) self.assertEqual(response.status_code, status.HTTP_200_OK) this code works fine. but I need the content of response object. -
MultiValueDictKeyError with modified inline template in Django admin
In Django 1.11, I have 2 models, Foo and Bar: class Foo(models.Model): name = models.CharField() class Bar(models.Model): name = models.CharField() foo = models.ForeignKey(Foo) My admin.py looks like this: class BarInline(admin.StackedInline): model = Bar template = 'admin/edit_inline/list.html' class FooAdmin(admin.ModelAdmin): fields = ('name') inlines = [BarInline] I use a customised template to show the Bar inline form, because I don't want the forms, just links to the edit pages for each Bar. list.html looks like this: {% load i18n admin_urls static %} <div class="js-inline-admin-formset inline-group" data-inline-type="stacked"> <fieldset class="module {{ inline_admin_formset.classes }}"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2> {{ inline_admin_formset.formset.management_form }} {% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}{% if forloop.last %} empty-form last-related{% endif %}"> <h3 style="overflow:auto"><span style="float:left">{{ inline_admin_formset.opts.verbose_name|capfirst }}:&nbsp;{% if inline_admin_form.original %}<a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}">{{ inline_admin_form.original }}</a>{% else %}#{{ forloop.counter }}{% endif %}</span><span style="float:right">{% if inline_admin_form.original %}<a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="inlinechangelink">Change</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="{% url 'admin:app_bar_delete' inline_admin_form.original.pk|admin_urlquote %}" class="deletelink">Delete</a>{% endif %}</span> </h3> </div>{% endfor %} <div class="add-row"> <a href="{% url 'admin:app_bar_add' %}?foo={{original.pk}}">Add a Bar</a> </div> </fieldset> </div> The problem is that when I edit an existing Foo, and click Save, I get the error: MultiValueDictKeyError at /admin/app/foo/1/change/ "'bar_set-0-id'" -
Django custom cache_page decorator
I am trying to override my django app's(restful API to be precise) caching. So it seems SessionMiddleware is setting vary header to Cookie. Because of this, every user has its own cache. But for my use case it does not need to have unique cache for every user. If a first person visited that route i want to cache it and serve cache to everyone(each user) since it's just a read-only endpoint. Because of vary: Cookie, it's not possible for default django cache. Cookie is different for any user. I dug django cache codes and found CacheMiddleWare is using UpdateCacheMiddleware, FetchFromCacheMiddleware Based on this i just had to write my own cache_page decorator just for certain Viewsets instead of writing whole middleware. All Middlewares(UpdateCacheMiddleware, FetchFromCacheMiddleWare) are extended from MiddlewareMixin Checking vary header is in UpdateCacheMiddleWare i tried overriding UpdateCacheMiddleWare but no luck. Please if anyone have solution please tell me. Thanks in advance. -
how to upload image using django with ModelForm , jquery , ajax
I've looked around at related questions, but none of the answers seem to work for me i need to upload image for each time the user submit the form meaning user have a for to fill in the requested data with the ability to upload image. i am using django and jquery with ajax once i click on submit button the system display this error jquery-1.12.4.min.js:4 Uncaught TypeError: Illegal invocation at e (jquery-1.12.4.min.js:4) at dc (jquery-1.12.4.min.js:4) at dc (jquery-1.12.4.min.js:4) at Function.n.param (jquery-1.12.4.min.js:4) at Function.ajax (jquery-1.12.4.min.js:4) at HTMLInputElement. (creativePage.html:214) at HTMLInputElement.dispatch (jquery-1.12.4.min.js:3) at HTMLInputElement.r.handle (jquery-1.12.4.min.js:3) these are the steps that i did it until now : add picture filed to models.py add picture element in the form.py create a form with enctype = "multipart/form-data" in the html page add the filed of image in the form in the html page add the img element in data field in jquery & ajax in order to send the request once the user click the submit button add the variable img in order to receive the data from ajax in views.py at the end saving the form. models.py class te2chira(models.Model): te2chira_id = models.AutoField( primary_key=True) num = models.IntegerField() # year = models.IntegerField() te2chira_date = models.DateField() … -
Displaying ImageField as required in swagger post api
My model: class Image(models.Model): image=models.ImageField(upload_to='photos') name=models.CharField(max_length=40,unique=False) My serializer: class imagesSerializer(serializers.ModelSerializer): image = Base64ImageField(required=True) class Meta: model = Image fields = ('id','name','image') My swagger looks like above: How to make the ImageField as required in my swagger post API using Django? -
Django encoding issue on ubuntu server
I am working on Django Rest Framework and I have a simple login view.py and everything is working perfectly fine on my localhost. But on ubuntu server it throws some strange error. Following is the view class class userDetail(generics.RetrieveUpdateDestroyAPIView): def post(self, request, *args, **kwargs): header = Header(request) checkHeader = header.checkHeader() if checkHeader['status'] == 0: return Response(checkHeader, status=status.HTTP_401_UNAUTHORIZED) # platform = request.META.get('HTTP_PLATFORM', 'Not Found') data = request.data serializer = loginSerializer(data = data) if serializer.is_valid(raise_exception=True): data = serializer.data username = data['username'] password = data['pword'] authenticate = Authentication(username, password) loginData = authenticate.check() if loginData[0]['status'] == 1: auth = skAuth_Token(loginData[0]['userID']) auth_token = auth.encode() if auth.saveToken(auth_token): rowData = UserMaster.objects.get(pk=loginData[0]['userID']) dataSerializer = loginDataSerializer(rowData) response = { 'status': 1, 'message': 'Login Successfull', 'header': checkHeader, 'skAuth_Token': auth_token, 'data': dataSerializer.data } else: response = { 'status': 0, 'message': 'Couldnot save skAuth_Token in dB', 'header': checkHeader, } elif loginData[0]['status'] == 2: response = { 'status': 2, 'message': 'User is not Registered as a seller', 'header': checkHeader } else: response = { 'status': 0, 'message': 'Login Failed', 'header': checkHeader } return JsonResponse(response) return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST) This Runs fine on my localhost(Windows). But gives the following error on ubuntu server. This is the main error - 'utf-8' codec can't decode byte 0x89 … -
How to fix this error - Not Found: /firstapp/ "GET /firstapp/ HTTP/1.1" 404 2065"
I have created a project named firstproject and added a new project firstapp in which urls.py of firstapp is invoked to call view.py which displays a string in webpage. But the webpage is showing error. I have created a project named firstproject and added a new project firstapp in which urls.py of firstapp is invoked to call view.py which displays a string in webpage. But the webpage is showing error. firstapp urls.py from django.conf.urls import url from . import views urlpatterns={ url('r^$',views.index,name='index') } views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<H2> Hey Everyone welcome to Django Tutorial! </H2>") # Create your views here. firstproject urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$/', include('firstapp.urls')), ] I expect the output to be "Hey Everyone welcome to Django Tutorial!" -
What framework should i choose yii or django?
What framework should I choose Yii or Django?. If Yii framework, then please guide me to call python files from controller and view pages of Yii. I want to install and access following library files for a machine learning project, Tesseract OpenCV Lipnet Pandas etc. Please note : I know to execute shell commands but i don't know how to implement in Yii -
Restrict values that appear in Django admin select box
In Django 1.11, I have 2 models, Foo and Bar: class Foo(models.Model): name = models.CharField() extra = models.BooleanField(default=False) class Bar(models.Model): name = models.CharField() extra_foo = models.ForeignKey(Foo) My admin.py looks like this: class BarInline(admin.StackedInline): model = Bar fields = ('name', 'extra_foo') class FooAdmin(admin.ModelAdmin): fields('name') inlines = [BarInline] My problem is that the in the Bar inline form, the dropdown for extra_foo shows all of my existing Foos. I want it to only show Foos for which extra is true. How can I modify the admin to restrict the available options in a select box to a subset of the whole? -
Django follow feature with m2m
I tried to solve the problem and got stuck. The problem is that I have a post that I can follow. My problem is that I don't know how to add a tracking button. Should this be done by url, with a view? Or should it be rather as a method in the model? My problem is also whether it is properly written in terms of models - using the intermediate model Follower? Here is Post model and I would like to add followers here. I mean, everybody who is interested, can follow this post. class Post(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1024) followers = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Follower', blank=True) is_visible = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:post_detail', kwargs={'pk': self.pk}) def number_of_followers(self): return self.followers.count() Here is my manager for follower model: class FollowerManager(models.Manager): use_for_related_fields = True def follow(self, user, pk): post_object = get_object_or_404(Post, pk=pk) if user.is_authenticated(): if user in post_object.followers.all(): Follower.objects.filter(post=post_object, user=user).delete() else: Follower.objects.create(post=post_object, user=user) Here is Follower model: class Follower(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = FollowerManager() -
Lookup field in DRF make it case insensitive
I currently have something like this class GetUsernameUnique_RetrieveAPIView(RetrieveAPIView): queryset = modelEmployer.objects.all() lookup_field = 'user__username' serializer_class = Serializer_ListEmployer permission_classes = (permissions.AllowAny,) However it seems the username in lookup field is case sensitive. Any idea how I can make it case insensitive. -
Django user edit profile How to update info without creating another user?
If I use u_form.save(), I suppose there will be a new user data recorded into database. What if I just want to update info but keep the same user? Here's part of my codes: @login_required def profile(request): Exist_Emails = User.objects.filter(is_active=True).values_list('email', flat=True) Exist_Usernames = User.objects.filter(is_active=True).values_list('username', flat=True) current_user = User.objects.get(username=request.user.username) if request.method == 'POST': update_username = request.POST.get('username') update_email = request.POST.get('email') if update_username != current_user.username and update_email == current_user.email and update_username not in Exist_Usernames: u_form = UserUpdateForm(request.POST, instance=request.user) if u_form.is_valid(): User.objects.filter(email=current_user.eamil).update(username=update_username) messages.success(request, f'Your account has been updated!') return redirect('/users/profile/') #.Other elif cases... else: u_form = UserUpdateForm(instance=current_user) Here I only show one of the case: the user changes the username, but keep the same email, and the new username should have existed in the database yet. But when I go to my profile page and change only the username, press the submit button, there's no change at all! And I also checked admin user page, there's no change either. I am so confused. if any of my code is wrong please help, thank you! -
Djongo always connects to localhost mongodb
I have followed the guide of db connection config: https://nesdis.github.io/djongo/database-configuration/ However, it always connects to localhost one, not my setting's one. Does anyone have any idea on this issue? my packages versions: Django 2.0 django-cors-headers 2.4.0 django-rest-auth 0.9.3 djangorestframework 3.9.0 djongo 1.1 mongoengine 0.16.3 pip 10.0.1 pymongo 3.7.2 urllib3 1.24.1