Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a Django detail def
well these are the codes: views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from . import models def detail(request, question_id): question = get_object_or_404(models.Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> urls.py from django.urls import path from . import views from django.urls import path, re_path path(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'), but the result is an TypeError : detail() got an unexpected keyword argument 'pk' and if you add 'pk' argument to detail() like this : def detail(request, pk, question_id): question = get_object_or_404(models.Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) the resualt is another error : detail() needs an important argument 'question_id' where is the problem from? -
How to get the data from custom serializer.CharField() after update?
I've got 2 models. CollabDocument groups CollabVersions. Together they are like a document that tracks its changes. Binary field only because the content is encrypted. class CollabDocument(models.Model): name = models.CharField(max_length=4096, null=False, blank=False) class CollabVersion(EncryptedModelMixin, models.Model): document = models.ForeignKey(CollabDocument, related_name="versions", on_delete=models.CASCADE) content = models.BinaryField(blank=True) I've got this base serializer: class CollabDocumentSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) class Meta: model = CollabDocument fields = "__all__" The content field in the following serializer ist important. I call the patch -> update method of the collab document and then a new version is created. That way there is a history of all changes made. This serializer does not update the document itself btw. class CollabDocumentUpdateSerializer(CollabDocumentSerializer): content = serializers.CharField(write_only=True) # <-- without write_only=True I get a 500 error def update(self, instance, validated_data): version = CollabVersion(content=validated_data['content'], document=instance) version.encrypt(request=self.context['request']) version.save() return instance This my problem: I can't get the content in the response, if I remove write_only=True the request fails. What I want: { id: 1, content: '<h1>awesome document</h1>', name: 'My Document' } What I get instead: { id: 1, name: 'My Document' } In my retrieve serializer I've done the following: class CollabDocumentRetrieveSerializer(CollabDocumentSerializer): content = serializers.SerializerMethodField() quill = serializers.SerializerMethodField() def get_latest_version(self, obj): if not hasattr(self, 'latest_version'): self.latest_version = … -
Requesting for POST method but only GET is working
The Form in register.html request for POST method but GET method is working. Submit is calling register method in views.py using GET method, but this shouldn't be happening. Error : Request Method: POST Request URL: http://127.0.0.1:8000/Profile/register/register/ from django.http import HttpResponse from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib import messages def register(request): if request.method == 'POST': return redirect('/') else: return render(request, 'register.html') register.html <form action="register" method="post"> {% csrf_token %} <input type="Submit"> </form> urls.py of Project from re import template from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), path('Profile/', include('Profile.urls')), path('accounts/', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(template_name="login.html"), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('reset_password/', auth_views.PasswordResetView.as_view(), name = 'reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete') ] urls.py of Profile app from django.urls import path from Profile import views urlpatterns = [ path('profile/', views.profile, name='profile'), path('register/', views.register, name='register'), ] -
How to get schema name of logged in Tenant in Django multi-tenant app?
I am using sqlalchemy to get the query result and then passing the result to pandas data frame. But it's enter image description heregenerating an error like "(psycopg2.errors.UndefinedTable) relation "identification_individual" does not exist". I figured out that schema name is required with the table to execute this statement successfully. "schemaName.identification_individual" works fine my question is how can I get the schema name of the logged-in tenant (i want this to be dynamic so that schema should be changed according to every tenant ) and how can the below query be updated. code is: engine = sqlalchemy.create_engine('postgresql://postgres:password@localhost:5432/dbname') df= pd.read_sql_query("""SELECT DISTINCT (customer_id),customer_id,customer_type,product_type,delivery_channel,diligence_type, customer_name,over_all_discount_status,risk_score,risk_category,pep_status,identification_individual.city FROM identification_individual LEFT JOIN discounting_individuldiscount ON identification_individual.customer_id = discounting_individuldiscount.individual_id WHERE over_all_discount_status='Pending' or over_all_discount_status='Rejected' or over_all_discount_status='Proceed';""",engine) -
How to merge two dependant models in django and get count of each type
I'm new to django, how to relate two model classes and extract total count of it class FoodBatch(models.Model): batch_code = models.CharField(max_length=200, blank=False, null=False) expiry = models.DateField() price = models.FloatField() class FoodItem(models.Model): seller_code = models.CharField(max_length=200, blank=False, null=False) brand = models.CharField(max_length=200, blank=False, null=False) quantity = models.IntegerField() batch = models.ManytoMany(FoodBatch) FoodBatch has to be unique for each FoodItem. FoodItem can map to multiple FoodBatch. Also, need to total count of quantity from all the FoodBatch for each FoodItem. Thanks in advance. -
Calling data from Django Admin via Frontend live search
I was hoping someone here could point me in the right direction; I don't know how best to phrase the question so I'm not even sure if this has already been asked, although a search does not reveal anything. I commissioned a new app in Django which has been registered in Admin view - what I am trying to do is add data from Django Admin within the app which has several fields, one field being a 'keyword' field which is comma separated. The current app view from Admin is like this: Django Admin View - App The fields within the entry: Django Admin View - Add Entry From front-end, I want to add an AJAX search that will check through the keywords in each entry within the app and return the corresponding fields dynamically below the search bar. The front end search will look something like this: Frontend Search Below the search bar, for each matching keyword, I want the metric name, metric URL and metric embed code to be presented. Hopefully the attached screenshots will help demonstrate things visually as I may not be describing this very accurately. Any help is highly appreciated :) -
Django 'http://localhost:8000' has been blocked by CORS policy
I have an error on the server http://95.216.155.54:8000/ (local host is OK) from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I tried the following (followed this page How can I enable CORS on Django REST Framework) pip install django-cors-headers # Added at the top of MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # Added after allowed hosts CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True After the changes below I have You can see the error in browser developer's mode VM87:5553 crbug/1173575, non-JS module files deprecated. How can I fix the error? -
Django: DRF relationship key issues
I am facing an issue while trying to create a model that another model has a foreign key to and each time an instance is created in the model the model that has a relationship to the model needs to update as well but I don't think this is a good way to create relationships class User(AbstractBaseUser, PermissionsMixin): .... #three fields pointing to one model owner = models.ManyToManyField(School, verbose_name=_( "Ownes"), related_name='owner', blank=True) workes_at = models.ForeignKey(School, verbose_name=_( "Workes at"), related_name='Workes_at', on_delete=models.PROTECT, blank=True, null=True) learns_at = models.ForeignKey(School, verbose_name=_( "Learns at"), related_name='learns_at', on_delete=models.PROTECT, blank=True, null=True) this way I have the issue I talked about above as when I want to create a school instance the owner would need to be set on the user model I also put the fields in the school model but that would mean when I want to filter users based on the schools they go to or own or work at, and also creating students or workers would be a hard task, I want to know what the recommended way to do this kind of stuff if maintaining 3 foreign key fields to the same model is not a good idea please recommend me another way, I have … -
Django Invalid credentials: User object check_password returns True, but authenticate function returns False
I've a user account in Django's default User model, where the account's check_password() is True, but the authenticate function doesn't return user the object with the same password, and it is happening only for this user. >>> from django.contrib.auth import authenticate >>> from django.contrib.auth.models import User >>> user = User.objects.get(username='user_1') >>> user.check_password('1234') // returns True >>> authenticate(username='user_1', password='1234') // returns False and most importantly it happens only to this user object [username: user_1] and not to any other users. I've tried resetting the password using set_password() >>> user.set_password('1234') >>> user.save() Even after resetting the password, the authenticate still doesn't returns the user object and it resets for other users properlly. The question is, why it is happening for a specific user and not for any other users. Django version: 2.2 -
Why Django form.save() returns object(None)?
from django.shortcuts import render from django.forms import forms from .models import Chart, ChartData from .forms import ChartForm, ChartDataForm import datetime def home(request): chart_form = ChartForm(request.POST) chart_data_form = ChartDataForm(request.POST) context = { 'chart_form': chart_form, 'chart_data_form': chart_data_form, } if chart_form.is_valid(): chart_obj = chart_form.save() chart = Chart.objects.get(pk=23) print(chart_obj) print(chart) return render(request, 'charts/home.html', context) chart_form.save() returns "Chart object (None) I have to eventually pass the chart_obj to another model for the foreign key, but right now it brakes there with error - save() prohibited to prevent data loss due to unsaved related object. In the admin site I see that the object is created. -
__str__ returned non-string (type NoneType) error when trying to save in Django admin menu
I have create a custom user model for my project. I am using python-social-auth to log the user in. Logging in and getting the user data to database works fine but when I go to admin panel to change something manually I get this error. Even if I am not changing anything and just click save I get the same. Why is this happening? Models.py from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from .managers import CustomUserManager # Create your models here. class CustomUser(AbstractUser): username = models.CharField(max_length=32, blank=True, null=True) name = models.CharField(max_length=200, unique=True) steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True, db_column='steam_id') player = models.TextField(null=True) user_coins = models.FloatField(default=0.00) is_active = models.BooleanField(default=True, db_column='status') is_staff = models.BooleanField(default=False, db_column='isstaff') is_superuser = models.BooleanField(default=False, db_column='issuperuser') USERNAME_FIELD = "name" REQUIRED_FIELDS = [] objects = CustomUserManager() def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser -
relation "django_content_type" or "auth_user" does not exist does not exist with multiple database django
There are similar questions to this, but none has helped me. I'm gonna be very specific with my issue. Hopefully why the error will help not just me. Context: I'm using Django 3.2.9. I have a UserProfile model which is a OneToOne to the Auth model. The UserProfile is in an app called, account, which is added to installed apps. I want to use multiple databases, therefore, I have set the 2 databases accordingly DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), "other": dj_database_url.parse(os.environ.get("AUTH_DATABASE_URL")), } To route, I have added this file class AuthRouter: route_app_labels = {'auth', 'contenttypes', 'account'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'other' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'other' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'other' return None And then I point to this DB routing in my settings.py file as DATABASE_ROUTERS = ['account.routers.db_router.AuthRouter'] After migrating and everything, this works fine when I run the server. The Admin and API requests work as expected. No issues there. My Problem: In the current above … -
Django queryset window aggregates
I have a fairly simple model, let's call it Metric: class Metric(models.Model): metric_1 = models.FloatField() ... Now suppose there is a metric for each day and person, and I have an endpoint that calculates the average of those metrics over a given period, and the change compared to the previous month. A straight forward (but probably inefficient?) approach: def calculate_aggregates(self, previous_start, start, end, member): metrics = DailyLoadDataMetric.objects.filter(target_member=member, target_date__gte=previous_start, target_date__lte=end) previous_metrics = metrics.filter(target_date__lte=start) current_metrics = metrics.filter(target_date__gte=start) curr_aggregates = current_metrics.aggregate( average_metric_1=Avg('metric_1'))) prev_aggregates = previous_metrics.aggregate( average_metric_1=Avg('metric_1')) aggregates = { 'average_metric_1': curr_aggregates['average_metric_1'], 'average_metric_1_change': ((curr_aggregates['average_metric_1'] / prev_aggregates['average_metric_1']) - 1.0) * 100, } return aggregates It seems that something like this could be performed by completly by the database. But how? Specifically since I need the average value from the previous month, I have to perform two aggregate calls, hitting the db twice. I have looked into window functions, but it seems they can only be used with annotate, which does not seem like the thing I want. Is there something that takes an entire queryset, and calculates aggregates based on a given partitioning? In this case, it could even be a fixed number of rows, because I know I have one Metric row for each … -
Django: Create new model attributes from current model variables
As I am new to Django I am practicing building a money-saving app. In the app, I want to create model attributes from my current model input. The user-created model fields look like this: class Items(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) item_name = models.CharField(max_length=200, null=False, blank=False, default='Enter name') item_category = models.ForeignKey(Categories, null=True, blank=True, on_delete=models.SET_NULL) item_created_at = models.DateTimeField(auto_now_add=True, null=True, blank=False) item_start_date = models.DateField(null=True, blank=False) item_end_date = models.DateField(null=True, blank=False) item_purchase_price = models.FloatField(null=True, blank=False) item_rest_value = models.FloatField(null=True, blank=False) def __str__(self): return self.item_name Using four of these fields (item_start_date, item_end_date, item_purchase_price, item_rest_value) I want to calculate several things. Save goal (purchase price - rest value) Save period in days (end date - start date) Days passed (end_date - current_date) I tried this doing the below: def __init__(self, item_name, item_start_date, item_end_date, item_purchase_price, item_rest_value): self.item_name = item_name self.item_start_date = item_start_date self.item_end_date = item_end_date self.item_purchase_price = item_purchase_price self.item_rest_value = item_rest_value def get_saving_goal(self, item_purchase_price, item_rest_value): return self.item_purchase_price - self.item_rest_value def get_date_delta(self, item_end_date, item_start_date): return self.item_end_date - self.item_start_date def get_days_passed(self, ): from datetime import date today = date.today() return today - self.item_start_date ## probably will need something like a datediff function Question 1: However, when I add these methods below the model fields, it shows this error. How … -
git push origin master, is showing nothings in the bitbucket repository
I'm trying to push my project for the first time in bitbucket, when I type git push origin master, as i choose master for my branch, it's shows nothing in the repository I have created in bitbucket. the messages throws at me: * [new branch] master -> master when I type git push origin master --force the message: git push origin master --force Everything up-to-date -
Altering django model data based on link selected in prior view
I would like the link that a user clicks on to instantiate a model differently on a subsequent view. I have a page ‘tools.html’ that is a templateView: urls.py path( "tools/", TemplateView.as_view(template_name="pages/tools.html"), name="tools", ) tools.html has two links (AP and AD) on it - both should go to the same template ’se_balance.html’ a page where users complete a form. The view for se_balance.html is: class CaseView(TemplateView): model = Case template_name = "../templates/se_balance.html" def get(self, *args, **kwargs): print('getting') case_form = CaseForm sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none()) return self.render_to_response( { "case_form": case_form, "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) The ‘Case ‘ model is as follows: class Case(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed case_id = models.UUIDField( primary_key=True, unique=True, default=uuid.uuid4, editable=False ) # Remove blank=True if we want to make login compulsory user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL ) P_CHOICES = [(‘AD’, ‘AD’), (‘AP’, ‘AP’),] Depending on the link that was clicked at tools.html I would like the model instantiated differently (i.e.e with P_CHOICEs as Either ‘AD’ or ‘AP’ but I am not sure of the correct way to do this? Thanks! -
Bootstrap Table not sending selected checkbox values in POST request in Django app
I am using Bootstrap Table (https://bootstrap-table.com/) to display a product list in a Django app. I would like the user to select some products and click the button to submit. Using Bootstrap Table seems to prevent the checked checkboxes being sent in the POST request. views.py class ProductProcessView(View): def post(self, request): products = request.POST.getlist('product_checkboxes') # process the chosen products return redirect('product-list') html template <form method="post"> {% csrf_token %} <table class="table-striped" data-toggle="table" > <thead> <tr> <th data-field="product_id" data-checkbox="true"></th> <th data-field="product">Product</th> </tr> </thead> {% for product in product_list %} <tr> <td><input type="checkbox" name="product_checkboxes" value="{{ product.id }}"></td> <td>{{ product.short_name }}</td> </tr> {% endfor %} </table> <button onclick="location.href='{% url 'process-products' %}'">Select Products</button> </form> If I remove the line data-toggle="table" this correctly sends the selected product IDs in the POST request, but with that line included it does not send any IDs at all. Bootstrap Table requires the data-toggle="table" attribute to initialise the table so without it there is no formatting. This is the request.body with data-toggle="table" included: <QueryDict: {'csrfmiddlewaretoken': ['fOma6gtvG2ETw1hrVYMdIuSUWuE1RA2jpX2Tae7ntipMPGX4yKNYEGgkHD0Jcuco'], 'btSelectItem': ['on', 'on']}> This is without it: <QueryDict: {'csrfmiddlewaretoken': ['Si6UyiTZ4yAJNYKKQ9FtA8dk0gNPGTPp2rMDCgxRROlC6DqntVGewkBKLp9x1NZu'], 'product_checkboxes': ['43004', '43006']}> I would be very grateful for any ideas about how I can use the Bootstrap Table framework with it's formatting and … -
Filtering unseen messages in Python Django
I have two models, ChatBox and Message. I want to loop through all chats and display them, and I want to display a count of unseen messages (Message model is in a foreign key relation) for each chat. Could anyone please help me to do this since I ve been strugling with it for few hours. Firstly I wanted to pass each object from the loop to django filters/tags and add a count of unseen messages to it, but I got advised to use objects.annotation. However, i can not find ways to implement none of these. Here is my view that displays inbox: class InboxView(LoginRequiredMixin, ListView): model = ChatBox template_name = 'chat/inbox.html' def get_queryset(self): # getting all chats for a request.user object_list = ChatBox.objects.filter(Q(user1=self.request.user) \ | Q(user2=self.request.user)).all() return object_list And here are my models: class ChatBox(models.Model): user1 = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user1') user2 = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user2') slug = models.SlugField(_("Slug"), max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Message(models.Model): chat = models.ForeignKey(ChatBox, on_delete=models.CASCADE) sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sender') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) seen = models.BooleanField(default=False) -
how to get highest value in django model for each objects
admin want to add diffrent challenges. each challenge have lot of users . each users maybe have lot of likes . i want to show the winner of each challenge. for that i need to get which candidate get highest like . how can i get it . is there any way like .count .? how can i use that ? in which model . for example :- challenges 1 first_contest 2 second_contest candidates id name contest 1 jhon first_contest 2 sara second_contest 3 abi first_contest candidates likes id user_id candidate_id 1 1 1 2 2 2 3 1 1 in this case cadidate 1 = jhon get 2 likes so in first contest jhon wins . also in second contest sara get 1 like . so i need show the winner in first contest . how is that ? models.py class Challenge(models.Model): title = models.CharField(max_length=50) class Candidates(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) image = models.FileField( upload_to="challenge_candidates/",) def likes_count(self): return self.likes.all().count() class CandidateLikes(models.Model): like = models.CharField(max_length=10) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='candidate_likes') contest_candidates = models.ForeignKey(Candidates, on_delete=models.CASCADE, related_name='likes') sorry for my poor english . thank you . -
Django should connect to MSSQL
I am using PyCharm, Django and the MSSQL-Backend-Project. I am working on my iMac, and in the local network there is a Microsoft SQL Server I would like to connect to. I am not sure what credentials to use (IP, oder the HOST named below). However with first attempt I get a hole lot of errors. Which seams for me not to be a problem with the credentials, but with some installation error or something. I already installed a ne virtual environment (a suggestions I found on google). But still not working. Can anyone help me, where to start? settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'bnt': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'POS', 'USER': 'l.bamberg', 'PASSWORD': '****************', 'HOST': 'BNTS20005\\SQL17STD', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } Error message: Traceback (most recent call last): File "/Users/georghuber/Desktop/Waschhalle/venv/lib/python3.7/site-packages/sql_server/pyodbc/base.py", line 11, in <module> import pyodbc as Database ImportError: dlopen(/Users/georghuber/Desktop/Waschhalle/venv/lib/python3.7/site-packages/pyodbc.cpython-37m-darwin.so, 0x0002): Library not loaded: /usr/local/opt/unixodbc/lib/libodbc.2.dylib Referenced from: /Users/georghuber/Desktop/Waschhalle/venv/lib/python3.7/site-packages/pyodbc.cpython-37m-darwin.so Reason: tried: '/usr/local/opt/unixodbc/lib/libodbc.2.dylib' (no such file), '/usr/local/lib/libodbc.2.dylib' (no such file), '/usr/lib/libodbc.2.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, … -
How to remove 'GET?' string from URL when submitting a GET form
I'm working on a search feature. When user enters a keyword, he or she should get a list of brands. The current URL is 'http://127.0.0.1:8000/brand/list' And if I search for "bag", it should be "http://127.0.0.1:8000/brand/list?keyword=bag" But now, it's "http://127.0.0.1:8000/brand/list/GET?keyword=bag". I wanna remove the 'GET?' thing. How can I do this? I don't know why but I can't find any solutions to this. <section id="brand-list"> <form action="GET"> <input type="text" name="keyword"> <button>Search</button> </form> </section> Thank you! -
Django users last login = NULL ordered in different way between local and production
I have this ListView which returns a list of users ordered by last_login. class ListaUtentiOrderedByLastLogin(StaffRequiredMixin, ListView): model = EmailUser context_object_name = "lista_utenti" template_name = "emailusers/lista_utenti.html" paginate_by = settings.PAGINATION_NUM def get_queryset(self): if self.kwargs['order'] == "asc": return EmailUser.objects.order_by('last_login',Upper('last_name'), Upper('first_name'), Upper('email')) else: return EmailUser.objects.order_by('-last_login',Upper('last_name'), Upper('first_name'), Upper('email')) Locally users are ordered with last_login NULL < NOT_NULL so in descending case users not yet logged are at the bottom of the user list. But in production NULL > NOT_NULL and same users are at the top of the list. Locally I use squlite db and the webserver included in manage.py Production: postgresql + gunicorn + nginx -
Python Django PowerShell Installer
I created an automatic script for installing Django in Windows PowerShell. What needs to be improved? I did multiple tests and it seems ok to me. Can anyone help me test on their system? The script can be run from the PowerShell terminal with the command like: .\django.ps1 -name "DjangoProject" -username "admin" param($name, $username) $CurrentPath = Get-Location $NewFolder = "$CurrentPath\$name" $ForbiddenNames = 'asgiref', 'Django', 'sqlparse', 'tzdata2' if (-not(Get-Command 'python' -errorAction SilentlyContinue)) { Write-Host "You must install Python first. You can download the latest stable Python version from https://www.python.org/downloads/" -ForegroundColor "Red"; break } elseif ($name.length -eq 0) { Write-Host "Error! Missing Required Command Line Arguments: django [-name] 'your_project_name' [-username] 'your_username'" -ForegroundColor "Red"; break } elseif ($name -match '[^A-Za-z0-9_]') { Write-Host "CommandError: '$name' is not a valid project name. Please make sure the name is a valid identifier." -ForegroundColor "Red"; break } elseif (Test-Path -Path $NewFolder) { Write-Host "You cannot create a project named '$name', it already exists a folder with this name in current path. Please try another name." -ForegroundColor "Red"; break } elseif ($name.length -gt 30) { Write-Host "Error: The name ""$name"" is greater than 30 characters. Please try another name." -ForegroundColor "Red"; break } else { Write-Output "import $name" … -
Deployment problem: socket.io -- Apache2 Server on linux ubuntu 20.04
My project is created with React (create-react-app), React router (no webpack), -- Django (rest) and Socketio with eventlet on the backend. I have 3 problems with deployment with apache2 - Everything worked perfectly on development: Created 2 conf files, one for the frontend port 80 and one for the backend port 8000 - separetely they work fine relatively. The problem I have with deployment: Socket.io gives [wsgi:error] eventlet.wsgi.server(eventlet.listen(("", 8000)), application, log_output=False) sock.bind(addr) Address already in use checked what uses the port --> only apache2 and it gives the same result with any other port tried to create a separate conf file for socket with port 5000 (changing the port in wsgi eventlet line), same result the socketFile.conf: Listen 5000 <VirtualHost *:5000> ServerName www.yawp.live ServerAlias yawp.live ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/path/to/main/folder> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess exampleSocket python-home=/home/path/to/venv python-path=/home/path/to/main/folder WSGIProcessGroup exampleSocket WSGIScriptAlias / /path/to/wsgi.py </VirtualHost> Not sure how to create an equivalency to sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) socketio_app/views.py async_mode = None import os import socketio basedir = os.path.dirname(os.path.realpath(__file__)) sio = socketio.Server( async_mode=async_mode, logger=False, cors_allowed_origins='http://localhost:3000' ) thread = None ... wsgi.py import os from django.core.wsgi import get_wsgi_application from socketio_app.views import sio import socketio import … -
Django TypeError: 'set' object is not reversible
I'm new to Django, and I followed a tutorial online. I have two paths for this app, and I'm trying to link two paths. But unexpectedly, when I use {% url 'name' %}, TypeError at /task/add occurs. here's my code: #urls.py from django.urls import path from . import views #app_name = "tasks" urlpatterns = [ path("", views.index, name="index"), path("add", views.add, name="add") ] #index.html {% extends "tasks/layout.html" %} {% block body %} <ul> {% for task in tasks %} <li>{{ task }}</li> {% endfor %} </ul> <a href="{% url 'add' %}">Add a New Task</a> {% endblock %} I tried to re-run my virtual server, but it's not the case. any idea why it's going wrong? #error trackback TypeError at /task/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/task/ Django Version: 4.0.2 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: /home/ryan/Documents/lecture3/newenv/lib/python3.8/site-packages/django/urls/resolvers.py, line 496, in _populate Python Executable: /home/ryan/Documents/lecture3/newenv/bin/python Python Version: 3.8.10 Python Path: ['/home/ryan/Documents/lecture3/lecture3', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ryan/Documents/lecture3/newenv/lib/python3.8/site-packages'] Server time: Sat, 05 Feb 2022 10:53:49 +0000 Error during template rendering In template /home/ryan/Documents/lecture3/lecture3/task/templates/tasks/index.html, error at line 9 'set' object is not reversible 1 {% extends "tasks/layout.html" %} 2 3 {% block body %} 4 <ul> …