Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
Django APscheduler prevent more workers running scheduled task
I use APScheduler in Django, on Windows IIS to run my background script. Problem is, taks gets run multiple times. If I run same program on my PC, it only runs once, but when I upload to windows server (which hosts my Django app) it runs more times. I guess it has some connection with the number of workers? Job is scheduled, but each time job task is done, it's like it runs random number of instances. First 1 time, then 2, then 10, then again 2. Even tho I have 'replace_existing=True, coalesce= True, misfire_grace_time = 1, max_instances = 1' planer_zad.py from apscheduler.schedulers.background import BackgroundScheduler from blog.views import cron_mail_overdue def start(): scheduler.add_job(cron_mail_overdue, "cron", hour=7, minute=14, day_of_week='mon-sun', id="task002", replace_existing=True, coalesce= True, misfire_grace_time = 10, max_instances = 1) scheduler.start() apps.py from django.apps import AppConfig class BlogConfig(AppConfig): name = 'blog' def ready(self): #print('Starting Scheduler...') from .planer import planer_zad planer_zad.start() For test I tried 'interval': scheduler.add_job(cron_mail_overdue, "interval", minutes=1, id="task002", replace_existing=True, coalesce= True, misfire_grace_time = 10, max_instances = 1) Tried: scheduler = BackgroundScheduler({ 'apscheduler.executors.default': { 'class': 'apscheduler.executors.pool:ThreadPoolExecutor', 'max_workers': '1' }, 'apscheduler.executors.processpool': { 'type': 'processpool', 'max_workers': '1' }, 'apscheduler.job_defaults.coalesce': 'True', 'apscheduler.job_defaults.max_instances': '1', 'apscheduler.timezone': 'UTC', }) scheduler.add_job(cron_mail_overdue, "cron", hour=9, minute=3, second=00, day_of_week='mon-sun', id="task002", replace_existing=True, coalesce= True, misfire_grace_time … -
One to many relationship flask
I have class which represents stuff: class Stuff(db.Model): id = db.Column(db.Integer, primary_key=True) price = db.Column(db.Integer, nullable=False) name = db.Column(db.String(100), unique=True, nullable=False) logo = db.Column(db.Text) description = db.Column(db.Text) def __repr__(self): return '<Stuff %r>' % self.name And have class which represents User: class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) name = db.Column(db.String(80), unique=False, nullable=False) cart = db.Column(db.Text) def __repr__(self): return '<User %r>' % self.name Here cart is json string like ["Stuff_id_1", "Stuff_id_2"] To add new item i just change this string I understand that my way of using cart field is dumb How to make relationship one to many? -
Getting error while installing mysqlclient on Mac ( Terminal )
I am trying to install mysqlclient on my mac to connect MySQL database to django for a website and I always face an error for the command : pip install mysqlclient Error: ERROR: Could not find a version that satisfies the requirement mysqlclient (from versions: 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.3.9, 1.3.10, 1.3.11rc1, 1.3.11, 1.3.12, 1.3.13, 1.3.14, 1.4.0rc1, 1.4.0rc2, 1.4.0rc3, 1.4.0, 1.4.1, 1.4.2, 1.4.2.post1, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.1.0rc1, 2.1.0). ERROR: No matching distribution found for mysqlclient I even tried installing specific versions of mysqlclient: pip install mysqlclient==2.0.0 But I still get an error. -
DRF: Can't create object null. Error: value in column "network_from_id" violates not-null constraint
I want to create Transaction object. But have error: django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "network_from_id" violates not-null constraint DETAIL: Failing row contains (6, 12, null, null). What is wrong in my code? And what is the proper way to create object with ModelViewSet? My code: models.py class Networks(models.Model): Name = models.CharField(max_length=50) ... class Transaction(models.Model): network_from = models.ForeignKey(Networks, on_delete=models.DO_NOTHING) network_to = models.ForeignKey(Networks, on_delete=models.DO_NOTHING) ... view.py class TransactionView(viewsets.ModelViewSet): serializer_class = TransactionSerializer queryset = Transaction.objects.all() def get_transaction_create_serializer(self, *args, **kwargs): serializer_class = TransactionSerializer kwargs["context"] = self.get_serializer_context() return serializer_class(*args, **kwargs) def create(self, request, *args, **kwargs): serializer = self.get_transaction_create_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = {"result": serializer.data} return Response( response, status=status.HTTP_201_CREATED, headers=headers ) serializers.py class TransactionSerializer(serializers.ModelSerializer): network_from = serializers.SerializerMethodField() network_to = serializers.SerializerMethodField() class Meta: model = Fee fields = '__all__' def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance -
Django The current path, randombet/1, didn’t match any of these
I was greeted with this 404 when i tried to access http://192.168.68.106:8000/newapp/1 Using the URLconf defined in test_01.urls, Django tried these URL patterns, in this order: 1.admin/ 2.polls/ 3.newapp [name='index'] 4.newapp testform/ [name='testform'] 5.newapp thanks/ 6.newapp 1/ The current path, newapp/1, didn’t match any of these. following the poll tutorial on the official doc ( https://docs.djangoproject.com/en/4.0/intro/tutorial01/ ), the polls app works fine. and the newapp index also works. but when I try to add new pages to expand itno the app by creating new pages to it ( namely testform/, thanks/, 1/), I get a 404 in response. views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from .forms import TestForm class IndexView(generic.View): template_name = "newapp/index.html" def get(self, request, *args, **kwargs): context = { /mycontexts } return render(request, self.template_name, context) class TestForm(generic.edit.FormView): form = TestForm template_name = "newapp/form_test.html" success = "/thanks/" def thanks(request): return HttpResponse("thanks!") def test1(request): return HttpResponse("good") urls.py from . import views app_name = "newapp" urlpatterns = [ path("", views.IndexView.as_view(), name="index"), path("testform/", views.TestForm.as_view(), name="testform"), path("thanks/", views.thanks), path("1/", views.test1), ] what have be baffled is clearly the framework understand that I do have the view and … -
How to restrict content, search result by users origin
I hope someone would be able to give an answer or suggestion for the following. I have an application (Django/bootstrap/postgres) that contains books from in different languagues i.e. English, Arabic, Hindi, Bengali. I would like to restrict or control to view, search based on the users's origin. As an example, if an user logged in from UAE or Saudi Arabia, he will be able to search only all the books in English and Arabic like if someone logged in from India, he will be able to see books in Hindi and English. Any help would be much appreciated. -
Django, DRF: How do I prevent PageNumberPagination from issuing a count query for all but the first page?
How do I prevent PageNumberPagination from issuing a count query for all but the first page? I have managed to stop the pagination count query from being issued as shown below, but How can I make it so that no count queries are issued except for the first page (after page 1)? class CustomPaginatorClass(Paginator): @cached_property def count(self): return sys.maxsize class CustomPagination(PageNumberPagination): django_paginator_class = CustomPaginatorClass def paginate_queryset(self, queryset, request, view=None): page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = int(self.get_page_number(request, paginator)) data = super().paginate_queryset(queryset, request, view=view) if not data and page_number > 1: raise NotFound("No data found for this page") return data def get_paginated_response(self, data): return Response( OrderedDict( [ ("next", self.get_next_link()), ("previous", self.get_previous_link()), ("results", data), ] ) ) -
Ember 4.1. Django rest json api. Access field choices from OPTIONS request in Ember data model or elsewhere
My DRF JSON API backend responds with a JSON on OPTIONS request. The OPTIONS response includes field choices declared on Django model. On my frontend, in my Ember 4.1 app I want to use these exact same choices on my form select. Is there a way to access these choices on my Ember model? and if so, How do I do it? Here's an example OPTIONS response: { "data": { "name": "Names List", "description": "API endpoint for Names", "renders": [ "application/vnd.api+json", "text/html" ], "parses": [ "application/vnd.api+json", "application/x-www-form-urlencoded", "multipart/form-data" ], "allowed_methods": [ "GET", "POST", "HEAD", "OPTIONS" ], "actions": { "POST": { "name": { "type": "String", "required": true, "read_only": false, "write_only": false, "label": "Name", "help_text": "name", "max_length": 255 }, "name-type": { "type": "Choice", "required": true, "read_only": false, "write_only": false, "label": "Name type", "help_text": "Name type", "choices": [ { "value": "S", "display_name": "Short" }, { "value": "L", "display_name": " ] } } } } } -
I uploaded my python project on linode cloud server
I uploaded my python project on linode cloud server yet it doesn't show up on the URL. It works fine on my local host, but after uploading the file on the server which I created on linode, the domain is still empty. Please I need help with this problem. -
Django server - unable to change robot.txt file
my desired robots.txt rule as follow, allow all bots, allow all files to be accessed (DIS ALLOW none), site map : theoriginalwebsitename.com/sitemap.xml User-agent: * Disallow: Sitemap: https://www.theoriginalwebsitename.com/sitemap.xml the above code is saved in server but when accessing from outside I get below User-agent: * Allow: / Sitemap: mywebsite/sitemap.xml I wonder why https://www.theoriginalwebsitename.com/sitemap.xml not comes in sitemap directory -
sync field that declared only in migrations with models.py file
I have model field that declared only in migration file, I need to declare it in models.py file, but when I'm trying to do that I'm getting this error: ValueError: Error adding translation field. Model 'MyModel' already contains a field named 'name_en'.