Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving value of one model field count to another field of the same model during save
I am working on a pool app and want to add the total_likes attribute to the model which will allow me to count the number of users who liked the question just like Youtube community question allows. I just tried to override the save(*args, **kwargs) but got many error. what should I do now from django.db import models from django.contrib.auth.models import User class Question(models.Model): enter code here text = models.TextField() voters = models.ManyToManyField(to=User, blank=True, related_name='voters') impression = models.CharField(max_length=30, choices=impression_choices, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(to=User, related_name='likes', blank=True) total_likes = models.IntegerField(default=0) def __str__(self): return self.text def save(self, *args, **kwargs): self.total_likes = self.likes_set.count() super().save(*args, **kwargs) The Model below works totally fine. In the model above I tried to override the save() method but don't know how to? class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=20) votes = models.IntegerField(blank=True, default=0) def __str__(self): return self.text -
Django - Settings.py, urls.py and views.py resulting in 404 error
Recently I came across a 404 error when running my Django Project. I can't figure it out for some reason and I need help. I'm new to django and coding in general. Here is the error Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin index.html [name='index'] experience.html [name='experience'] projects.html [name='projects'] research.html [name='research'] education.html [name='education'] 404.html [name='comeback'] design.html [name='design'] The empty path didn’t match any of these. Here is the program code. Here is views.py from django.shortcuts import render def index(request): return render(request, 'index.html', {}), def experience(request): return render(request, 'experience.html', {}), def projects(request): return render(request, 'projects.html', {}), def research(request): return render(request, 'research.html', {}), def education(request): return render(request, 'education.html', {}), def comeback(request): return render(request, '404.html', {}), def design(request): return render(request, 'design.html', {}), Here is urls.py (app) from django.urls import path from . import views urlpatterns = [ path('index.html', views.index, name="index"), path('experience.html', views.experience, name="experience"), path('projects.html', views.projects, name="projects"), path('research.html', views.research, name="research"), path('education.html', views.education, name="education"), path('404.html', views.comeback, name="comeback"), path('design.html', views.design, name="design"), ] Here is urls.py (where settings is) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] Here are the settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent … -
Trobles to load a partial for a dependent drop-down list in a Django template
I'm trying to implement a dependent drop down list between countries and cities, but the document responsible to load the cities doesn't load. I'm trying to solve this problem since 3 days and I don't get a clue. The database has no problem because I tested it with non-ajax requests. And it is not a database problem, because the entire partial doesn't load. The most probable cause of the problem is that I based some code on online tutorial which probably use old versions either of JQuery or Django. But, here's the code Models.py from django.db import models class Country(models.Model): class Meta: db_table = 'countries' name = models.CharField(max_length=300) def __str__(self): return self.name class City(models.Model): class Meta: db_table = 'cities' name = models.CharField(max_length=300) state_id = models.BigIntegerField(null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class Person(models.Model): class Meta: db_table = 'people' name = models.CharField(max_length=300) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name Forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city') """ right now we are overriding the default init method, and setting the queryset of the … -
Mono crash after python file was edited and saved
I'm coding to call C#.Net dll file from Django Python Project. I think there is no error or warning was occurred in source. But I edited python file and saved while Django was running. And following error was occurred. ================================================================= Native Crash Reporting ================================================================= Got a SIGSEGV while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application. ================================================================= ================================================================= Native stacktrace: ================================================================= 0xffff9bca02fc - /lib/libmonosgen-2.0.so.1 : 0xffff9bca0624 - /lib/libmonosgen-2.0.so.1 : 0xffff9bc5b1e0 - /lib/libmonosgen-2.0.so.1 : 0xffff9bbd914c - /lib/libmonosgen-2.0.so.1 : 0xffffa5eb75b8 - linux-vdso.so.1 : __kernel_rt_sigreturn 0xffff9bbe1d44 - /lib/libmonosgen-2.0.so.1 : 0xffff9bd9edd0 - /lib/libmonosgen-2.0.so.1 : 0xffff9bda2280 - /lib/libmonosgen-2.0.so.1 : mono_runtime_invoke 0xffffa065fff8 - /home/phyo/lib/python3.8/site-packages/cffi.libs/libffi-3d8725bd.so.6.0.1 : ffi_call_SYSV 0xffffa066096c - /home/phyo/lib/python3.8/site-packages/cffi.libs/libffi-3d8725bd.so.6.0.1 : ffi_call 0xffffa41d2904 - /home/phyo/lib/python3.8/site-packages/_cffi_backend.cpython-38-aarch64-linux-gnu.so : 0x5939dc - /home/phyo/bin/python : _PyObject_MakeTpCall 0x501e20 - /home/phyo/bin/python : _PyEval_EvalFrameDefault 0x5932c0 - /home/phyo/bin/python : _PyFunction_Vectorcall 0x593dd0 - /home/phyo/bin/python : _PyObject_FastCallDict 0x594094 - /home/phyo/bin/python : _PyObject_Call_Prepend 0x67a830 - /home/phyo/bin/python : 0x5939dc - /home/phyo/bin/python : _PyObject_MakeTpCall 0x501e20 - /home/phyo/bin/python : _PyEval_EvalFrameDefault 0x5932c0 - /home/phyo/bin/python : _PyFunction_Vectorcall 0x593dd0 - /home/phyo/bin/python : _PyObject_FastCallDict 0x594094 - /home/phyo/bin/python : _PyObject_Call_Prepend 0x67a830 - /home/phyo/bin/python : 0x5939dc - /home/phyo/bin/python : _PyObject_MakeTpCall 0x5019c8 - /home/phyo/bin/python : _PyEval_EvalFrameDefault 0x5932c0 - /home/phyo/bin/python : _PyFunction_Vectorcall 0x59268c - /home/phyo/bin/python … -
Django Form not updating data in the model
this is my first Django project and I am stuck. If not a solution, but just a hint on what I am doing wrong will be truly appreciated. I have a model with one attribute set as Null by default and I want to use a Form to update that attribute with the ID taken from another model. These are the 2 models: models.py class Squad(models.Model): squad_name = models.CharField(max_length=20) def __str__(self): return self.squad_name class AvailablePlayer(models.Model): player_name = models.CharField(max_length=25) squad = models.ForeignKey(Squad, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.player_name This is the form: forms.py class AddSquadToPlayerForm(forms.Form): # squad the player will be added to squad_to_player = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): super(AddSquadToPlayerForm, self).__init__() self.fields['squad_to_player'].queryset = AvailablePlayer.objects.all() This is the view file, where I think something is missing/wrong: views.py def add_player_to_squad(request, squad_id): # player = AvailablePlayer.objects.get(id=squad_id) squad = Squad.objects.get(id=squad_id) if request.method == "POST": form = AddPlayerToSquadForm(request.POST) if form.is_valid(): form.squad = form.cleaned_data['id'] form.save() return redirect('fanta_soccer_app:squad', squad_id=squad_id) else: form = AddPlayerToSquadForm(queryset=AvailablePlayer.objects.all()) context = {"squad": squad, "form": form} return render(request, 'fanta_soccer_app/add_player.html', context) And finally, this is html file add_player.html <body> <p>Add a new player to the Squad:</p> <p><a href="{% url 'fanta_soccer_app:squad' squad.id %}">{{ squad }}</a></p> <form action="{% url 'fanta_soccer_app:add_player' squad.id %}" method="POST"> {% csrf_token %} … -
How do I access instance of a many-to-many field in django __str__ method
I am having two models; class Cart(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="book") quantity = models.PositiveIntegerField(default=1, null=True, blank=True) def __str__(self): return f"{self.quantity} of {self.book.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cart = models.ManyToManyField(Cart) def __str__(self): return f"{self.cart.quantity}" I get 'ManyRelatedManager' object has no attribute 'quantity'. This usually works for a foreignkey field; but it seems not to for a many-to-many field. Note: I am trying to access quantity that belongs to the cart model from the Order model using manytomany field. Is there any way of doing something like this? -
2.0.7 Django Operational Error No Such Table
I am just learning Django and I am attempting to make my own app called products. I have run python manage.py startapp products in PowerShell to create the app. The purpose was just a very simple app to store data on products. I will also post my settings.py, models.py, and admin.py for reference models.py # Create your models here. class Product(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() summary = models.TextField(default = 'This is the default response') settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # own 'products', ] admin.py from django.contrib import admin # Register your models here. from .models import Product admin.site.register(Product) I did then run both python manage.py makemigrations and python manage.py migrate both of these worked and detected the new migration Product. This also showed up on my admin page as shown here Django Admin It worked as expected all the TextFields were present, but when I clicked save I got this operational error back Error I am a bit lost as to what to do from here any help would be much appreciated. -
Django can't import module due to a circular import
Following a tutorial and am have the module views.py file #attempt2/src/products/views.py from django.shortcuts import render from .forms import ProductForm, RawProductForm from .models import Product def product_create_view(request): #this creates an instance of that form my_form = RawProductForm() context = { "form": my_form } return render(request, "product/product_create.html", context) But I get the following error File "C:\Users\dancc\dev2\attempt2\src\products\views.py", line 2, in <module> from .forms import ProductForm, RawProductForm File "C:\Users\dancc\dev2\attempt2\src\products\forms.py", line 4, in <module> from products.views import product_create_view ImportError: cannot import name 'product_create_view' from partially initialized module 'products.views' (most likely due to a circular import) (C:\Users\dancc\dev2\attempt2\src\products\views.py) I've tried searching to see where it might be importing a different product_create_view but there is not another one, none of the files or folders' names repeat this is forms.py #attempt2/src/products/forms.py from django import forms from products.views import product_create_view from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price' ] #This is what product_create_view is using class RawProductForm(forms.Form): title = forms.CharField() description = forms.CharField() price = forms.DecimalField() This is models.py file #attempt2/src/products/models.py from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) #max_length required description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10000) summary = models.TextField() This is views.py … -
Test with customized auth_user model
I have a customized auth_user model in my application name "test-app". Here is how I create migration file: python3 manage.py makemigration test-app It will generate auth_user fine in 0001_initial Now when I try to run python3 manage.py migrate I will get: django.db.utils.ProgrammingError: relation "auth_user" does not exist I assume it has something to do with me customizing auth_user model. So I run migration with python3 manage.py migrate test-app Everything works. Now the issue is when I run the tests with python3 manage.py test It throws the exact same error: relation "auth_user" does not exist, hence the test db's table cannot be populated correctly. I can't seem to find an option to tell the test db to create with specific app tag and it looks like it' just running python3 manage.py migrate. Any help is appreciated :) -
How to properly redirect to new template using uuid as url slug in view
I have the following source template which renders the uuid of model Pollers as a hidden <a> tag to redirect the user to this item rendered in a fresh new template upon user click. <div class="poller-wrapper"> <a class="hidden_poller_id" href="/poller/{{ poller.poller_id }}"> <div class="poller-text">{{ poller.poller_text }}</div> [...] The url mapping looks like follows: urlpatterns = [ # Main overview of recent pollers path('pollboard/', pollboard, name='pollboard'), # Redirect url to single Poller path('poller/<uuid:poller_id>', single_poller, name='single_poller'), ] View def single_poller(request): return render(request, 'pollboard/single_poller.html') Right now I get the following error and I'm not sure why it doesn't redirect properly: TypeError at /poller/d251ce80-1d0d-41c4-a096-c12bdd2399f8 single_poller() got an unexpected keyword argument 'poller_id' -
Django-Why doesn't the likes system work?
Why is the likes system not working? Аfter clicking on the "like" button I get an error. class ImageDetail(DetailView): model=Image template_name='images/image/detail.html' context_object_name='image' def get_queryset(self): return Image.objects.filter(id=self.kwargs.get('id'),slug=self.kwargs['slug']) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) likes_connected=get_object_or_404(Image, id=self.kwargs['id'],slug=self.kwargs['slug']) liked=False if likes_connected.users_like.filter(id=self.request.user.id).exists(): liked=True data['number_of_likes']=likes_connected.number_of_likes() data['post_is_liked']=liked return data def ImagePostLike(request,id,slug): image=get_object_or_404(Image, id=request.POST.get('image_id'), slug=request.POST.get('image_slug')) if image.users_like.filter(id=request.user.id).exists(): image.users_like.remove(request.user) else: image.users_like.add(request.user) return HttpResponseRedirect(reverse('image_detail', args=[self.id, self.slug])) Why is the likes system not working? Аfter clicking on the "like" button I get an error. urls.py from django.urls import path,include from . import views app_name = 'images' urlpatterns = [ path('create/', views.image_create, name='create'), path('detail/<int:id>/<slug:slug>/', views.ImageDetail.as_view(), name='image_detail'), path('image_like/<int:id>/<slug:slug>/', views.ImagePostLike, name='image_like'), ] Why is the likes system not working? Аfter clicking on the "like" button I get an error. detail.html {% extends 'base.html' %} {% load thumbnail %} {% block title %}{{image.title}}{% endblock title %} {% block content %} <h1>{{ image.title }}</h1> <img src="{{ image.url }}" class="image-detail"> {% if user.is_authenticated %} <form action="{% url 'images:image_like' image.id image.slug%}"> {% csrf_token %} {% if post_is_liked %} <button type="submit" name="image_id" value="{{image.id}}" class="btn btn-info">Unlike</button> {% else %} <button type="submit" name="image_id" value="{{image.id}}" class="btn btn-info">Like</button> {% endif %} </form> {% else %} <a class="btn btn-outline-info" href="{% url 'login' %}?next={{request.path}}">>Log in to like this article!</a><br> {% endif %} <strong class="text-secondary">{{ number_of_likes … -
How to redirect to a new template using already rendered data in django
I do have a model called Pollers which consists of individual questions asked by users. One template renders an overview of the latest questions asked. Now I would like to redirect the user to a new template for a specific question upon click of its container. Now my understanding is that I would define a url that contains a <slug:slug> field to catch some data from the first template to query the correct item from the database to render the new template. But how do I grab the data (in my case it would probably be the UUID?) pass the data to the url and use it in a new view to query the database for this certain question? Model class Questions(models.Model): # Assign unique ID to each poller poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # Assign timestamp of creation created_at = models.DateTimeField(auto_now_add=True) # Assign the user who created the poller by her ID via user session created_by = models.CharField(max_length=100) # Poller Text poller_text = models.CharField(max_length=250) # Choices given by user poller_choice_one = models.CharField(max_length=30) poller_choice_two = models.CharField(max_length=30) [...] View def pollboard(request): # Query Pollers questions_queryset = Questions.objects.all() # Convert to list qs_list = list(questions_queryset) # Shuffle the list shuffle(qs_list) # Create … -
What is an efficient way of inserting hundreds of records into an SQLite table using Django?
I have a CSV file with hundreds of data, I want to insert everything into my SQLite DB in my Django app. Inputting each value one by one will be a complete waste of time. What is a more efficient way to approach this? -
Best practice for sending POST request from client side to Django models?
Relatively new to Django so apologies if I'm not getting all the wording here right. I'm sending data from my client side (React) to my models through a POST request. Django can handle this either through its class-based views, something like this: views.py class ListCreateView(ListCreateAPIView): queryset = Users.objects.all() serializer_class = UsersSerializer serializers.py class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = "__all__" urls.py urlpatterns = [ path('', ListCreateView.as_view()), ] or through something like this: views.py def create_user(request): if request.method == 'POST': response=json.loads(request.body) user_db = Users() user_db.user = response['user'] user_db.save() return(HttpResponse(200)) What's better? I'm using something similar to both of these, and they both work. What should I be thinking about? Thanks. -
PostgreSQL error "unable to connect to server
I start learning Django, and I had a problem using the Postegres database, The server worked fine with sqlite3, but as soon as I declared Postgres in the project, the server stopped working DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # on utilise l'adaptateur postgresql 'NAME': 'sarah disquaires', # le nom de notre base de donnees creee precedemment 'USER': 'sarra', # attention : remplacez par votre nom d'utilisateur 'PASSWORD': '', 'HOST': '', 'PORT': '5432', } } I get this error: python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", … -
Django adding words to image url
I want to load an image on my template using: <img src="{{ item.pic }}"> It works fine sometimes but once I start doing it from a view it adds the path of that view to my image src automatically causing the image to fail to load. I want it to be src="images/item.jpg" for example, but because of different views it may end up as "view1/images/item.jpg" or "anotherview/images/item.jpg" causing Django to be unable to find the image. Is there a way to code it so that view names won't be added to the src? -
Django filter by looping through each day of a date range
I have a model called Orders which is for an e-commerce web-app and I'd like to know how many orders was made from each day in the past year. so I filtered the Orders as follows: product_orders = Order.objects.filter( ordered=True, variant__product=self, date__range=[(timezone.now() - timedelta(weeks=52)), timezone.now()]) I'd like to loop through each day from this time range and get the number of orders from each day, the result should look something like this: [ { date: "2021-06-21", quantity: 6 }, { date: "2021-06-22", quantity: 0 } ] where the quantity is Order.objects.filter(...).count() -
bulk create for models with foreign key
I have these two models: class Item(models.Model): item_id = models.CharField(max_length=10, primary_key=True) item_name = models.CharField(max_length=100) description = models.CharField(max_length=500) slug = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.item_name class Image(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) image_url = models.CharField(max_length=200) I have a lot of items, and each Item has some images assigned to it. To add items in the database, I do it through a bulk create: it = (Item( item_id = item['id'], item_name= item['title'], description = item['description'], slug = item['slug'], price = item['price']['amount'] ) for item in items ) while True: batch = list(islice(it, batch_size)) if not batch: break Item.objects.bulk_create(batch, batch_size) This works perfectly fine, ok. But I want to do the same with the images, since I have too many images to do it individually. For now I do it like this: for item in items: for image in item['images']: Item.objects.get(item_id = item['id']).image_set.create(image_url = image['urls']['big']) But this is too slow in uplaoding all the Images (it may take 30 minutes), so I want to upload in bulk like I do it with Item, but since Image model has Item as a foreign key, I cannot do it the same way. How can I upload Images in a more efficient manner? I … -
Where to store media file of Django on production?
So I am learning Django. And I have made some websites with it. Now I am hosting those to Heroku. I am using free Dyno on Heroku. Also, I am using supabase.io database instead of Heroku's because supabase gives more space for the database on the free tier. Now the problem I am facing is with the media files. I can not access them on Heroku since I don't have any place to store them. I have seen some addons on Heroku for the file storage but to use those I need to provide my credit card information, which I do not have. But I have seen an object storage option on supabase.io. It gives 1 GB free storage which is more than enough for me now. But I don't know how can I use it with my Django application. That is why I am looking for help. Also if there are any free alternatives to store my media file without credit card information, please feel free to guide me. Since I do not own any card. -
How to fix "Failed to restart gunicorn.service: Unit gunicorn.socket not found." error?
I'm trying to deploy a django application to a DigitalOcean droplet. I created a systemd service to start gunicorn on boot. Here is my config file: (/etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data Environment="DJANGO_SETTINGS_MODULE=core.settings.production" WorkingDirectory=/home/myproject-api/src ExecStart=/home/myproject-api/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock core.wsgi:application [Install] WantedBy=multi-user.target When I run "ExecStart" line on directly on terminal, it works. But I cant start the gunicorn service. I get this error when I try to start gunicorn: Failed to start gunicorn.service: Unit gunicorn.socket not found. I checked the gunicorn executable, it exists: test -f /home/myproject-api/env/bin/gunicorn && echo "Gunicorn exists." I'm able to run server with gunicorn --bind 0.0.0.0:8000 core.wsgicommand. When I run like this, i can access the server using the server's IP address. Normally, the socket file should been created when I start the server. Also I tried to create the socket file with "touch /run/gunicorn.sock" but it didn't work. I double-checked file and directory names. No mistake. How can I solve this problem? -
how to login a user with email or username in django custom user model
This is my current code can anyone please add the required code to allow a user to login with email or username backends.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend, UserModel class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field: username}) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user -
Cannot switch EMAIL_BACKEND to smtp.EmailBackend
I have a weird problem although my settings.py file specifically says EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" my Django app still uses django.core.mail.backends.console.EmailBackend, how can that be? No matter if I have debug True or False # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" DEFAULT_FROM_EMAIL = "yes@gmail.com" SERVER_EMAIL = "yes@gmail.com" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "yes@gmail.com" EMAIL_HOST_PASSWORD = "yes" EMAIL_USE_TLS = True EMAIL_USE_SSL = False -
ModuleNotFoundError: No module named 'fontawesomefree'
I am getting this error when I try to import fonrawesomefree icons to my django project. I used official django docs requirements.txt file have following # some other requirements fontawesomefree==5.15.4 settings.py have following: INSTALLED_APPS = [ # some other installed apps 'fontawesomefree', ] base.html file have following <head> #some other link & script files <link href="{% static 'fontawesomefree/css/all.min.css' %}" rel="stylesheet" type="text/css"> </head> Project structure [projectname]/ ├── [projectname]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | |── [App1] |── [static]/ | ├── [css] | ├── [Javascript] | └── [Images] | |── [templates] |── manage.py └── requirements.txt When I try to run server I get following error: ModuleNotFoundError: No module named 'fontawesomefree' Any help is appreciated -
how to use an authentication api in frontend part django
I implemented a login and register API that I want to use in frontend part of the project. I could use some clarifications about the mechanism of using an API for login and register request so I can understand what is wrong. here is my code : user_registration.html {% extends 'core/base.html' %} {% block head_title %}Banking System{% endblock %} {% block content %} <h1 class="font-mono font-bold text-3xl text-center pb-5 pt-10">Register</h1> <hr /> <div class="w-full mt-10"> <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {% csrf_token %} <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> First Name </label> <input name="firstname" type="text" placeholder="Your first Name" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 'rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"> </div> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> Last Name </label> <input name="lastname" type="text" placeholder="Your last Name" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 'rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> Email </label> <input name="email" type="text" placeholder="user@example.com" class="appearance-none block w-full bg-gray-200 text-gray-700 border … -
Pass dynamic choice list to form from Views in class based views
I just want to pass a list which will look like this from views to form , FYI i'm using MultipleChoiceField [('ad7d4d7c5fbd4678bafd9f2b93fdd4b5', 'Chandrayaan'), ('b55d7c02c29d4501b8d3f63053fef470', 'MOM'), ('b90a66ea9eb24d019102fadde900fdda', 'Galactica')] i have another issue related to this question as well which i have posted already here