Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error: value must be either True or False
I'm currently having this error message on django: ["*** value must be either True or False."] It's really strange that I could not found where's the bug manager.py models.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, password, email, **extra_fields): if not username or not password or not email: raise ValueError("All values must be filled!") if not password: raise ValueError("Password could not be empty!") user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, password, **extra_fields) def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, password, **extra_fields) models.py import hashlib import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token import server.settings as settings from user.manager import UserManager STATUS_CHOICES = ( (0, "禁用"), (1, "启用"), ) class Users(AbstractUser): userid = models.AutoField(primary_key=True, verbose_name="用户ID", help_text="用户ID") username = models.CharField(max_length=150, unique=True, db_index=True, verbose_name="用户账号", help_text="用户名") email = models.EmailField(max_length=255, verbose_name="邮箱", null=True, blank=True, help_text="邮箱") avatar = models.CharField(max_length=255, verbose_name="头像", null=True, blank=True, help_text="头像", default="https://api.vvhan.com/api/qt?qq=771151240") VIP_CHOICES = ( (0, "普通用户"), (1, "VIP用户"), … -
Refactor or Relocation of data range validation in Views
im new to stack and dont know if its the best way to post, but im learning. I have a view in Django to validate dome data range fields that i have built with bootstrap, But im learning about managers, querysets and im trying to follow best practices. I feel that i can refactor this view, or shrink in size using forms and etc. Could you give me some tips? this views is large? can be refactored or relocated to other files, like forms? thanks in advance. https://github.com/paasxx/crypto-site/tree/sqlite_to_postgre/app_crypto def market(request, crypto): crypto_name = crypto crypto_model = getModelByName(crypto) sd = request.GET.get("startDate") ed = request.GET.get("endDate") min_date_table = crypto_model.crypto_objects.first_date().date max_date_table = crypto_model.crypto_objects.last_date().date crypto_data_all = crypto_model.crypto_objects.all_data() if sd == None and ed == None or sd == "" and ed == "": crypto_data = crypto_data_all context = { "currencies": currencies, "crypto": crypto_name, "crypto_data": crypto_data, "min_date_table": min_date_table, "max_date_table": max_date_table, } return render(request, "app_crypto/crypto_list.html", context) else: if datetime.strptime(ed, "%Y-%m-%d") < datetime.strptime(sd, "%Y-%m-%d"): messages.warning( request, "End Date must be greater than Start Date, Please try again." ) crypto_data = crypto_data_all context = { "currencies": currencies, "crypto": crypto_name, "crypto_data": crypto_data, "min_date_table": min_date_table, "max_date_table": max_date_table, } return render(request, "app_crypto/crypto_list.html", context) else: if sd == None or sd == "": … -
django Strings must be encoded before chechking?
i have a register form it work well and when i login the user it says that 'strings must be encoded before chechking ; and the error always show in login bcrypt.chekwp def getregisterpage(request): if request.method == "POST": firstname=request.POST.get('firstname') lastname=request.POST.get('lastname') email = request.POST.get("email") password = request.POST.get("password") hashed_password = bcrypt.hashpw(password.encode('utf-8'),bcrypt.gensalt()) if firstname and lastname and email and password : data=User(firstname=firstname,lastname=lastname,email=email,password=hashed_password) data.save() return redirect('login') else: return render (request,'register.html') ef getloginpage(request): if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.objects.get(email=email) except User.DoesNotExist: return redirect('register') if bcrypt.checkpw(password.encode('utf-8'),user.password): authenticated_user = authenticate(request,email=email,password=password) if authenticated_user: login(request, authenticated_user) messages.success(request, 'Logged in Successfully.') return redirect("home") else: messages.error(request, 'Authentication failed') else: messages.error(request, 'Invalid email or password.') return render(request, "login.html") -
When i try to login through new user and try to update its balance it is giving me {"detail": "User not found", "code": "user_not_found"} this error
My transaction API that i created where is this error occuring My serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'password', 'gender', 'age'] class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) class Meta: model = User fields = ['username', 'password'] class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['account_id', 'account_no', 'balance'] class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ['account_id', 'transaction_type', 'transaction_balance'] My Views in Apps # only use serializer here in request body and response @swagger_auto_schema(method="post", request_body=LoginSerializer, responses={"200": 'LoginSerializer'}, operation_id="user Login", ) @api_view(['POST']) @permission_classes([AllowAny]) def login(request): # user can sign_in through this API serializer = LoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] user_obj = User.objects.get(username=username, password=password) refresh = RefreshToken.for_user(user_obj) return Response({'msg': 'Logged In', 'refresh': str(refresh), 'access': str(refresh.access_token)}) return Response(serializer.errors) @swagger_auto_schema(method="post", request_body=TransactionSerializer, responses={"200": 'TransactionSerializer'}, operation_id="user signup transaction", ) @api_view(['POST']) # @authentication_classes(JWTAuthentication) # @permission_classes(IsAuthenticated) def transaction(request): # all read and update of balance logic here from this API serializer = TransactionSerializer(data=request.data) token = request.headers.get('Authorization') new_token = token.split(" ") decode_payload = jwt.decode(jwt=new_token[1], key=SECRET_KEY, algorithms=['HS256']) user = decode_payload['user_id'] if serializer.is_valid(): user_id = user transaction_type = serializer.validated_data['transaction_type'] acc_id = serializer.validated_data['account_id'] tran_bal = serializer.validated_data['transaction_balance'] if transaction_type == Transaction.TransactionType.DEPOSIT: acc_balance = Account.objects.get(id=acc_id.id, user_id=user_id) acc_balance.balance = acc_balance.balance … -
DJANGO: Query for select_related in view shows error
In my project with this ERM: I need to add equipment to an institute. Tried this: class EquipmentinLocationAdd(CreateView): model = EquipmentInstitute, Lot form_class = EquipmentInstituteForm template_name = 'Procure/equipmentininstitute_add.html' def get_success_url(self): return reverse('equipmentinstitute_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get( id = self.kwargs['pk'] ) initial = {'Institute': qs} return initial def get_context_data(self, **kwargs): # query for Institute Var1 = Institute.objects.all().get( id = self.kwargs['pk'] ) # query for Project Var4 = Project.objects.get(id = 5) # Here is my problem context = super().get_context_data(**kwargs) context ['queryset2'] = Lot.objects.all().values_list("LotTitle","Project") context.update({'LOK': Var1, 'LOKID': Var1.id, 'PR_id':Var4.id, 'PR':Var4}) return context Var1 is delivering data of the related institute. Var4 is supposed to get the related project. For testing purposes I worked with an fix 'id' of 5 However I need the related project of the selected institute but all my query efforts failed to retrieve the related project_id. (See Var4 in code) Need help! Thanks in advance Ben -
ImpropertyConfigured issues with customized password valiators in django
I´m writing customised password validators for django. But I get ImproperlyConfigured error -> ImproperlyConfigured django.core.exceptions.ImproperlyConfigured: The module in NAME could not be imported: auth.validators.UppercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting. settings.py (path : app/conf/settings/settings.py). -> AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 12}}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, {'NAME': 'auth.validators.UppercaseValidator'}, ] validators.py (path: app/auth/validators.py). -> import re from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class UppercaseValidator(object): def validate(self, password, user=None): if not re.findall('[A-Z]', password): raise ValidationError( _("The password must contain at least 1 uppercase letter, A-Z."), code='password_no_upper', ) def get_help_text(self): return _("Your password must contain at least 1 uppercase letter, A-Z.") I'm started to get a bit crazy because I cant see what the problem is pliz help me -
How to filter a Django model by properties of a reverse foreign key
I need to filter a Django model based on properties of a reverse foreign key and I'm not sure of the best way to do this. I have two models in which Products belong to a ProductRange class ProductRange(models.Model): pass class Product(models.Model): product_range = models.ForeignKey(ProductRange, related_name="products") is_archived = models.BooleanField() Product Ranges in which all products are set is_archived=True are to be considered archived, if any products are not marked as archived they are not considered archived. I need a way to filter Product Ranges based on this, i.e a filter that returns product ranges for which all products are archived. I'm aware I can filter by the related name: ProductRange.objects.filter(products__is_archived=False) However this returns product ranges where Any product is archived no all products. I'm also aware I can do the filtering in Python but I need this filter work on a large dataset and I'm sure there is a more efficient way to do this in the database. I've also considered using models.Subquery or models.Exists, however I feel like there is probably a simpler and more performant way of doing this that I am missing, also this would require a lot of refactoring to avoid a circular import. I feel … -
How to customize UI of Swagger (drf-yasg) to use dark mode?
So we have done our Django API documentation setup using drf-yasg, and I was wondering if it's possible to use dark mode in the documentation screen. For reference, the screen looks something like this: -
AttributeError: 'WSGIRequest' object has no attribute 'tenant'
I'm using django-tenants, following the Installation Guide, and I've created a simple project. Here's the scenario: I have a model named UnVerifiedTenants that stores company data, including their email and tenant ID. class UnVerifiedTenants(models.Model): """ model that Saves user email, depending upon below points 1. all emails from tenants for proper tenant utilization 2. all emails who just enquired and did not proceed further """ tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(verbose_name="Email Address", unique=True) admin = models.BooleanField("Is user admin", default=False) created_on = models.DateField(auto_now_add=True) updated_on = models.DateField(auto_now=True) When users create their accounts on the registration page, the data is stored in this model. After users verify their phone number (which is stored in a different table), I migrate their schema. After completing the migration, they enter their email on the login page. I check their email, retrieve their schema, and create a URL to redirect them to their tenant domain for further authentication: class Login(generic.TemplateView): form_class = InitialAuthenticationForm template_name = "login.html" def post(self, request, **kwargs): email = request.POST["email"] scheme = "https" if self.request.is_secure() else "http" domain = settings.DOMAIN shared_user = AllUsersEmails.objects.filter(email=email).first() if shared_user: tenant_obj = shared_user.tenant try: tenant = tenant_obj.schema_name sub_url = f"accounts/enter-password/{encrypt(email.encode()).decode()}" url = f"{scheme}://{tenant}.{domain}/{sub_url}" shared_user.update_last_login() return redirect(url) … -
Django - large file upload - moving file from temp folder to final destination fails
Stumbled upon this error when upgrading Python, Django and Alpine to latest versions... and it's a weird one. The error occurs when I upload a file that is larger than FILE_UPLOAD_MAX_MEMORY_SIZE (set to 5MB). I have two development environments set up. One is local dev server (just normal py manage.py runserver), the other one is running under Docker(Windows) + Alpine linux + Apache2 + mod_wsgi which is also still a 'development' environment. This error occurs only under Docker environment and only when file exceeds max memory size. Under all other circumstances the upload works - even when file exceeds memory limit on local dev server. The error: Saving new order file to: customer_name/_web_portal/PendingOrders/7935/zip_03.zip Internal Server Error: /b2b_api/orders/ Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/code/api/views.py", line 352, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise … -
DRF APITestCase but HttpResponseNotFound status_code=404
Hi I'm trying to make unittest by django and DRF but I have a problem when running test the below code is my tests, views, models code I check urls and runserver too and they work well. I need your help. tests.py class TestCohorts(APITestCase): def setUp(self): models.Cohort.objects.create(code=COHORT_CODE) def test_cohort(self): response = self.client.get("api/v1/cohort") print(response) data = response.json() self.assertEqual(response.status_code, 200, "status code is not 200.") views.py class CohortList(ListAPIView): queryset = models.Cohort.objects.all() serializer_class = serializers.CohortSerializer models.py class Cohort(models.Model): code = models.CharField(max_length=30) def __str__(self) -> str: return f"{self.code}" class Meta: db_table = "cohort" -
Should I render dynamic charts in Django or serve them from another webapp?
Here is this Django webapp hosted in a Apache2 server with mod_wsgi My question is: How do I add dynamic graphs to my webapp? In producion, in order to serve files, Nginx reverse proxy server catches the urls with the /static/ subdomain and serves the content (otherwise the request is redirected to apache) Google returns planty of ways to address the matter. Do you have any recomandation or relatable experience that I should know before choosing any? My concerns are: How clients update graph data without refreshing the whole page ? (I currentlly use htmx for rendering html) Should I use a second webapp to serve the content to nginx redirect? Is django-plotly-dash the most straight way? Will it work with htmx or else? I tried to periodically render an html with a plotly graph using htmx; resulted awful -
Django viewset: using get for list() only
I have this viewset where i wnat to use get method for list() only. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() def get_serializer(self, instance=None, *args, **kwargs): serializer = UserSerializer(method=self.action, instance=instance, *args, **kwargs) return serializer def get_permissions(self): if self.action == 'list': permission_classes = [IsAdminUser] elif self.action == 'update': permission_classes = [IsAuthenticated, IsOwner] elif self.action == 'create': permission_classes = [] else: raise ValueError(f"Invalid action: {self.action}") return [permission() for permission in permission_classes] I tried ti define http method names first, but list and retrieve both run for get method. Is there any other solution to this? -
User inbox feature in django project
Inbox feature in django project. I am working on this django project, and I want to implement an inbox feature in the project. The inbox will enable the admin if the website send messages to the users. Can someone help me out or point me in the right direction, I'll be so grateful. I am expecting the the users will be able to only read the admin message. -
Django: prevent Form to crash when akward date format is used
I have a form: class EditProfileForm(forms.ModelForm): template_name = 'users/edit_profile.html' def __init__(self, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.fields['email'].help_text = _( 'Providing your email would enable you to recover your lost password') class Meta: model = get_user_model() fields = ( 'first_name', 'last_name', 'email', 'birthday', 'language', 'headshot', ) with user model: class CustomUser(AbstractUser): birth_year = models.PositiveIntegerField( verbose_name=_('Birth year'), default=0) birthday = models.DateField(verbose_name=_( "birthday"), null=True, blank=True) headshot = models.ImageField(verbose_name=_('Avatar'), null=True, blank=True, default='user_headshots/user.png', upload_to="user_headshots/") language = models.CharField(verbose_name=_('Language'), max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE) I had a user use a strange format for birthday "25,2,96", which led the django application to crash: The view users.views.edit_user_profile didn't return an HttpResponse object. It returned None instead. not much more information in the Traceback !?! Looking into the django code and internet, I was amazed that the DateField formfields did not come with embedded validators There are plenty of information on internet about setting specific dateformats for a specific DateField, but I wasn't able to find one kind of best practice that would work with all sort of localized date formats. Everything I found is very complicated for such a trivial issue, and I'm pretty sure there is a neat and easy to implement solution. Any suggestion? -
My python3 manage.py makemigrations or python manage.py makemigrations is erroring
I am trying to run th migration prompt in django and it isnt working. This is the error: @user: django_angular_auth_api % python3 manage.py makemigrations Traceback (most recent call last): File "/Users/user/django-angular-auth/django_angular_auth_api/manage.py", line 22, in main() File "/Users/user/django-angular-auth/django_angular_auth_api/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 442, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py", line 137, in handle loader = MigrationLoader(None, ignore_no_migrations=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in init self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 305, in build_graph self.graph.ensure_not_cyclic() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/graph.py", line 284, in ensure_not_cyclic raise CircularDependencyError( django.db.migrations.exceptions.CircularDependencyError: users.0001_initial I added in a dependancy and did everything possible to try and fix it. wiped and redid db, and most other things i found online. -
ecommerce website with django adding many item to cart
` hello developers. Im using django for ecommerce website and I cant add item cart with number. For ex: I want to add 100 pieces of the same product with typing not increasing. Waiting your helps ` index.html <div class="card-footer p-0 no-gutters"> {% if product|is_in_cart:request.session.cart %} <div class="row no-gutters"> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="text" name='product' value='{{product.id}}'> <input hidden type="text" name='remove' value='True'> <input type="submit" value=" - " class="btn btn-block btn-light border-right"> </form> <div class="number-center col">{{product|cart_quantity:request.session.cart}} in Cart</div> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="number" name='product' value='{{product.id}}'> <input type="submit" value=" + " class="btn btn-block btn-light border-left"> </form> </div> {% else %} <form action="/#{{product.id}}" method="POST" class="btn-block"> {% csrf_token %} <input hidden type="number" name='product' value='{{product.id}}'> <input type="submit" class="float-right btn btn-light form-control" value="SEPETE EKLE"> </form> </div Thanks -
Best Explanation on the implementation of Dependency Injection in Python.?
I am a Software Engineer with significant amount of years of experience. I always desire using core development principles in my projects and these include using DI. which I have used alot in .NET projects and in Nodejs Projects. however I can't wrap my head around how DI actully works in python projects especially using FLask or Django. The examples I have seen are not really conidered DI to me. Would appreciate a good explanation. Thanks. I simply want to apply DI in future Django and Flask Projects. -
Django: no such table: auctions_user_user_permissions
I wrote the Django program and registered some products with the admin panel. After making some changes in the codes, I encountered some problems: 1- It is no longer possible to enter the admin panel and it gives this error. 2- None of the product information is displayed and it seems as if there is no data on the site. what is the problem? # item detail page in views.py def item_detail(request, bidid): bid_desc = List.objects.get(pk = bidid, active_bool=True) nowbids = Bidmodel.objects.filter(listb_id = bidid) return render(request, "auctions/item_detail.html",{ "list": bid_desc, "comments" : Comments.objects.filter(listc_id = bidid), "now_bid": minbid(bid_desc.first_bid, nowbids), }) index.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} <div> {% for item in items %} <div> <img src= {{ item.image.url }} alt = "{{item.title}}"><br> <a>{{ item.title }}</a><br> <a>{{ item.category }}</a><br> <a><a>Frist Bid: </a> {{ item.first_bid }} $ </a><br> <a href="{% url 'item_detail' item.id %}">View Product</a> </div> {% endfor %} </div> {% endblock %} item_detail.html: {% extends "auctions/layout.html" %} {% block body %} {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif … -
WeasyPrint: Image not showing on linux (ubuntu)
I am using weasyprint it working on window perfectly and also it is working on linux when I used this string in html file like weasyprint my.html my.pdf It perfectly show image but when I do the below code so the image not showing I html_string = '<img src="http://domain_name/static/assets/images/logo/logo.png" alt = "Logo" /> <h1>images</h1>' # Create a PDF object from the HTML string #pdf = weasyprint.HTML(string= html_string, base_url=request.build_absolute_uri()).write_pdf(presentational_hints = True, stylesheets=[weasyprint.CSS(string='@page { size: letter; }')]) # # Create an HTTP response with the PDF content response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="marksheet.pdf"' response.write(pdf) return response I used absolute_url but not showing images nothing get any idea why it not showing image -
can i host django website on shared hosting? if, yes what are the pros and cons of it?
i am working on a project of django and make it online but the price of VPS hosting price is high. So, i am getting for a affordable option. Many people suggest me for free trail of Azure or AWS, but i am uncertain for its speed and price after the trail end. If anyone upload their django website on shared hosting please share the speed of website. I did research for and came to conclusion that when i upload django website on shared hosting i will problem while setting the wsi or while creating superuser. Also my server get crashed frequently. -
How to upgrade Django 1.3.1 to 1.3.7 on Ubuntu in Docker
I have an old django project and I built it in docker for the development environment, django 1.3.1 is installed. (Python version is 2.7 setting in docker-compose) Is there any way to upgrade to django 1.3.7? Thanks for advance. I tried followings but don't work. apt-get upgrade django apt-get install python-pip and pip install [--upgrade] django==1.3.7 Downloading/unpacking Django==1.3.7 Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement Django==1.3.7 No distributions at all found for Django==1.3.7 My dockerfile: FROM ubuntu:12.04 ... # Install dependencies RUN apt-get update \ && apt-get install -y \ apache2 \ libapache2-mod-wsgi \ mysql-server \ python-mysqldb \ python-django ... -
testing urls in django
hi I get some problems with my test in my Django project I want to write test for my URLs and one of my URLs gets an argument and I try a lot of ways and it still giving error that reverse relation doesn't match I gave the URL the id and I gave the greater and smaller sign to it but it still doesn't work -
How to filter rooms based on user's input as room_capacity , check_in_date and check_out date in Django
Here is my input form which takes user's input as room_capcity , check_in_date and check_out_date : HTML Page <!-- Filter form --> <form action="{% url 'Rooms:show_filtered_rooms' %}" method="POST" class="flex flex-row justify-center my-8 mx-10 space-x-4" > {% csrf_token %} <div class="flex flex-col"> <label for="room_capacity" class="text-xl font-semibold">Room Capacity</label> <select name="room_capacity" id="room_capacity" class="w-48 h-10 border-2 border-gray-300 rounded-md" > <option value="" hidden>Select Room Capacity</option> <option value="single">Single</option> <option value="double">Double</option> <option value="triple">Triple</option> </select> </div> <div class="flex flex-col"> <label for="check_in_date" class="text-xl font-semibold">Check In Date</label> <input type="date" name="check_in_date" id="check_in_date" class="w-48 h-10 border-2 border-gray-300 rounded-md" /> </div> <div class="flex flex-col"> <label for="check_out_date" class="text-xl font-semibold">Check Out Date</label> <input type="date" name="check_out_date" id="check_out_date" class="w-48 h-10 border-2 border-gray-300 rounded-md" /> </div> <button type="submit" class="px-1 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600" > Apply Filters </button> </form> <!-- Filter form ends --> Here is my logic in view.py file: def showFilteredRooms(request): if request.method == 'POST': room_capacity = request.POST.get('room_capacity') check_in_date = datetime.strptime(request.POST.get('check_in_date'), '%Y-%m-%d').date() check_out_date = datetime.strptime(request.POST.get('check_out_date'), '%Y-%m- %d').date() print(room_capacity) print(check_in_date) print(check_out_date) # Step 1: Get booked rooms with the specified capacity and overlapping date range booked_rooms = Booking.objects.filter( capacity=room_capacity, checkInDate__lte=check_out_date, checkOutDate__gte=check_in_date ).values_list('roomNo', flat=True) # Step 2: Get available rooms with the specified capacity available_rooms = Room.objects.filter( capacity=room_capacity ).exclude(roomNo__in=booked_rooms) print(available_rooms) context = { 'available_rooms': available_rooms, 'filter_applied': True, # … -
I am trying to implement swagger for my django drf project but it's displaying all endpoint methods I don't want post put delete methods
Actually I am trying to implement swagger for my django drf project but it's displaying all endpoint methods I don't want post put delete methods display in swagger what should I do Actually I am trying to implement swagger for my django drf project but it's displaying all endpoint methods I don't want post put delete methods display in swagger what should I do?