Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can't create user in django
I am trying to create a login and signup feature on my website but for some reason, I can't create a user. and it's not showing any error. I have done these before in another code but I don't know why it is not working in this one. And also when I refresh the website, it asks if it should resubmit the form. These are the codes below index.html <div class="main-register"> <div class="close-reg"><i class="fal fa-times"></i></div> <ul class="tabs-menu fl-wrap no-list-style"> <li class="current"><a href="#tab-1"><i class="fal fa-sign-in-alt"></i> Login</a></li> <li><a href="#tab-2"><i class="fal fa-user-plus"></i> Register</a></li> </ul> <!--tabs --> <div class="tabs-container"> <div class="tab"> <!--tab --> <div id="tab-1" class="tab-content first-tab"> <div class="custom-form"> <form method="post" action="" name="registerform"> {% csrf_token %} {% for message in messages %} <h4 style="color: red;">{{message}}</h4> {% endfor %} <label>Email Address * <span class="dec-icon"><i class="fal fa-user"></i></span></label> <input name="email" type="email" placeholder="Your Mail" onClick="this.select()" value=""> <div class="pass-input-wrap fl-wrap"> <label >Password * <span class="dec-icon"><i class="fal fa-key"></i></span></label> <input name="password" placeholder="Your Password" type="password" autocomplete="off" onClick="this.select()" value="" > <span class="eye"><i class="fal fa-eye"></i> </span> </div> <div class="lost_password"> <a href="#">Lost Your Password?</a> </div> <div class="filter-tags"> <input id="check-a3" type="checkbox" name="check"> <label for="check-a3">Remember me</label> </div> <div class="clearfix"></div> <button type="submit" class="log_btn color-bg"> LogIn </button> </form> </div> </div> <!--tab end --> <!--tab --> <div class="tab"> <div id="tab-2" … -
How to get object uid from previous page in Django web-app?
I`m trying to make a CreateView form that takes the UID of the object as a foreign key from the previous page. Here I got DetailView of Plan model: class PlanDetailView(IsStaffPermissionMixin, DetailView): model = Plan template_name = "backoffice/plans/plan_detail.html" context_object_name = 'plan' def get_object(self): uid = self.kwargs.get("uid") return get_object_or_404(Plan, uid=uid) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) practice_sessions = PracticeSession.objects.all().filter(plan__uid=self.kwargs.get("uid")) context['practice_sessions'] = practice_sessions return context And here I got a PracticeSession CreateView: class PracticeSessionCreateView(IsStaffPermissionMixin, CreateView): model = PracticeSession template_name = "backoffice/practice_session/practice_session_create.html" fields = ['uid', 'title', 'plan', 'snippet', 'welcome_content', 'done_content', 'order_index', ] success_url = reverse_lazy('practice-sessions') As you understand, PracticalSession contains Foreign Key for the Plan model Now I want that when I click on the button to create a PracticalSession (the picture below), I create a form in which the plan field already contains a "uid" of Plan from the page of which I create a new PracticalSession My Form: class PracticeSessionCreateForm(ModelForm): class Meta: model = PracticeSession fields = '__all__' Big THANK YOU In advance !!! -
Having trouble in creating forms in django
This is my models.py file from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=120) created_on = models.DateTimeField(auto_now_add=True) class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=120) body = models.TextField() draft = models.BooleanField(default=False) This is my forms.py file from blog.models import Article from django import forms class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['title', 'body', 'draft'] Can someone tell me how do I insert the first attribute of class Article which is blog in class Articleform? I am learning django and some help will be appreciated. -
Python how to check why 2 things are not equalled
I am trying to run a test to validate that an error is thrown if I try to pick up a closed offer object, but the error is not thrown, because the comparison operator returns false, even though it recognises my offer status as closed. Only relevant code displayed below, not the full actual code: test def test_pickup_closed_offer(self): # open offer created as self.offer in test setup offer = self._CloseOfferWorkflow.close_offer(self.offer.id) logger.debug(offer.status) # CLOSED logger.debug(offer.status == Offer.STATUS.CLOSED) # TRUE with self.assertRaisesMessage(OfferClosedError, "Offer is already closed"): # Failed to raise match = self._PickupOfferWorkflow.pickup_offer( offer_id = offer.id ) django model for Offer from django.db import models from enum import Enum OFFER_STATUS_CHOICES = ( ('AVAILABLE', 'Available'), ('CLOSED', 'Closed') ) class Offer(models.Model): class STATUS(Enum): AVAILABLE = 'AVAILABLE' CLOSED = 'CLOSED' def __str__(self): return self.value status = models.CharField(max_length=256, choices=OFFER_STATUS_CHOICES) pickup_offer method class PickupOfferWorkflow: _OfferController = OfferController() def pickup_offer(self, offer_id): offer = Offer.objects.get(id=offer_id) # Validate input self._OfferController.validate_offer_pickup(offer) OfferController validator def validate_offer_pickup(self, offer): # Validate input self.validate_offer_not_closed(offer.status) def validate_offer_not_closed(self, status): if status == Offer.STATUS.CLOSED: raise OfferClosedError("Offer is already closed", "OFFER_CLOSED") logger.debug(status) #CLOSED logger.debug(Offer.STATUS.CLOSED) #CLOSED logger.debug(status == Offer.STATUS.CLOSED) #FALSE close offer class CloseOfferWorkflow: def close_offer(self, offer_id): offer = Offer.objects.get(id=offer_id) offer.status = Offer.STATUS.CLOSED offer.save() return offer The weird thing is … -
how to pass context (placeholder in my case) to django admin Simple List filter
I am creating a college management system with facility to store quiz/tests in the website and get student performance. I wanted to filter quiz based on month year, such as show all quiz of march 2022. For this purpose, I can not show all months and years in the sidebar, its useless for the first, second it will take lot of space and client has to scroll a lot. So I created a custom Simple Text Input by following some blogs. Here is that generic filter code: class SimpleTextInputFilter(admin.SimpleListFilter): template = 'admin/input_filter.html' def filter(self, request, queryset, value): raise NotImplementedError('Implement this method in subclasses.') def queryset(self, request, queryset): if self.value() is not None: return self.filter(request, queryset, self.value()) def lookups(self, *args, **kwargs): return None def has_output(self): return True def choices(self, changelist): all_choice = next(super().choices(changelist)) all_choice['query_parts'] = ( (k, v) for k, v in changelist.get_filters_params().items() if k != self.parameter_name ) yield all_choice And here is how I am using it: class QuizMonthYearFilter(SimpleTextInputFilter): parameter_name = 'date' title = 'Quiz (Month Year)' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.place_holder = 'MM YYYY' def filter(self, request, queryset, value): try: date = datetime.strptime(value, '%b %Y') except: pass else: return queryset.filter(date__year=date.year, date__month=date.month) and the html is: {% load … -
Django user.checkpassword always returns `FALSE`
I'm using a custom user auth in my Django application, and am trying to login using the API but when I use check_password it always gives me a false even if it's a correct password,, here is my code: CustomUser Model class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.user_type = 'admin' user.save(using=self._db) return user class CustomUser(AbstractUser): user_type_choices = ( ('client', 'Client'), ('supplier', 'Supplier'), ('admin', 'Admin'), ) username=None phone = models.CharField(max_length=200, unique=True,verbose_name=_("Phone"),help_text=_("Phone number of the user")) user_type = models.CharField(max_length=200, choices=user_type_choices,verbose_name=_("Type"),help_text=_("Type of the user"),default='client') company_name = models.CharField(max_length=200,verbose_name=_("Company Name"),help_text=_("Company name of the supplier"),blank=True,null=True) email = models.EmailField(max_length=200,verbose_name=_("Email"),help_text=_("Email of the supplier"),blank=True,null=True) establishment_date = models.DateField(verbose_name=_("Establishment Date"),help_text=_("Establishment date of the supplier's company"),blank=True,null=True) number_of_projects = models.IntegerField(verbose_name=_("Number of projects"),help_text=_("Number of projects the supplier has"),blank=True,null=True) tax_id = models.FileField(upload_to='media/tax_id',verbose_name=_("Tax ID"),help_text=_("Tax ID of the supplier"),blank=True,null=True) logo = models.FileField(upload_to='media/logo',verbose_name=_("Logo"),help_text=_("Logo of the supplier"),blank=True,null=True) business_register = models.FileField(upload_to='media/business_register',verbose_name=_("Business Register"),help_text=_("Business register of the supplier"),blank=True,null=True) about_company = models.TextField(verbose_name=_("About Company"),help_text=_("About company of the supplier"),blank=True,null=True) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") And … -
My django admin page gives Page not found (404)
my project was running ok I used my admin page at it was all all right today I tried to open it and it gives a Page not found (404) No Product matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/admin Raised by: store.views.product_detail No Product matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/admin Raised by: store.views.product_detail I havent touched the store app or project files at all at it was waking just fine yesterday now i cannot access admin page project urls from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls', namespace='store')), path('basket/', include('basket.urls', namespace='basket')), path('account/', include('account.urls', namespace = 'account')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) store urls from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.product_all, name='product_all'), path('<slug:slug>', views.product_detail, name='product_detail'), path('shop/<slug:category_slug>/', views.category_list, name='category_list'), ] store views from urllib import request from django.shortcuts import get_object_or_404, render from store.context_processors import categories from .models import Category, Product def product_all(request): products = Product.products.all() return render(request, 'store/home.html', {'products': products}) def category_list(request, category_slug=None): category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) return render(request, 'store/products/category.html', {'category': category, 'products': products}) def … -
Django issue with urls.py about / after path
I'm starting to learn about DJANGO in one course. And I have my HTML and views.py working good, just if I use the / after the path:: path("create/", views.create, name="create"). In my video aulas I saw that the people usually don't put this /, but if I try like that: path("create", views.create, name="create") I have the error 404 Page not found even using /create in my URL. So, why seems that is just me who need's to use this ( / ) ?? -
Django Inner & Left Join
I'm trying to map SQL to Django ORM but without success. I want to map the below SQL query to Django. Can you help me out? SELECT DCon.Name, Dcon.Address1, FROM Fact FPT JOIN Profile DPP ON DPP.ProfileKey = FPT.ProfileKey JOIN Consignee DCon ON DCon.ConsigneeKey = FPT.ConsigneeKey LEFT Join Country DC ON DC.CountryID = DCon.CountryID and DC.IsCurrent = 'Y' WHERE DPP.trackingCode = SomeTrackingCode AND Dpp.Number = SomeNumber This is what i tried so far data = Fact.objects.select_related("profilekey", "consigneekey") class Fact(models.Model): profilekey = models.ForeignKey( "Profile", on_delete=models.PROTECT, db_column="parcelprofilekey" ) consigneekey = models.ForeignKey( "Consignee", on_delete=models.PROTECT, db_column="consigneekey" ) dateordered = models.DateTimeField() dateprocessed = models.DateTimeField() class Country(models.Model): countryid = models.BigIntegerField() countryname = models.CharField(max_length=64) iscurrent = models.CharField(max_length=1) class Consignee(models.Model): Consigneekey = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=500) countryid = models.BigIntegerField() class Profile(models.Model): dimparcelprofilekey = models.BigIntegerField(primary_key=True) number = models.CharField(max_length=50) trackingcode = models.CharField(max_length=64) -
unable to access image from request in django
I am trying to send images in FormData() from react to django. But not images is recieving in the django server. Other text fields are showing in QueryDict but images are not there. react code - let formdata = new FormData(); formdata.append('title', ref_title.current.value); formdata.append('price',ref_price.current.value); formdata.append('description',ref_desc.current.value); formdata.append('images',ref_image.current.files[0],ref_image.current.files[0].name); console.log(formdata.get('images')); axios.post(url, formdata).then(res => { (res.status == 200)?alert('success'):alert('error'); }) django code - print(request.POST.get('title')) print(request.POST.get('price')) print(request.POST.get('images')) # it is returning None print(request.POST) I am getting the following output in django hello 41 None <QueryDict: {'title': ['hello'], 'price': ['41'], 'description': ['hello world']}> There is no images key in QueryDict. How can I access the image? -
Django : How write a decorator that takes an input after a redirect function
I want to write a decorator that takes an input coming from a redirect function (the value : id_contrat). If I explain a little bit more. An user selects a value in a form, then this value is redirect to another view "home". I want to check that the user has the rights on this value ! So I need to get it in my decorator. How do I add this value to my decorator. I tried something but it is not working : TypeError: wrapper_func() got an unexpected keyword argument 'id_contrat' My views : @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(id_contrat,))) context['form_client'] = form_client return render(request, 'base/selectcontrat.html', context) @authenticated_user @check_user_rights def home(request, id_contrat=None): context = initialize_context(request) return render(request, 'home.html', context) the url definition : from django.urls import path from . import views urlpatterns = [ path('home/<int:id_contrat>/', views.home, name="home"), path('', views.loginAD, name="login"), path('signin', views.sign_in, name='signin'), path('callback', views.callback, name='callback'), path('selectcontrat', views.selectcontrat, name='selectcontrat') the form : class SelectClient(forms.Form): ID_Customer = forms.ChoiceField(label="Company :") def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = AADJNTGroup.objects.filter(ID_User_id=self.user.id).values_list('ID_Group_id', flat=True) id_client_list = list(id_client_list) client_choices = Groups.objects.all().filter(ID__in=id_client_list).values_list('IDCustomer','GroupName') self.fields['ID_Customer'].choices = client_choices the decorator def check_user_rights(id_contrat) … -
how do I get all the objects associated with a foreignkey field
How do I get all the objects associated with the foreignkey field in "ProductImage". So I've multiple images for one "Product" model in "ProductImage", how do I get all of the associated ones. Currently, I'm getting an error "MultipleObjectsReturned at /shop/product-slug" idk what I'm doing wrong, would appreciate it a lot if someone can help! thx! models.py class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() image = models.ImageField(null=True, blank=True) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.ImageField(null=True, blank=True, upload_to='productimg/') urls.py path("<slug:slug>", views.detail_view, name="detail_view"), views.py def detail_view(request, slug): products = Product.objects.get(slug=slug) productimg = ProductImage.objects.get(product=products) -
(Django Allauth) 'CustomUser' object has no attribute 'username'
I'm trying to implement a CustomUser model in Django Allauth. When I used the allauth provided login template, I encountered this error My Customer User Model in users/models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomUserManager(BaseUserManager): def create_superuser(self, email, password=None): if password is None: raise TypeError('Password should not be none') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True if user.is_superuser is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if user.is_staff is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') user.save() return user def create_user(self, email, password=None): if email is None: raise TypeError('Users should have a Email') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google', 'twitter': 'twitter', 'email': 'email'} class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) about = models.TextField(_( 'about'), max_length=500, blank=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.email settings.py """ custom user """ AUTH_USER_MODEL = 'users.CustomUser' """ allauth """ AUTHENTICATION_BACKENDS = [ # Needed to login by username … -
Creating a shopping List in Django Admin
I am trying to show the shopping Cart for only a specific user in the Django Admin template . I managed to do it in a normal views like this : order = Order.objects.get(user=self.request.user, ordered=False) but when trying to do the same inside the model items = models.ManyToManyField(OrderItem.objects.get(user=settings.AUTH_USER_MODEL)) I get this error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. What I'm trying to achieve is to only show the items that the user entered to his shopping cart instead of all the order items in the system so is there a way to filter what is shown in the admin panel based on the user -
The project just stopped loading. everything worked fine yesterday
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\deku0\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\deku0\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self.kwargs) File "C:\Users\deku0\PycharmProjects\pythonProject2\New_venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\deku0\PycharmProjects\pythonProject2\New_venv\lib\site-packages\django\core\management\commands\runserver.py", li ne 134, in inner_run self.check(display_num_errors=True) File "C:\Users\deku0\PycharmProjects\pythonProject2\New_venv\lib\site-packages\django\core\management\base.py", line 487, in che ck all_issues = checks.run_checks( File "C:\Users\deku0\PycharmProjects\pythonProject2\New_venv\lib\site-packages\django\core\checks\registry.py", line 88, in run checks raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (slugg) specified for Tag raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (slugg) specified for Tag -
How to access and print 2d array in template in Django?
I am new to django. I am trying to build a soduku solver in django. When the user inputs the soduku board, I am storing the board in a 9x9 2D list. After the user presses submit I want to print the solved 2D list on the site in a table. Basically I want to access the list elements like arr[1][2] but django throws an error Could not parse the remainder: '[0][1]' from 'arr[0][1]' I know I can access elements by arr.1 but can this be used for a 2d list? -
i am getting error while importing _frozen_importlib
I have created a django app and in init.py while importing _frozen_importlib i got this error i have tried changing version of python but not worked currently my python version is 3.9 -
Auto resend Activation email in Djoser
I'm using djoser with unique email addresses and I want to be able to resend activation email if user try to login with correct user and pass and account is not already active or not receive activation email class CustomTokenObtainPairView(TokenViewBase): """ Takes a set of user credentials and returns an access and refresh JSON web token pair to prove the authentication of those credentials. """ serializer_class = CustomTokenCreateSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.get_user(is_active=False) if user and not user.is_active: signals.user_activated.send( sender=self.__class__, user=self.user, request=self.request ) return Response(serializer.validated_data, status=status.HTTP_200_OK) Any advice would be welcome. -
Django DRF image field does not accept null values
Django DRF image field does not accept null values. My model consists of image = models.ImageField(upload_to='uploads/', blank=True, null=True) If I upload a file there's no problem. But, if I leave it blank it gives the following error: The submitted data was not a file. Check the encoding type on the form. I want to make the image field optional So I set null=True and blank=True. But this does not seem to work. -
How to use Django custom user tables are not extended user model?
custom use model class CustomUser(models.Model): account = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255) password = models.CharField(max_length=255) mobile = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) settings.py AUTH_USER_MODEL = 'user.CustomUser' How can I use the custom model to complete the functions of registration and login, can you give me some advice or references? Thanks -
TypeError: Field 'amount' expected a number but got datetime.datetime(2022, 3, 27, 10, 46, 51, 801087, tzinfo=datetime.timezone.utc)
I think I did something wrong and I need to delete it. but i can't fix it. How can I do it? I migrate and I get this error File "C:\Users\HP\Desktop\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value raise e.__class__( TypeError: Field 'amount' expected a number but got datetime.datetime(2022, 3, 27, 10, 46, 51, 801087, tzinfo=datetime.timezone.utc). (venv) C:\Users\HP\Desktop\markon> models.py class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) images = models.ImageField(upload_to='product/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=100) price = models.FloatField() sale = models.FloatField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Django Add Model Field Dynamically
I saw one application is using the same technique like user can add new field to a existing model. Suppose I have order form like the picture I Have attached below. It has some field for order creating. Now if user want then he can create another field for the order form and can set the fieldtype like email or datatime or text and then make it required or not to submit the form. How they do this using django? Which procedure to follow If I am able to pass the data dynamically how can sync the db without migrate command?? I don't know any good way help me if you can kindly. check the pictures -
How to get value in Django without POST or GET SIMILAR to FLASK request.args.get
how to get request.args.get in Django without changing url.py and no passing an argument/variable through def index(request, NO__EXTRA_VARIABLE_HERE) it is possible to get value without POST or GET form? What I can use to get this value in Django? I tried: request.GET but then I get WSGI Error or Exception Value: Reverse for 'index' with keyword arguments '{'currency_type': 'usa'}' not found. 1 pattern(s) tried: ['\\Z'] <a href="{% url 'index' currency_type=item.currency_type %}" class="btn btn-outline-primary {{item.active}}" role="button">{{item.display_text}}</a> FLASK CODE index.html in flask app <div class="card-footer text-center"> <a class="btn btn-primary" href="{{ url_for('movie_details', movie_id=movie.id) }}">Show more</a> </div> @app.route('/') def homepage(): selected_list = request.args.get('list_type', "popular") buttons = [ {"list_type": "now_playing", "active": "", "display_text": "now playing"}, {"list_type": "popular", "active": "", "display_text": "popular"}, {"list_type": "upcoming", "active": "", "display_text": "upcoming"}, {"list_type": "top_rated", "active": "", "display_text": "top rated"}, {"list_type": "favorites", "active": "", "display_text": "favorites"}, ] if selected_list not in ["now_playing", "upcoming", "top_rated","favorites"]: selected_list = "popular""" for button in buttons: if button['list_type'] == selected_list: button['active'] = 'active' if selected_list =="favorites": favorite_list = show_favorite() list_of_favorites = [get_single_movie(i) for i in favorite_list] if not favorite_list: flash("You dont have favorites movies", "alert-danger") return redirect(url_for("homepage")) return render_template("homepage.html",current_list=selected_list,buttons=buttons, list_of_favorites=list_of_favorites) else: movies = tmdb_client.get_movies(how_many=8, list_type=selected_list) return render_template("homepage.html",current_list=selected_list,buttons=buttons, movies=movies) What I tried to do in Django: def … -
Django 4.x Djongo MongoDb Support
i installed djongo requirements and django 4.x. Upgraded pip before install packeges in settings.py i used this connection string. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '<DB>', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': '<Host>', }, } } When i try to runserver having an issue. django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Packeges installed but why dont work? -
Key (email)=(macmusonda@gmail.com) already exists error in django
I am trying to register new users in my django ecommerce webapplication. I am using custombased model. But whenever i submit the form, my database shows that the user has been saved but then this error "duplicate key value violates unique constraint "account_account_email_key" DETAIL: Key (email)=(macmusonda@gmail.com) already exists." still comes up.The user can even login..How do i get rid of this error?? My views.py import email from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from account.forms import RegistrationForm from django.contrib import messages from .models import Account def registration(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): form.save() first_name = request.POST['first_name'] other_names = request.POST['other_names'] email = request.POST['email'] username = request.POST['username'] raw_password = request.POST['password1'] phonenumber = request.POST.get('phonenumber') Address_1 = request.POST['Address_1'] Address_2 = request.POST['Address_2'] user = Account.objects.create_user(first_name=first_name, other_names=other_names, email=email, username=username, password=raw_password, phonenumber=phonenumber, Address_1=Address_1, Address_2=Address_2) user.save() messages.success(request, ('Your account was successfully created!')) login(request, user) return redirect('home') else: messages.error(request, ('Invalid input.')) else: form = RegistrationForm() return render(request, 'account/register.html', {'form': form}) def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) try: user = Account.objects.get(username=username) except: messages.error(request, 'username does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: …