Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Is it better to store user information by customising the default User model, or should I create a separate Model for this?
This is for a practice project I am building to learn Django. The site will need to track certain data about the user. Should I customise the default User model? Or create a new model like - class UserData(models.Model): '''holds user info''' owner = models.ForeignKey(User) # data I couldn't find a clear answer. -
How to delete a django object from multi-form button submission?
Im working on a django app and im fairly sure ive got this wrong but i cant workout how to delete a django object from a form button. Ive got the edit/update fields working but im not sure how to use the same form (or the one below it) to also process a delete. my experience with django is limited and i havent setup the logging yet properly. Ive tried the below. What am i doing wrong? the Model: class Tier(models.Model): number = models.PositiveSmallIntegerField(default=0) description = models.TextField(max_length=800, verbose_name='Description') price = models.IntegerField(verbose_name='Price') can_message = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tier_user') def __str__(self): return 'Tier ' + str(self.number) def save(self, *args, **kwargs): amount = Tier.objects.filter(user=self.user).count() self.number = amount + 1 return super().save(*args, **kwargs) def delete(sender, instance, *args, **kwargs): tier = instance tier.delete() EditTierForm: <div> <form method="post" action="" role="form" class="col s12"> <h4>Edit Tier</h4> {% csrf_token %} <div class="input-field col s12"> ... </div> <div class="input-field col s12>"> <button class="btn waves-effect waves-light" type="submit" name="action">Save <i class="material-icons right">add</i> </button> </div> </form> <form action="{% url 'tier_delete' tier_id=tier.number %}" method="delete" role="form" class="col s12"> {% csrf_token %} <div class="input-field col s12>"> <button class="btn waves-effect waves-light btn red" type="submit" name="action">Delete Tier <i class="material-icons left">delete</i> </button> </div> </form> </div> urls: path('mytiers/', … -
TypeError when trying to create a model instance
I have a project where I need to create a Django command to upload multiple images at a time. I have a base class Image that defines the file, and subclass Icon that associates a word and a description to the icon. My issue is that I get an error when I call Icon.objects.create(). It works in a single upload context, but not here in the bulk uploader. What should I do about it? models.py class Image(TimestampedModel): """ Abstract model containing an image, a hash of that image, and operation methods. """ class Meta: """ The metaclass defining its parent as abstract. """ abstract = True # Static variables RELATIVE_PATH = 'img' BLOCK_SIZE = 2**16 # Attributes image = models.ImageField( blank=True, null=True, default=None, upload_to=RELATIVE_PATH) _hash = models.BinaryField( _('MD5 hash'), editable=False, null=True, default=None, max_length=16) class Icon(Image): """ Image file associated with a word, a descriptor, and (for verbs) tense. """ # Static variables TENSE_CHOICES = [ (None, 0), ('1', 1), # present ('c', 2), # present participle ('p', 3), # past ('pp', 4), # past participle ] BLOCK_SIZE = 2**12 # Attributes word = models.CharField(max_length=32) descriptor = models.CharField(blank=True, null=True, max_length=32) tense = models.PositiveSmallIntegerField( blank=True, null=True, default=None, choices=TENSE_CHOICES) is_approved = models.BooleanField(default=False) bulk_uploader.py … -
Accessing profile info through user model Django
Hello I am a beginner with the django python framework. I need to display a user's image and bio on a file named user_posts.html in my blog app. I have it where I can access the user's image and bio by looping over the posts for the user. However, I need it so it only displays the bio and the image once. I have a separate profile.html in a users app. In that file, I can do just src="{{ user.profile.image.url }}" and {{ user.profile.bio }} to access the users information but that does not seem to work in my user_posts.html because of the structure of my project. I can't figure out how to tell the for loop to just go over once to access the users information. users_post.html {% extends "blog/base.html" %} {% block content %} <hr size="30"> <div class="row"> <div class="column left"> {% for post in posts %} <img style= "float:left" src="{{ post.author.profile.image.url}}" width="125" height="125"> <h5 style="text-align: left;">{{ post.author.profile.bio }}</h5> {% endfor %} </div> views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') models.py from django.db import models from django.contrib.auth.models … -
how to add variable to value in django templates
i got the problem , im trying to add variable to input Value , i found some solution to this but is not working for some reason, any idea what i wrong ? html <input id="city" name="city" type="text" value="{{ form.country }}"/> <br> {{ form.country }} and this what im getting -
Can't make migrations
I write python3 manage.py makemigrations (I have a mac), migrations are not done, I get a lot of errors, but I don't understand anything about the project at all, here is the traceback Traceback (most recent call last): File "/Users/work/Projects/ims/api/manage.py", line 21, in <module> main() File "/Users/work/Projects/ims/api/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.9/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 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/work/Projects/ims/api/ims/settings.py", line 35, in <module> hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) socket.gaierror: [Errno 8] nodename nor servname provided, or not known teamlead in the team did something like migrations and they were applied, now, after I added indexes to models.py, to optimize sql queries, I needed to make migrations, but it did not work, but the server … -
Parsing nested dictionaries in Html (django)
Models.py class Subject(models.Model): name = models.CharField(max_length = 20) class Student(models.Model): name = models.CharField(max_length = 20) hometown =models.CharField(max_length = 20) class Classes(models.Model): name = models.CharField(max_length = 20) Views.Py def admin_main(request): Student_data = Student.objects.all() Subject_data = Subject.objects.all() Classes_data= Classes.objects.all() New_dict = {"Student_data":Student_data, "Subject_data",Subject_data, "Classes_data",Classes_data} return render(request,"admin_main.html",New_dict) How to display all names from Student in admin_main.html admin_main.html -
AppConfig.get_model usage in custom manager
So i need to get model to use self.model in my Custom manager within AppConfig.get_model, but I don't understand how to use it. <<managers.py>> class CustomUserManager(BaseUserManager): use_in_migrations = True model = ??? def _create_user(self, email, password, **extra_fields): if not email: raise ValueError(_("email is required")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser should to have flag is_superuser=True')) return self._create_user(email, password, **extra_fields) -
Very slow django with "large" database (< 1M rows)
I'm trying to build an app with django. When I work with a small database (around 10k rows), the app works perfectly. However, in some views, I need to calculate some data of my classes, so I need to call all of my database. It is very slow (more than 30s), and according to Django Debug Toolbar, most part of the time is consumed by CPU. Here's an example of a (very) simplified code I try to launch: def test_view(request): queryset_articles = Articles.objects.all() total_count = sum([a.words_count for a in queryset_articles]) response = 'Total words : ' + str(count) return HttpResponse(response) How should I do to get a reasonable waiting time? I think about doing another table, which I would update frequently with these historical stats, then call them directly in my view. Thank you, Pierre -
deploy python django rest framework app in heroku
I am trying to deploy my Django Rest FrameWork project in Heroku but I got "Deployment failed" no module named 'rest_framework' Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/app/.heroku/python/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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' I tried this command in my vscode terminal heroku run pip install djangorestframework to try to install it in Heroku, I got a message successffuly installed but always deployement failed. How can I fix this issue? When I do heroku run pip freeze : appdirs==1.4.4 asgiref==3.4.1 certifi==2021.5.30 distlib==0.3.2 dj-database-url==0.5.0 Django==3.2.5 django-heroku==0.3.1 filelock==3.0.12 gunicorn==20.1.0 pipenv==2020.11.15 psycopg2==2.9.1 psycopg2-binary==2.9.1 pytz==2021.1 six==1.16.0 sqlparse==0.4.1 virtualenv==20.4.7 virtualenv-clone==0.5.4 whitenoise==5.2.0 djangorestframework doesn't exist. my .gitignore file: venv *.pyc staticfiles .env *.sqlite3 my Pipfile: [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [requires] python_version = "3.6" [packages] "psycopg2-binary" = "*" django-heroku … -
Formsets + Many to Many Relationship Problem
I have partially implemented the formsets + many to many relationship feature with an Invoice and Inventory Model. My problem is the form does not show the available Inventory (even though they exist). See problem here: https://www.dropbox.com/s/mtqkfee2pisyh5a/dj005_formset_many_to_many_relationship_working.jpg?dl=0 Here is the working code: # MODELS.PY class Invoice_Test_M2M(models.Model): id = models.BigAutoField(primary_key=True) ref_num = models.CharField(max_length=100) def __str__(self): return self.ref_num class Inventory_Test_M2M(models.Model): id = models.BigAutoField(primary_key=True) inventory_name = models.CharField(blank=True, max_length=100) invoice = models.ManyToManyField('Invoice_Test_M2M', through= "Invoice_Inventory_Through") def __str__(self): return self.inventory_name class Invoice_Inventory_Through(models.Model): invoice = models.ForeignKey(Invoice_Test_M2M, on_delete=models.CASCADE) inventory = models.ForeignKey(Inventory_Test_M2M, on_delete=models.CASCADE) price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) quantity = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) amount = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) # FORMS.PY Inventory_TestLineItem_M2M_Formset = inlineformset_factory(Invoice_Test_M2M, Invoice_Inventory_Through, fields = '__all__', exclude=[], can_delete=True) # VIEWS.PY class Invoice_M2M_CreateView(CreateView): model = Invoice_Test_M2M fields = '__all__' def get_context_data(self, **kwargs): context = super(Invoice_M2M_CreateView, self).get_context_data(**kwargs) if self.request.POST: context['track_formset'] = Inventory_TestLineItem_M2M_Formset(self.request.POST) else: context['track_formset'] = Inventory_TestLineItem_M2M_Formset() return context def form_valid(self, form): context = self.get_context_data(form=form) formset = context['track_formset'] if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) Is there a way around this? PS. INTERESTINGLY, if I just use a pseudo many to many MODEL (i.e. using a foreign field and not a many to many field). It works. You can see it … -
Send_email with django generate error _getfullpathname:
i'm tring to send email with django but i recive ad error even with a easy code send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) i get that output error Traceback (most recent call last): File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\VisualStudioWorkspaces\DjangoPlayground\django_tutorial\accounts\views.py", line 93, in register send_mail( File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\__init__.py", line 52, in send_mail connection = connection or get_connection( File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\__init__.py", line 35, in get_connection return klass(fail_silently=fail_silently, **kwds) File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\backends\filebased.py", line 20, in __init__ self.file_path = os.path.abspath(self.file_path) File "C:\Users\oscur\AppData\Local\Programs\Python\Python39\lib\ntpath.py", line 527, in abspath return normpath(_getfullpathname(path)) Exception Type: TypeError at /accounts/registration/ Exception Value: _getfullpathname: path should be string, bytes or os.PathLike, not NoneType -
How to add error messages in login and registration form in Django
I am creating a website with Django. I want to add an error message to the login and registration form, so if I click on the login / register button and have some fields filled in incorrectly or the username is already in use, a message will appear below each form field. I've already tried form.errors, but I couldn't style it with CSS and I also couldn't edit the text that showed up when I filled in some field wrong. This is my login.html template: {% extends 'base.html' %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static "/css/login.css" %}"> <div class="square-form"> <form method="post" class="form-group"> {% csrf_token %} <div class="username"> <p class="username-p">Uživatelské jméno:</p> <div>{{ form.username }}</div> </div> <div class="password"> <p class="password-p">Heslo:</p> <div>{{ form.password }}</div> </div> <p class="havent-account">Nemáte ještě účet? Vytvořte si ho zdarma <a href="/register">zde</a></p> <button type="submit" class="btn-btn-succes">Přihlásit se</button> </form> </div> {% endblock %} And this is my register.html template: {% extends "base.html" %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static "/css/register.css" %}"> <div class="square-form"> <form method="POST" class="form-group"> {% csrf_token %} <div class="username"> <p class="username-p">Uživatelské jméno*:</p> <div>{{ form.username }}</div> </div> <div class="email"> <p class="email-p">Email*:</p> <div>{{ form.email }}</div> </div> <div class="password1"> … -
How can I configure Flask to behave like Django?
I'm new to Python frameworks. I've read Flask is more flexible than Django, but the Django design choices are very solid. My question is, can you extend Flask to adopt those same choices and work in a similar way? If so, how? (Don't worry, I'm looking for a broad answer, not a full configuration manual :D) -
I want to Pass the text inside anchor tag when clicked on that tag and to show the same text on the directed page
This is my discover.html file <form action="POST"> <div class="swipe-area"> <div class="swiper-container mySwiper"> <div class="swiper-wrapper"> {% for topic in topics %} <div class="swiper-slide"> <a href="{% url 'content' %}" style="color: white; text-decoration: none;"> <h1 name="headings" data-tooltip="{{ topic.description }}" data-tooltip-location="bottom"> {{ topic.heading }} </h1> </a> </div> {% endfor %} </div> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> </div> <!-- <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> --> </div> </form> I want to pass the value of h1 tag that is {{ topic.heading }} when clicked on that link to the page that link takes me. <a href="{% url 'content' %}" style="color: white; text-decoration: none;"> <h1 name="headings" data-tooltip="{{ topic.description }}" data-tooltip-location="bottom"> {{ topic.heading }} </h1> </a> Below is my views.py file def content(request): heading = request.GET['headings'] content = Search.objects.all().filter(title__contains = heading) context = {'content': content} return render(request, 'search/content.html', context) So I want that variable value in my content.html page. Please tell me how to tackle this problem, I have been stuck here for 2 weeks. -
Django to return a view with TokenAuthentication for WebView
I am trying to create a flutter app which will use webview to display authenticated data from my Django App. Steps Involved: Flutter app sends authentication request Django validates the user credentials (user id & Password) and returns authtoken Flutter then sends a request via a webview to a url (which requires login). I would like to login the user in webapp using this token and return the webview. If the url does not require authentcation, it works like a charm. When the url requires authentication, I am redirected to the login page and I want users to bypass that using token authentication which is already aquired in Step 1 here is my Django view. class QuizTake(FormView): permission_classes = (IsAuthenticated,) form_class = QuestionForm template_name = 'question.html' result_template_name = 'result.html' single_complete_template_name = 'single_complete.html' login_template_name='login.html' def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) print(self.kwargs['quiz_name']) """ Authenticate if the request has token authentication """ if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: print("sitting false") if self.logged_in_user: return render(request, self.single_complete_template_name) else: redirecturl = "/login/?next=/quiz/"+self.kwargs['quiz_name']+"/take/" return redirect(redirecturl) return super(QuizTake, self).dispatch(request, *args, **kwargs) … -
Django sqlite3 migration for trigger failing with "OperationalError: incomplete input" despite functional SQL code
I wanted to implement a trigger in a hobby project of mine which uses an sqlite3 database. For this purpose I wrote a custom-migration that runs custom-sql code. When trying to execute this specific trigger, the migration fails with the stacktrace below. What is odd however is that at the same time: The SQL Code for the trigger on its own works fine. When I execute it directly on the database (through sqlitebrowser), there is no error (see the specific query in migration file below) and the trigger shows up as expected. The migration process on its own works fine. I was able to migrate with the migration file shown below as long as I swapped out the migration.RunSQL code for that of a much simpler trigger also shown below. It is only when I use the two together that I get an error. Given that the code of the migrations.RunSQL call itself (as the only variable left) also looks perfectly fine to me, I am at a bit of a loss. What am I doing wrong? SIDENOTE: If there are ways of writing triggers inside of Django, I would welcome them, but still rather get this way to work … -
Why do i keep getting page not found error
i have been trying to solve this problem but it keep showing 'page not found' whenever i run the program. Here is the problem, i am using python and django to write a message in a browser but i keep getting the page not found error. here is the code for views.py `from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello world') def news(request): return HttpResponse('Here is the news') ` and here is the urls.py `from django.urls import path from . import views urlpatterns = [ path('', views.index), path('news', views.news) ] ` in my browser, if run http://127.0.0.1:8000/products it prints the out put 'Hello world" but when ever i run this http://127.0.0.1:8000/products/news or http://127.0.0.1:8000/products/new it shows page not found error and i change my code of urls.py to urlpatterns = [ path('', views.news) ] it get executed. So i don't know what's wrong with the code. Thanks. -
Render data in a table on a Django template from multiple tables after filtering
I am new to Django and any help on my query is appreciated. I am trying to create an inventory portal and want to display summary information in the template as a table. models.py class Location(models.Model): location_name = models.CharField(max_length=5) ....< other attributes > class Rack(models.Model): location = models.ForeignKey(Location, on_delete=models.SET_NULL) rack_id = models.CharField(max_length=10) ....< other attributes > class Equipment(models.Model): rack_id = models.ForeignKey(Rack,on_delete=models.SET_NULL) make = models.CharField(max_length=20) model = models.CharField(max_length=20) type = models.CharField(max_length=20) ....< other attributes > My query There are several equipments installed on a rack (such as Comms equip, Processing equip, etc.,) which in turn is available on a location. I want to render summary information onto a template where the first column should be location_name, the second column the count of comms equipment in that location, and the third column count of processing equip, and so on. | Location | Comms Equip | Processing Equip | | -------- | ----------- | ---------------- | | Loc1 | 5 | 8 | | Loc2 | 2 | 10 | I can obtain the first column by: views.py location = Location.objects.all() context = {'location': location, } return render(request, 'appname/summary.html', context) summary.html {% for x in location %} {{ x.location_name }} For second and … -
Handling user registrations Using only Django without the need to be redirected to other template
This is my view class UserRegistrationView(FormView): template_name = "register/register_form.html" form_class = None extra_fields_form_page_slug = "" email_template = "register/account_activation_email.html" def get_form(self, form_class=None): form = super().get_form(form_class) add_extra_fields( form.fields, form.helper.layout.fields, self.extra_fields_form_page_slug ) return form def get_extra_form(self): return FormPage.objects.filter(slug=self.extra_fields_form_page_slug).first() def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() email = form.cleaned_data.get("email") email_template = "register/account_activation_email.html" send_confirmation_email( self, "Activate Your Account", user, email, email_template ) return render(self.request, "register/after_submission.html") This is working fine (registration wise) but it's not from many other sides, because I have the registration form as a pop up window in the header, so it's available throughout the whole website, my problems are: if the user had a successful registration they will be redirected to the specified template "after_submission" what I want is to stay on the same page and display a pop up with some message if the user had an unsuccessful registration they will be redirected to the main template "register_form.html" with the errors displayed their, what I want is to stay on the same page and to display the error messages on the pop up form if the user opened it again is this achievable using only Django?? or I must throw some JS in there, and if JS is … -
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
I am trying to create a custom user model for my project model.py class ShopkeeperRegTable(AbstractBaseUser, PermissionsMixin): uu = models.UUIDField(unique=True, default=uuid.uuid4) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=50,default=None,null=True) email = models.CharField(_('email address'), max_length=200, unique=True) phone_number = models.BigIntegerField(unique=True) enable_wp = models.BooleanField(default=False) bucket = models.CharField(null=True, blank=True, max_length=200) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) created_on = models.DateTimeField(auto_now_add=True, null=True, blank=True) last_login = models.DateTimeField(null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','phone_number'] objects = CustomUserManager() def __str__(self): return self.email CustomUserManager() class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user serializer.py enter class ShopkeeperRegTableSerializer(serializers.ModelSerializer): class Meta: model = ShopkeeperRegTable fields = "__all__" extra_kwargs = { 'password' : {'write_only':True} } def … -
Prevent superuser account from logging into django website
I have encountered a problem in Django. When I login into Django admin using the superuser account and reload the actual website the superuser also gets logged in into the website rather than only admin page (I guess its a normal behavior as superuser is also a user). How do I prevent the superuser from being logged in into website. def user_login(request): resp = dict() if request.method == "POST": login_username = request.POST.get('uname') login_password = request.POST.get('password') user = authenticate(username=login_username, password=login_password) if user is not None and login_username != 'ruturajK': login(request, user) resp['invaliduser'] = False resp['redirect'] = True resp['message'] = "" else: resp['invaliduser'] = True resp['redirect'] = False resp['message'] = "Invalid Credentials" return HttpResponse(json.dumps(resp), content_type="application/json") return HttpResponse("404 not found") The account ruturajK is a superuser account Superuser also logged in into website This function is called by the url in urls.py path('login', views.user_login, name='login') I have also seen that when I login using any other account(nonstaff) I cant login into backend Nonstaff user I see this after reloading admin page -
502 Bad Gateway nginx
I wanted to add indexes to optimize sql queries, after adding I start the server and get nginx-proxy_1 | nginx.1 | 2021/07/02 12:50:43 [error] 40#40: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.19.0.1, server: api.localhost, request: "GET /api/procurements/ HTTP/1.1", upstream: "http://172.19.0.2:80/api/procurements/", host: "api.localhost" nginx-proxy_1 | nginx.1 | api.localhost 172.19.0.1 - - [02/Jul/2021:12:50:43 +0000] "GET /api/procurements/ HTTP/1.1" 502 559 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36" "172.19.0.2:80" After, I canceled all the changes, returned everything as it was, i completely stop the whole process with Ctrl + C, then I raise the server with docker-compose up, but I still get 502 Bad Gateway I absolutely do not understand anything in the project and I do not know which files to show you to make it easier for you to understand what the problem is, but I am always in touch and will throw off any files, just tell me Thanks for any help and advice. -
Django get True/False if field has data
In a Django queryset I have the following: class Address(models.Model): building town geo_lat geo_lng queryset = Address.objects.all() What i want to do is return True or False field if both geo fields are set. This would allow me to show that we need to update geo data as some are missing. I assume I need to annotate or something but cant find what i need to use. I dont want to filter out any, but add an extra field I can use to test if true or false) -
Django gives errors when running the server
So, I'm very new to the concept of Django but I'm very familiar with python and tried to learn Django using YouTube. Turns out, that whenever I try to run the server after following the steps they have mentioned, I get the same error. So I also decided to look upon StackOverflow for some answers, and all the answers were not of any use to my problem. And thus I finally post my problem here. Please help. I get an error message for the rest_framework and wsgi_application This is the error returned after attempting to run the server: C:\Users\name\OneDrive\Documents\ZZZ\Coding\React-Django\music_app>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 02, 2021 - 18:06:25 Django version 3.2.4, using settings 'music_app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\name\anaconda3\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\name\anaconda3\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\name\anaconda3\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = …