Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install virtualenvwrapper-win not working
pip install virtualenvwrapper-win after this above command these errors are shown ERROR: Could not find a version that satisfies the requirement virtualenvwrpper-win (from versions: none) ERROR: No matching distribution found for virtualenvwrpper-win I cann't solve this problem. i tried to create a virtual environment wrapper. -
product.reviews undefined in react ProductScreen
In my Django + react + redux ecommerce project reviews are not visible on product screen. models.py: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) everything is migrated, I checked it. product_views.py: @api_view(['POST']) @permission_classes([IsAuthenticated]) def createProductReview(request, pk): user = request.user product = Product.objects.get(_id=pk) data = request.data # review already exists alreadyExists = product.review_set.filter(user=user).exists() if alreadyExists: content = {'details':'Product already reviewed'} return Response(content, status=status.HTTP_400_BAD_REQUEST) # no rating or 0 stars elif data['rating'] == 0: content = {'details': 'Please select a rating'} return Response(content, status=status.HTTP_400_BAD_REQUEST) #create review else: review = Review.objects.create( user=user, product=product, name=user.first_name, rating=data['rating'], comment=data['comment'], ) reviews = product.review_set.all() product.numReviews = len(reviews) # calulate rating: total … -
ImportError: cannot import name 'name' from partially initialized module 'app.models' [closed]
У меня два приложения Users и Main для работы с пользователями и с основным ядром соответственно, в main реализованы модели в которых храниться пользователь. из-за чего я не могу импортировать основные сущности которые относятся к приложению main в users и наоборот, суть ошибки я понимаю но, что делать? Единственное её решение это идти наперерез логике и реализовывать функции там, где им не место, например, я хочу показать сколько пользователь получил лайков на свои посты, и этот метод я реализую в модели Card(мое название для модели постов) хотя по логике должен был в моделе User все это просто по тому что я не могу импортировать нужные мне модели в приложение Users. Пока что все функции я реализовал где это максимально приближенно к логике (не считая модель User) подскажите можно ли как то обойти это ошибку и может это не ошибка вовсе -
Can't use django Form.clean() method
I'm trying to add some extra validation to a form overriding it's clean method but the error doesn't raises, a ValueError exception saying "The view apps.orders.views.view didn't return an HttpResponse object. It returned None instead." raises instead, but if I make an else clause in the if condition to check if the form is valid or not and print form.errors it prints the error created in the clean method. For the record, I'm usin the form along with a formset. Thanks beforehand. Here the form: class OrderForm(forms.ModelForm): """ModelForm Class for Orders objects.""" class Meta: model = Order fields = '__all__' widgets = { 'executor_signature_date': forms.DateInput( format=('%Y-%m-%d'), ), 'customer_signature_date': forms.DateInput( format=('%Y-%m-%d'), ), } def clean(self): cleaned_data = super().clean() check_diagnosis = cleaned_data.get("check_diagnosis") repair = cleaned_data.get("repair") install = cleaned_data.get("install") maintenance = cleaned_data.get("maintenance") if (not check_diagnosis) and (not repair) and (not install) and (not maintenance): self.add_error(None, "At least one modality option must be checked.") else: return cleaned_data The check_diagnosis, repair, install and maintenance fields are BooleanField. Here the view: def post(self, request, **kwargs): order = Order.objects.get(pk=kwargs['pk']) form = self.form_class(request.POST, instance=order) ItemTimesFormSet = modelformset_factory(ItemTimes, exclude=['order']) formset = ItemTimesFormSet(request.POST) if form.is_valid() and formset.is_valid(): order.items.clear() form.save() for form in formset: if form.cleaned_data.get('item'): item = form.cleaned_data.get('item') times = … -
Best way to process images
I have a project that I am using django for backend and flutter for the frontend.The project involves uploading many images to the the backend through the mobile app which is the flutter.I want to know what is the best way to process the images like compression,resize e.t.c.Should I do it in the backend after they are uploaded or in the frontend during the time they are uploaded Also as a follow up question,if I decide to do it in the backend how do I go about it.I'm thinking about using signals to process and save the images after the model is created or celery to do same.Also which is best in this case signals or celery? -
How do I order a many to many relationship based on a field in the intermediary table?
I am writing a django application that tracks ranked statistics for a player in a video game. When I define the "through" field of a many to many relationship, I expect the resulting query to be ordered using the "ordering" meta field of the intermediary object. I cannot get the test below to pass. My db is fully migrated. Where am I misunderstanding things? Model Code from django.db import models class Player(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) name = models.CharField(max_length=255) class GameMode(models.Model): name = models.CharField(max_length=30) leaderboard = models.ManyToManyField(Player, through="ELO", related_name="game_modes") class ELO(models.Model): player = models.ForeignKey(Player, related_name="elos", on_delete=models.PROTECT) game_mode = models.ForeignKey(GameMode, related_name="elos", on_delete=models.PROTECT) current = models.PositiveIntegerField(default=0) peak = models.PositiveIntegerField(default=0) class Meta: unique_together = ["player", "game_mode"] ordering = ("-current",) Test Code def test_leaderboard_works_okay_with_different_game_modes(db): # checks that creating player elos will have them sorted on the game_mode leaderboard game_mode1 = GameMode.objects.create() game_mode2 = GameMode.objects.create() player1 = Player.objects.create() player2 = Player.objects.create() ELO.objects.create(game_mode=game_mode1, player=player1, current=1500) ELO.objects.create(game_mode=game_mode2, player=player1, current=1000) ELO.objects.create(game_mode=game_mode1, player=player2, current=1000) ELO.objects.create(game_mode=game_mode2, player=player2, current=1500) assert game_mode1.leaderboard.first() == player1 assert game_mode2.leaderboard.first() == player2 Error Log The leaderboard has the list of players, but they aren't correctly ordered and the assertion fails. > assert game_mode2.leaderboard.first() == player2 assert <Player: Player object (30a9670a-28de-4027-b7c0-70cec65ec08e)> == <Player: Player object … -
Carousel Navigation icon in Django
{% extends 'shop/basic.html' %} {% block css %} .col-md-3 { display: inline-block; margin-left:-4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 170px; height: 200px; } body .carousel-indicator li{ background-color: blue; } body .carousel-indicators{ bottom: 0; } body .carousel-control-prev-icon, body .carousel-control-next-icon{ background-color: blue; } .carousel-control-prev, .carousel-control-next{ top: auto; bottom: auto; padding-top: 222px; } body .no-padding{ padding-left: 0, padding-right: 0; } {% endblock %} {% block body %} {% load static %} <div class="container"> <!--Slideshow starts here --> {% for product, range, nSlides in allProds %} <h5 class="my-4">Flash Sale On {{product.0.category}} - Recommended Items</h5> <div class="row"> <div id="demo{{forloop.counter}}" class="col carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo{{forloop.counter}}" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#demo{{forloop.parentloop.counter}}" data-slide-to="{{i}}"></li> {% endfor %} </ul> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title" id="namepr{{i.id}}">{{i.product_name}}</h5> <p class="card-text">{{i.desc|slice:"0:53"}}...</p> <span id="divpr{{i.id}}" class="divpr"> <button id="pr{{i.id}}" class="btn btn-primary cart">Add To Cart</button> </span> <a href="/shop/products/{{i.id}}"><button id="qv{{i.id}}" class="btn btn-primary cart">QuickView</button></a> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- left … -
Object has no attribute issue
I've followed a tutorial on how to create a CRM via Python, Django and came across an issue in the end result. When I attempt to convert a lead into a client, I am faced with 'Lead' object has no attribute 'comment'. This is present if the lead has comments under it and if it does not. But once I get back to the lead list, I notice that the lead has been converted and duplicate 4 times. Has anyone else come across this issue? And how would I go about fixing it? Below is the models.py file class Lead(models.Model): LOW = "low" MEDIUM = "medium" HIGH = "high" CHOICES_PRIORITY = ((LOW, "Low"), (MEDIUM, "Medium"), (HIGH, "High")) team = models.ForeignKey(Team, related_name="leads", on_delete=models.CASCADE) name = models.CharField(max_length=255) email = models.EmailField() number = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) priority = models.CharField(max_length=10, choices=CHOICES_PRIORITY, default=MEDIUM) converted_to_client = models.BooleanField(default=False) created_by = models.ForeignKey( User, related_name="leads", on_delete=models.CASCADE, default="Admin" ) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ("name",) def __str__(self): return self.name class Comment(models.Model): team = models.ForeignKey( Team, related_name="lead_comments", on_delete=models.CASCADE ) lead = models.ForeignKey(Lead, related_name="comments", on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) created_by = models.ForeignKey( User, related_name="lead_comments", on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.created_by.username This is … -
CSS Background Image Not Being Applied To Django Project Correctly
I'm attempting to develop a rather simple playlist directory and when working on the frontend, I encountered an issue creating a blur and hover effect for the cards. I originally started with the template from App Seed: Template Code, which I attempted to add some css on. The issue is that although all the other css is being applied, the background and hover seem to be conflicted by something and are not being applied, instead its just the card with the correctly formatted texts. This is the template I'm attempting to apply the CSS to: {% extends "layouts/base.html" %} {% block title %} Basic Elements {% endblock %} <!-- Specific Plugin CSS goes HERE --> {% block plugin_stylesheets %} <!-- Plugin css for this page --> <link rel="stylesheet" href="/static/assets/vendors/select2/select2.min.css"> <link rel="stylesheet" href="/static/assets/vendors/select2-bootstrap-theme/select2-bootstrap.min.css"> <!-- End plugin css for this page --> {% endblock plugin_stylesheets %} <link rel="stylesheet" href="/static/assets/css/playlist.css"> <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} **Unrelated Code*** <div class="row"> <div class="col-md-3"> <div class="card playlist-card"> <div class="card-body bg-blur"> <!-- Content of the first playlist card --> <h5 class="card-title">Playlist Title 1</h5> <h6 class="card-subtitle">Subtitle 1</h6> <p class="card-description">Description of the first playlist.</p> </div> </div> </div> … -
How to handle a file which has been passed as a string from backend in react?
in my react app, i have a button that triggers a request to backend Django. In the response of that request, there is a excel file but it has passed as a string like the image I added in the bottom. do you have any idea how should i handle that file to be downloaded on users system? picture of the response i'm getting -
Django email sends multiple times when attachment is bigger in size
We are using Django and use EmailMultiAlternatives library of django core mail to send email. we are facing issue that we are getting multiple same email when we attach attachment with bigger size. test case: when attachment size is around 1 MB get one email 1 times when attachment size is around 5 MB get one email 4 times when attachment size is around 8 MB get one email 5 times As we are sending mail once after adding all attachments but getting same email multiple times when attachment size is bigger. -
Multi level Drop Down with a gap
I have built a nav bar which has a dropdown and inside this dropdown when each item is hovered, another drop down appears in tree view. I don't want it to be in tree view, I want to be at same starting height. What I mean is when I select the second item the second dropdown at right appears with a gap above, I don't want it. Please ignore other errors. Here is the code: * { margin: 0; padding: 0; } .header-bottom { height: 8vh; background-color: #283045; position: relative; } .navigation-menu { height: 100%; /* Set the navigation menu's height to 100% of its parent (.header-bottom) */ display: flex; align-items: center; justify-content: space-between; padding-top: auto; padding-left: 13%; padding-right: 9.5%; font-size: 15px; } .navigation-menu ul { list-style: none; height: 100%; margin: 0; /* Remove default margin */ padding: 0; /* Remove default padding */ display: flex; align-items: center; text-align: center; } .navigation-menu .nav-content { height: 100%; display: flex; align-items: center; } .navigation-menu .nav-content .nav-link{ display: inline-block; display: flex; align-items: center; padding: 10px 30px; position: relative; height: 100%; } .navigation-menu .nav-content li a { color: aliceblue; text-decoration: none; text-transform: uppercase; } .navigation-menu .nav-content li a .arrow-down{ position: relative; left: 10px; } … -
Django allauth creating dupilcate user?
I have a customerUser inherited from AbstractUser,if the user Signup with the email aaaa@gmail.com , Then the second times, he tries to signup with Google Signin and same Email (aaa@gmail.com) Does Django-Alluth create a duplicate user, if so how I can avoid this, from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ( "username", "email", "age", ) # ne email = {"required": True} class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ( "username", "email", "age", ) # ne email = {"required": True} class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) email = models.EmailField(blank=False, null=False) -
How to resolve "django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known"
I'm trying to run a Django dockerized project on my local machine. I'm new to dockers so,I'm just trying to run this project to learn how dockers work.I'm sure the project code is absolutely fine to work with because it runs fine on my friend's local machine. I tried docker-compose -f global-compose.yml up This is my global-compose.yml version: '2' services: ### redis the-redis: image: redis:3.2.7-alpine ports: - '6379:6379' volumes: - ../data/redis:/data db: image: postgres:10.20 environment: - PGDATA=/var/lib/postgresql/data/pgdata - POSTGRES_MULTIPLE_DATABASES=postgres,payments,justlegal_attorney_scheduler - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - db_data:/var/lib/postgresql/data/pgdata - ~/backups:/backups - ./postgres:/docker-entrypoint-initdb.d ports: - '5433:5432' web: build: ./gotlaw env_file: ./env_web entrypoint: ./django_instances.sh volumes: - ./gotlaw:/code - /static:/static environment: REDIS_HOST: the-redis REDIS_PORT: 6379 REDIS_URL: the-redis:6379 expose: - '8000' depends_on: - db - the-redis restart: always nginx: hostname: local.got.law image: nginx:1.16.0 volumes: - ./deploy/nginx/conf.d:/etc/nginx/conf.d:ro - ./deploy/nginx/pages/errors:/var/www/errors - ./deploy/nginx/conf.d/stunnel:/etc/nginx/conf.d/stunnel:ro - /static:/static ports: - '80:80' - '443:443' depends_on: - web # - payments-client # - attorney-scheduler # - client-scheduler # links: # - attorney-scheduler:attorney-scheduler-server # - client-scheduler:client-scheduler-server volumes: db_data: On my friend's local and some other local machines it just start running the website but on my machine I face this error Starting gotlaw-main_the-redis_1 ... done Starting gotlaw-main_db_1 ... done Starting gotlaw-main_web_1 ... done Starting gotlaw-main_nginx_1 … -
Django's connection with Firestore
I am about to create a project in django. I have to use firestore as nosql database. Is there a way to save django features like authorization without having sql database? Need every advice, article and library on django + firestore, i have no idea where to start. Thanks! I found only one article on how to connect firestore with django, but still i have to create authorization, endpoints etc. -
Best practice for marking CharFields for translation in django models?
I have a few models for which a specific CharField has to be systematically translated. It appears that those are never picked-up by compilemessages, but are translated ok when the translation is manually introduced into the .po file. Of course it creates an issue each time I update the .po files... which led me several time to loose those specific translation without realizing I therefore wanted to mark those specific CharField for translation once and for all. I was first expecting a declaration in the CharField definition such as: label = models.CharField(max_length=20, default='empty', unique=True, mark_for_translation=True) but looking for it on the documentation, then directly in the Django code ... such a functionality is not currently implemented Then I tried within my code to mark it with gettext_noop, but apparently, in the following code, the corresponding messages are not picked-up during the compilemessages instruction. def difficulty_label_from_index(): difficulties = Difficulty.objects.all().values("label", "index") # Translators: PuzzleDifficulty label return {diff['index']: gettext_noop(diff['label']) for diff in difficulties} Does anyone has a clue why it is not working? or what could be best practices when we need to mark content of a CharField for translation? -
Why is my django /login url shows noting on website
urls.py from django.urls import path from . views import * urlpatterns=[ path('',home,name='home'), path('<str:year>/',companies,name='company'), path('<str:year>/<str:company>',experience,name='experience'), path('login',loginUser,name='login'), path('logout',logoutUser,name='logout') ] views.py def loginUser(request): return render(request,'App/login.html',context={}) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Placemet Freak - SFIT</title> </head> <body> <h1>Login</h1> </body> </html> Output Output It shows a blank page, all other urls are working properly File Structure File Structure It always returns a blank page, it should return Login -
Schema validation error - failed validating 'minItems'
I have a Django (& DRF) application using drf_spectacular. When running manage.py spectacular --validate I got following warning: Warning: encountered multiple names for the same choice set (ProgramTypeEnum). This may be unwanted even though the generated schema is technically correct. Add an entry to ENUM_NAME_OVERRIDES to fix the naming. In order to fix it, I added the problematic (at least that I assume) enum to ENUM_NAME_OVERRIDES: # some/module/enums.py from django.db import models class ProgramTypes(models.TextChoices): A = 'a', 'AAA' B = 'b', 'BBB' # settings.py (...) SPECTACULAR_SETTINGS = { # ... "ENUM_NAME_OVERRIDES": { "ProgramTypes": "some.module.enums.ProgramTypes", }, } Which now results in a schema validation error: E drf_spectacular.management.commands.spectacular.SchemaValidationError: [] is too short E E Failed validating 'minItems' in schema[0]['properties']['enum']: E {'items': {}, 'minItems': 1, 'type': 'array', 'uniqueItems': False} E E On instance['enum']: E [] I'm out of ideas on where to go next. This is problematic as I want to keep a test ensuring there are no schema validation warnings (or errors). -
Storing a Generic Table (with rows, columns) fields are not explicit as objects in Database Django
In my Django Project im trying to map out generic tables the number and column definitions would be different for each table Table 1 | Col1 | Col2 | | ----- | -----| Table 2 | Col A | Col B | Col C | | ----- | ----- | ------| These are the proposed models that I thought, not sure if this is the best way to do this or even if storing these tables in my psql database class GenericColumn(models.Model): given_name = models.CharField(max_length=128, verbose_name='Given Column Name') class GenericTable(models.Model): table_name = models.CharField(max_length=128, verbose_name='Table Name') columns = models.ManyToManyField(GenericColumn, blank=True, verbose_name='Columns') class GenericRow(models.Model): table = models.ForeignKey(GenericTable, on_delete=models.CASCADE) data = models.JSONField(null=True) # data being {colName: "Value"} as a JSON object I did initially have a model for an individual cell but I aborted that idea as there would loads of entries in the database might get too big I wanted to ask what would be the best way to go about this as its a bit of unusual use case as none of the fields are specified it depends on what the table is. But on the front end you would be able to edit these thats why i stored it as … -
Cannot authenticate a django user using his token
I am creating a django rest framework api to interact with an Android app. I have opened the following endpoints: from django.urls import path, include from .views import UserViewSet, UserProfileViewSet, CurrentUserView,LoginView urlpatterns = [ path('usuarios/', UserViewSet.as_view(), name='usuarios'), path('usuarios-perfil/', UserProfileViewSet.as_view(), name='usuarios-perfil'), path('usuario-actual/', CurrentUserView.as_view(), name='usuario-actual'), path('login/', LoginView.as_view(), name='login'), ] My views are this ones: from rest_framework import generics from django.contrib.auth.models import User from .models import UserProfile from .serializers import UserSerializer, UserProfileSerializer from rest_framework.permissions import IsAuthenticated from django.contrib.auth import get_user_model from django.contrib.auth import authenticate from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authtoken.models import Token import logging logger = logging.getLogger(__name__) class UserViewSet(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserProfileViewSet(generics.ListCreateAPIView): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer class CurrentUserView(generics.RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get_object(self): logger.info(self.request.META) logger.debug(f"CurrentUserView.get_object called for user {self.request.user}") return self.request.user def authenticate(email=None, password=None): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None if user.check_password(password): return user # En tu LoginView class LoginView(APIView): def post(self, request, format=None): user = authenticate(email=request.data.get('email'), password=request.data.get('password')) if user is not None: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) else: return Response(status=401) My models: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_premium = models.BooleanField(default=False) def __str__(self): … -
styling conflicts/incoherence between daisUI and Tailwindcss in a django project
I'm trying to apply daisyUI styling in my django web-app project, and I'm note sure to understand well what's happening with the styling : in my case, I try to add some padding and border to an input text field generated dynamically by a django form : #forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'py-4 border w-full max-w-xs', 'placeholder':'Title'}), ... in my template I added {{form.title}} inside a form. Here is what it looks like vs what I expect : what I get vs. what I want The styling seems to be overridden somewhere but I'm unable to determine where that comes from... I got the screenshot of "what I want" using my lines of code with this tailwind-play tool More informations that could be useful : Locally on my computer, I installed django-browser-reload. My tailwind.config.js file looks like this : /** @type {import('tailwindcss').Config} */ module.exports = { content: ["../**/templates/**/*.html"], theme: { extend: {}, }, daisyui: { themes: ['light', 'dark', 'bumblebee', 'black', 'luxury', 'night', 'business'], }, plugins: [require("@tailwindcss/typography"), require("daisyui")], } I did try to rerun npm run tailwind-watch, refresh the web page using cmd+shift+R and rerun 'python manage.py runserver` every time … -
how to override a class method in Django Oscar
Currently I can already overwrite the class, but I can't overwrite the method get() what am i missing? I need to do this because if there is only 1 shipping method it does not load the 'Shipping-Method' page and it redirects to the payment page, but I want the customer to see the shipping value before going to the payment page. apps.py import oscar.apps.checkout.apps as apps from oscar.core.loading import get_class from django.urls import path class CheckoutConfig(apps.CheckoutConfig): name = 'apps.checkout' def ready(self): self.shipping_method_view = get_class('checkout.views', 'ShippingMethodViewOverwritten') super().ready() def get_urls(self): urls = super(CheckoutConfig, self).get_urls() urls += [ path('shipping-method/', self.shipping_method_view.as_view(), name='shipping-method'), ] return urls views.py from oscar.apps.checkout import views from oscar.core.loading import get_class ShippingAddressForm, ShippingMethodForm, GatewayForm \ = get_classes('checkout.forms', ['ShippingAddressForm', 'ShippingMethodForm', 'GatewayForm']) from django.contrib import messages Repository = get_class('shipping.repository', 'Repository') class ShippingMethodViewOverwritten(views.ShippingMethodView): template_name = 'oscar/checkout/shipping_methods.html' form_class = ShippingMethodForm pre_conditions = ['check_basket_is_not_empty', 'check_basket_is_valid', 'check_user_email_is_captured'] success_url = reverse_lazy('checkout:payment-method') def get(self, request, *args, **kwargs): if not request.basket.is_shipping_required(): self.checkout_session.use_shipping_method( NoShippingRequired().code) return self.get_success_response() if not self.checkout_session.is_shipping_address_set(): messages.error(request, _("Please choose a shipping address")) return redirect('checkout:shipping-address') self._methods = self.get_available_shipping_methods() if len(self._methods) == 0: # No shipping methods available for given address messages.warning(request, _( "Shipping is unavailable for your chosen address - please " "choose another")) return redirect('checkout:shipping-address') elif len(self._methods) == … -
Django Get a variable from one application view to another application view
i have two different apps in django project where i have views:auths/views.py on this path i have def home(request): users = CustomUser.objects.all() events = Event.objects.all() tags = Tag.objects.all() event_categorys = EventCategory.objects.all() tickets = Ticket.objects.all() if request.user.is_authenticated: email = request.user.email else: email = 'AnonymousUser' if request.method == "GET": url = request.get_full_path() code_index = url.find('code=') if code_index != -1: code = url[code_index + 5:] print("Code is :", code) request.session['code'] = code session_code = code else: session_code = request.session.get('code') get_bearer_token(request) print("ssssssssssssssssssssssssssssssssssss: ", session_code) return render(request, 'home.html', context={'events': events, 'tags': tags, 'event_categorys': event_categorys, 'tickets': tickets, 'session_code': session_code}) and on this path BogID/views.py I have this code : def get_bearer_token(request): # Define the authentication endpoint URL auth_url = "https://account-test.bog.ge/auth/realms/bog-id/protocol/openid-connect/token" session_code = request.session.get('session_code') if session_code: print("Session Code:", session_code) else: print("Session Code not found") payload = { "grant_type": session_code, "client_id": "your_client_id", "client_secret": "your_client_secret" } response = requests.post(auth_url,data=payload) return HttpResponse("asdasd") I am getting the token from the url in the home view,and giving this code to session_code variable,and i am trying to get this variable value with the get_bearer_token view.But It cant see this code in session,Is it because of that they are not in the same app?How can I solve this problem? It is giving me "Session … -
Property Object is not callable with python 3.10 and django 4.1
I am deploying a django application on apache using mod_wsgi. However, I'm getting the following error when wsgi.py is running: File "/home/ubuntu/release/innovate-backend/src/rest_apis/rest_apis/apache/wsgi.py", line 7, in <module> from django.core.wsgi import get_wsgi_application File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/utils/version.py", line 7, in <module> from django.utils.regex_helper import _lazy_re_compile File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/utils/regex_helper.py", line 10, in <module> from django.utils.functional import SimpleLazyObject File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/utils/functional.py", line 399, in <module> class SimpleLazyObject(LazyObject): TypeError: Error when calling the metaclass bases 'property' object is not callable Following is my wsgi.py file: import os, sys import time import traceback import signal from django.core.wsgi import get_wsgi_application # Calculate the path based on the location of the WSGI script. apache_configuration= os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.dirname(project) parent = os.path.dirname(workspace) sys.path.append(workspace) sys.path.append(project) sys.path.append(parent) os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_apis.apache.override' application = get_wsgi_application() Any idea what I might be doing wrong ? -
Django Project Questions
I have mac with frontend (react JS based) and backend (Django based). I am seeing error saying, null value in column "customer_id" of relation "main_order" violates not-null constraint DETAIL: Failing row contains (58, 2023-07-20 09:32:15.565247+00, null). Following are the code details: views.py class OrdersList(generics.ListCreateAPIView): queryset = models.Order.objects.all() serializer_class = serializers.OrderSerializer **def post(self, request, *args, **kwargs): print(request.POST) return super().post(request, *args, **kwargs)** class OrderDetails(generics.ListAPIView): queryset = models.OrderItems.objects.all() serializer_class = serializers.OrderDetailsSerializer def get_queryset(self): order_id = self.kwargs['pk'] order = models.Order.objects.get(id=order_id) order_items=models.OrderItems.objects.filter(order=order) return order_items models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_orders') order_time = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.order_time) class OrderItems(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.product.title serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = models.Order fields = ['id', 'customer'] def __init__(self, *args, **kwargs): super(OrderSerializer, self).__init__(*args, **kwargs) self.Meta.depth = 1 I am printing the request in post function of OrderList view class and I see <QueryDict: {'customer': ['7']}> <QueryDict: {'customer': ['7']}> I am seeing following error: Internal Server Error: /api/orders/ Traceback (most recent call last): File "/opt/homebrew/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/opt/homebrew/lib/python3.10/site-packages/psycopg/cursor.py", line 723, in execute raise ex.with_traceback(None) psycopg.errors.NotNullViolation: null value in column "customer_id" of relation "main_order" violates not-null constraint DETAIL: Failing row …