Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: avoid multiple DB queries for recursive model
I have following models: class Topic(models.Model): ... class Article(models.Model): ... class ArticleInTopic(models.Model): topic = models.ForeignKey(Topic, on_delete=models.PROTECT) article = models.ForeignKey(Article, on_delete=models.PROTECT) depends_on = models.ForeignKey(ArticleInTopic, on_delete=models.PROTECT) class Meta: unique_together = ('topic', 'article', 'depends_on') With this models set I'm trying to express the following situation: there are some studying topics, each consists of multiple articles. However, in order to learn a topic one should read the articles related to the topic but not in any order, rather in order defined by article dependencies. This means that in context of a topic an article may have another article which is required to be read before reading this article. It is guaranteed that the article on which the current article depends on comes from the same topic. So, basically, this whole structure looks like an acyclic (it is guaranteed) graph with parent-child nodes relation. In the business logic of my app I'm going to sort the graph topologically so I can tell the user which Article to read 1st, 2nd, etc. However, the problem is the way Django fetches ForeignKey's data from the database. AFAIK it uses N+1 request to fetch all foreign keys. There is a solution to it - using select_related but this … -
Trying to create a one-time calculated field in Django model
Building my first Django app, and I'm running into a snag. I have a Django model that creates Job objects, and I want each job code to be unique and auto-generated, with a particular format. The format is: aaaMMnnYYYY, where aaa is a 3-letter client identifier that we set, nn is a counter that represents the nth job from that client in that month., and MM and YYYY are month and year respectively. e.g., for the 3rd job from client "AIE" in feb 2023, the ID would be AIE02032023. Using a calculated field with the @property decorator causes the field to be continuously updated, so I'm trying to do this by modifying the save() method. There's also a related Cost object that has Job attributes via Foreign Key. The way I have it now, when I add a Cost, the 'iterating' part of the job code iterates, changing the job code, which causes uniqueness errors as well as URL errors (I'm using the job code in the URLConf. As a side note, I'd also like to be able to override the job code. Is there a way to set flags within a model, such as job_code_overridden = False, etc.? Here's … -
Django FirstApp
`# This is the url :Link views.py code: ` from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the poll index.")` urls.py code: (this is inside polls app urls.py file) : ` from django.urls import path, include from django.conf import settings from . import views urlpatterns = [ path(r'^$', views.index, name='index'), ] ` urls.py code : ( this is root urls.py file code): ` from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] ` here my run command : python manage.py runserver 8080 Unable to run this I am getting an error: `Page not found (404) Request Method: GET Request URL: http://35527a91f40c4e228d6c464d8a8c8487.vfs.cloud9.eu-west-1.amazonaws.com/ Using the URLconf defined in PollApp.urls, Django tried these URL patterns, in this order: poll/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.` Today I tried to run, But I am getting an error like this. ` -
This backend doesn't support absolute paths Django Google Storage
I have a Django app in Compute Engine. I set up a Google Cloud Storage as storage for my media files. In one endpoint, you can request for the file information including the file path. When I POST for this endpoint it returns: This backend doesn't support absolute paths. For simplicity my view for the endpoint look like this: class FilesView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): ... path = layer.file.path response_message = {'file': path } return Response(response_message, status.HTTP_200_OK) I have done the following: Create a service account and download the JSON. Configure it to my Django settings. I added the service account to the permissions in the bukcet i.e. set as Storage Admin. I added allUsers to have permission: Storage Legacy Object Reader. I changed the bucket from Uniform to Fine-grained. Here is in my settings: DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'sample-bucket' GCP_CREDENTIALS = os.path.join(BASE_DIR, 'sample-bucket-credentials.json') GS_CREDENTIALS = service_account.Credentials.from_service_account_file(GCP_CREDENTIALS) -
Link Django models together via GenericKey?
i have the following models: class Team(models.Model): users = models.ManyToManyField("User") class User(AbstractUser): ... class Subscription(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) name = models.CharField(max_length=64) class Package(models.Model): name = models.CharField(max_length=64) # packageA, packageB max_activation_number = models.PositiveIntegerField(default=1) class Activation(models.Model): subscription = models.ForeignKey("Subscription", on_delete=models.CASCADE) package = models.ForeignKey("Package", on_delete=models.CASCADE) created = models.DatetimeField() class PackageA(models.Model): ... class PackageB(models.Model): ... A team has one subscription and it can activate one or more package and the same package could be activated more than one time. (number of times specified with "max_ativation_number") Example: A team has a subscription called Suite and the available packages are: EmailAccount and Calendar The team choose to activate 3 EmailAccount and 2 Calendar (packages are not tied to each other) For that reason the team could activate the same package more times. For every activation i need to create a new instance on PackageA or PackageB (it depends on the choice a team made) and then i should "link" to that instance somehow. Should i use GenericKey field inside Activation model? I not only need the name of the chosen package but I also need to figure out which instance. -
Firebase get method returning a list for one object of objects and a dict for another
Im using django with firebase and have 2 objects of objects in the database, everything about them is the same, the way i store them in the database, the way im trying to access them. When i use the get method phones = ref.child('Data').child('users').child(uid).child('phones').get() computers = ref.child('Data').child('users').child(uid).child('computers').get() (absolutely the same way) for the fisrt one i get a list of dict looking like that [{'OS': 'Windows', 'battery': 2000.0, 'memory': 16.0, 'popularity': 200.0, 'price': 2429.73, 'screen': 6.0}, {'OS': 'Windows', 'battery': 1600.0, 'memory': 32.0, 'popularity': 200.0, 'price': 1907.28, 'screen': 6.0}] and for the second one i get a dict of dict like this one {'12': {'cd': 'no', 'hd': 5.0, 'multi': 'no', 'premium': 'yes', 'price': 1397.0, 'ram': 5.0, 'screen': 2.0, 'speed': 5.0}, '13': {'cd': 'yes', 'hd': 45.0, 'multi': 'no', 'premium': 'no', 'price': 1999.0, 'ram': 8.0, 'screen': 14.0, 'speed': 120.0}} the second one also has their id below which they are stored (i store them like that ref = db.reference("Data/users/"+str(request.session['user_id'])+'/phones/'+str(phone.id)) telephone = phone.save_to_firebase() ref.set(telephone), ref = db.reference("Data/users/"+str(request.session['user_id'])+'/computers/'+str(comp.id)) computer = comp.save_to_firebase() ref.set(computer)) i want both of them to look like the second and have no idea why they differ I checked everything but there is not a single difference about how the objects are treated -
fromisoformat: argument must be str Django
TypeError at /profile/updateAuction/updateData/1 fromisoformat: argument must be str I have this problem when I want to update expiration date by the form, but it changes in admin panel. But I want to make changeable for user. views.py @permission_classes([IsOwnerOrReadOnly]) @login_required(login_url='/accounts/login') def updateData(request, id): title = request.POST['title'] description = request.POST['description'] expiration_date = (request.POST['expiration_date'], f'%m/%d/%Y') lot_cost = request.POST['lot_cost'] image = request.POST['image'] updatedUser = Auction.objects.get(id=id) updatedUser.description = description updatedUser.expiration_date = expiration_date updatedUser.lot_cost = lot_cost updatedUser.cover = image updatedUser.title = title updatedUser.save() return HttpResponseRedirect(reverse('index')) models.py class Auction(models.Model): title = models.CharField(max_length=255, null=False, blank=False) image = models.ImageField(upload_to='images', default='images/no-image.svg') description = models.TextField(null=False, blank=False) lot_cost = models.PositiveIntegerField(null=False, blank=False, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expiration_date = models.DateTimeField() user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) updateAuction.html <form action="./updateData/{{ Auction.id }}" method="post" class="row w-25"> {% csrf_token %} Title: <input name="title" value="{{ Auction.title }}"> Description: <input name="description" value="{{ Auction.description }}"> Image: <input type="file" name="image" value="{{ Auction.cover }}"> Cost: <input type="number" pattern="[0-9]" min="0" name="lot_cost" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="{{ Auction.lot_cost }}"> Expiration date: <input type="date" name="expiration_date" value="{{ Auction.expiration_date }}"> <input type="submit" value="update" name="submit"> </form> -
[Django Rest Framework, try to call a specific header
I've got a view based on viewsets.ReadOnlyModelViewSet. All works fine when i call my API with my custom pagination. Now, I would like to implement a custom http header and call it with 'curl -I'. I know that is possible with Response(data, headers=[{'something': something}) Response documentation and : -->> https://github.com/encode/django-rest-framework/blob/22d206c1e0dbc03840c4d190f7eda537c0f2010a/rest_framework/mixins.py#L35 However, when i try to write my header like that, my custom pagination disapears. Is there a specific way to write headers with viewsets.ReadOnlyModelViewSet ? Thanks for reading me ! -
How to use API rest Framework for Images in Django
hello guys I am trying to create product model for my product details .i have some images for one product .i want to add multiple images in my django dashboard so i wrote this codes now i want show them in my template but i cant why? Here's my: Models.py : class Product(models.Model): name =models.CharField(max_length=100,verbose_name='نام محصول') header_pic = models.ImageField(upload_to="images/products",verbose_name='تصویر اصلی', default='images/product/product1.png') created_date =models.DateField(auto_now_add=True) description = RichTextField(blank = True , null=True) class Image(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE, related_name="product_images") image = models.ImageField(upload_to="images/products/product-images",verbose_name='تصویر', null= True , blank=True) @property def get_image_url(self): return self.image.url serializer.py : from django.db.models import fields from rest_framework import serializers from .models import Product, Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class ProductSerializer(serializers.HyperlinkedModelSerializer): images = serializers.SerializerMethodField() def get_images(self, product): return ImageSerializer(product.product_images.all(), many=True).data class Meta: model = Product fields = ('id','images') views.py : class ImageViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer admin.py from django.contrib import admin from .models import Product , ProductCategory ,Image from . import models admin.site.register(ProductCategory) class ImageAdmin(admin.StackedInline): model = models.Image extra = 4 @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ImageAdmin] readonly_fields=('views', ) class Meta: model = Product @admin.register(Image) class ImageAdmin(admin.ModelAdmin): pass template.html : <div class="product-bottom-slider owl-theme owl-carousel" id="sync2"> {% for img in images %} <div … -
How to show nested serializer data in parent table(Serializer) single list in python django rest framework
Country table that is grandparent table class Country(models.Model): country_id = models.IntegerField(primary_key=True) cname = models.CharField(max_length=100) def __str__(self): return self.name State table which is a direct child of the country class State(models.Model): stateid = models.IntegerField(primary_key=True) state_name= models.CharField(max_length=100) s_country = models.ForeignKey(Country, related_name='scountry', on_delete =models.CASCADE) def __str__(self): return self.state_name City table which is a direct child of State and indirect child of Country class City(models.Model): cityid= models.IntegerField(primary_key=True) city_name = models.CharField(max_length=100) city_strength = models.IntegerField() city_state = models.ForeignKey(State, related_name='cstate', on_delete =models.CASCADE) def __str__(self): return self.sname Serializers class StateSerializer(serialiizer.ModelSerializer): class Meta: model = State fields = '__all__' class CitySerializer(serialiizer.ModelSerializer): class Meta: model = City fields = '__all__' class FliterStateCitySerializer(serializers.ModelSerializer): state = StateSerializer(many=true) cities = CitySerializer(many=true) class Meta: model = Country fields = ('id', 'state', 'city') Views class FilterStateCityView(generics.ListAPIView): queryset = Country.objects.all() serializer_class = FliterStateCitySerializer The response I am getting is. [ { "country_id":"23", "cname": "USA", "state" : { "stateid": "16", "state_name": "Florida", "cities" : { "cityid":"55", "city_name": "Miami", "city_strength ": 40005 }, { "cityid":"56", "city_name": "Orlando", "city_strength ": 930067 }, }, { "stateid": "17", "state_name": "Texas", "s_country" : "USA" }, } ] Response that i want... [ { "country_id":"23", "stateid": "16", "cityid":"55", "state_name": "Florida", "city_name": "Miami", "city_strength ": 40005 }, { "country_id":"23", "stateid": "16", "cityid":"56", "state_name": "Florida", … -
TemplateDoesNotExist at /accounts/login/
I have checked the answers here, here, here, and here, and though I am getting the same error apparently I have a different root cause since those answers do not work for me. Here's the problem: I am using Django's LoginView, overriding the template name, but it only sometimes works. If I get to the login screen from the navbar, it works great, but the same url when gotten to from a different method throws a template does not exist error. My URLs file: from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = "accounts" urlpatterns = [ path( "login", auth_views.LoginView.as_view(template_name="accounts/login.html"), name="login", ), path("logout", auth_views.LogoutView.as_view(), name="logout"), path("signup", views.SignUp.as_view(), name="signup"), ] I have a nav item for the login screen, and it works great. The relevant section in the template: {% else %} <li class="nav-item"><a href="{% url 'groups:all' %}" class="nav-link">Groups</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:signup' %}">Sign Up</a></li> {% endif %} If someone clicks the login link in the navbar, it takes you to http://127.0.0.1:8000/accounts/login and works great. BUT: I have another section of code where you need to be logged in for a link to work, and … -
How to configure DB for Django, Celery, and SQS
I'm trying to offload a montecarlo task to Celery, and save the results to PostgreSQL AWS DB (RDS) from views.py: newResults = MonteCarloResultTrue.objects.create(htmlCompanyArray = "[]") viewRun = runMonteCarloAsync.delay(checkedCompaniesIDs,newResults.id) The object is created, but in tasks.py, the DB object is not being edited: @app.task(bind=True) def runMonteCarloAsync(self,checkedCompaniesIDs, calc_id): newResults = MonteCarloResultTrue.objects.get(id=calc_id) newResults.htmlCompanyArray = "[asdf]" newResults.save() How can I update the DB from the Celery task? Do I need to explicitly tell Celery where to look for the DB? (settings.py): CELERY_accept_content = ['application/json'] CELERY_task_serializer = 'json' CELERY_TASK_DEFAULT_QUEUE = 'django-queue-dev' CELERY_BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.parse.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.parse.quote(AWS_SECRET_ACCESS_KEY, safe='') ) CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-east-1", 'polling_interval': 20 } CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' What am I missing? -
Single page application: How to prevent page reload when browser back button is clicked
I have a audio player in the base html file and I want it to continue playing when I navigate to other pages(home and playlist). It is working. But when I click the browser back button from the home or playlist page, the audio stops because the page reloads Note: I dont know how to post my codes here. I keep getting error -
Cant create a normal html in Django / python [closed]
Hello and a good morning 2all , i have since days the same problem cant find anything about it , i use Pythonnand Django , and in django i open a template folder , the. When i want create a html file the problem begins , i cant write test.html i dont get the icon that the file is a html , but when i write test.htm . It shows me its a html file , but it dont realy work , i think this is the problem for my other problem 😅. Windows 11 msi laptop raider ge76. , sometimes when i start the virtual env , it shows me the alert scripts deactivated cant start /activate/ or something I tried sme Variations , and google the problem but i never found andthing -
Trying to load a static css file and it doesn't work
Partial head.html - (that loads the static file) If I put the css code in a style tag in here, it works well {% load static %} <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/brands.min.css" integrity="sha512-G/T7HQJXSeNV7mKMXeJKlYNJ0jrs8RsWzYG7rVACye+qrcUhEAYKYzaa+VFy6eFzM2+/JT1Q+eqBbZFSHmJQew==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/solid.min.css" integrity="sha512-6mc0R607di/biCutMUtU9K7NtNewiGQzrvWX4bWTeqmljZdJrwYvKJtnhgR+Ryvj+NRJ8+NnnCM/biGqMe/iRA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="{% static '/recipes/css/styles.css' %}" > <title>Home</title> </head> Page home.html (that includes the partial head.html) {% include 'recipes/partials/head.html' %} <body> {% include 'recipes/partials/header.html' %} <main class="main-content-container"> <div class="main-content main-content-list container"> {% include 'recipes/partials/recipe.html' %} </div> </main> {% include 'recipes/partials/footer.html' %} </body> </html> settings.py (I have copied the STATICFILES_DIR from documentation, but that didn't solve it) from pathlib import Path DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'recipes' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'learning_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'base_templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_django.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': … -
Django create and register model backed by mongo
I am using Django with pymongo and there are reasons within the team to not use Djongo for MongoDb. Currently I am stuck at registering a model and set that in AUTH_USER_MODEL. I have created a custom user to handle auth via Mongo but I am not sure how to register it as AUTH_USER_MODEL as Django needs a real model there. What is the workaround if any on this? -
Automatically create a subdomain and associate it with its own front-end (Reactjs) and back-end (django)
I'm trying to build a SaaS website. The user registers an account and then automatically creates a subdomain, and based on his plan, the main site automatically links it with a react js frontend and an independent backend using Django After searching I found that I have to use the django_tenants library and Wildcard domain But the problem is that this only achieves the first part, which is only the creation of the subdomain, and I did not find any way to transfer the files and the independence of the subdomain with its files -
Django Form Not Rendering on Html
#forms.py from django import forms from django.forms import ModelForm from .models import Account class SignupForm(forms.ModelForm): class Meta: model = Account fields = ['first_name', 'last_name'] -
how can i create a cycle of comments and replies?
I wonder how can I make a cycle of comments and replies : I wanted to make a replyable comment but replies also need to be replyable to make a better communication but I'm just a student and don't have much experience here is my models : class Comment(models.Model): #comments model post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=300) user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta(): verbose_name_plural = 'Comments' ordering = ['date'] def __str__(self): return self.test[:50] class Reply(models.Model): #replying to comments comment = models.ForeignKey(Comment,on_delete=models.CASCADE) text = models.CharField(max_length=300) user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta(): verbose_name_plural = 'Replies' ordering = ['date'] def __str__(self): return self.text[:50] problem is that if i use this models i have to make a new model for every reply and it's not in cycle. also I tried to check if replyable comment works or not and i got a problem with view: I couldn't add both forms(comment, reply) in the same get_context_data() class PostDetailView(FormView, DetailView): #detail page of items template_name = 'pages/post_detail.html' model = Post form_class = CommentForm, ReplyForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self,request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): form_instance = form.save(commit=False) form_instance.user = self.request.user … -
Axios CORS unable to see any response header
Hi I have a frontend being served for testing from localhost making request to backend running at api.whatify.io which is an Nginx server fronting a Django backend. The client app code is: const axiosApi = axios.create({ baseURL: API_URL, withCredentials: true, }) export async function post(url, data, config = {}) { return axiosApi .post(url, {...data }, {withCredentials: true}) .then(response => response.data) .then(response => { console.log("response is", response); console.log("WOW GOT", response.headers); console.log("CUSTOM", response.headers.get("Cache-Control")); }) } The request and response headers are as follows as seen from browser: Request URL: https://api.whatify.io/auth/login Request Method: POST Status Code: 302 Remote Address: 54.194.218.202:443 Referrer Policy: strict-origin-when-cross-origin Response Headers: access-control-allow-credentials: true access-control-allow-origin: http://localhost:5173 access-control-expose-headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with, cache-control, pragma, Set-Cookie content-length: 0 content-type: text/html; charset=utf-8 cross-origin-opener-policy: same-origin date: Sun, 05 Feb 2023 01:21:28 GMT location: / referrer-policy: same-origin server: nginx/1.21.6 set-cookie: csrftoken=zaBGdsPdVSEm1ZRvgNKuGxQcr2mRJvhh; expires=Sun, 04 Feb 2024 01:21:28 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure set-cookie: sessionid=z3gygehf6gcwuc5pdq2v8kzff61ipcss; expires=Sun, 19 Feb 2023 01:21:28 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure vary: Origin, Cookie x-content-type-options: nosniff x-frame-options: DENY Request Headers :authority: api.whatify.io :method: POST :path: /auth/login :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9 content-length: 44 content-type: application/json origin: http://localhost:5173 referer: http://localhost:5173/ sec-ch-ua: … -
Cannot runserver from Pycharm using Vagrant Interpreter. Path for manage.py is wrong, don't know where to fix it
I'm trying to configure correctly Pycharm (for a Django project) + Vagrant, to launch the runserver remotely from my host machine (and thus enable debugging). The command for such seems simple but the path is wrong, so it fails. It tries to run /home/vagrant/.virtualenvs/[myprojname]/bin/python /vagrant/[myprojname]/manage.py runserver 0.0.0.0:8000 Second parameter is wrong, it's missing either the initial /home/ or it isn' a relative path. My run configuration I'm running a host windows machine, and a vagrant ubuntu 20.10 guest VB. I setup my remote interpreter with what I suppose are the right parameters. In my vagrantfile I have setup the shared folder as following (Project name is PoeMogul) config.vm.synced_folder "PoeMogul", "/home/vagrant/PoeMogul" In my vagrant box, everything is setup fine (I think). I have my venv. In my /home/vagrant/PoeMogul dir i can see my working directory from PyCharm. I can manually (through vagrant ssh) run the server. But i cannot make Pycharm invoke the manage.py file correctly, it tries to access "/vagrant/..." and not "/home/vagrant/...". -
How to paginate multiple queries in a single function-based-view or class-based-view in django?
I have a search function that queries multiple models. I have the expected results displayed in a html template and so far all is fine. The problem is that I want to paginate the results using django's built in Pagination class. Pagination with multiple models is where I'm now stuck. I have other class based views working well paginating single models. def search_results(request): if request.method == 'POST': searched = request.POST['searched'] books = Book.objects.filter(description__icontains=searched, title__icontains=searched).order_by('-id') sermons = Sermon.objects.filter(description__icontains=searched, title__icontains=searched).order_by('-id') other_sermons = SermonsByOtherFathers.objects.filter(description__icontains=searched, title__icontains=searched).order_by('id') other_books = BooksByOtherFathers.objects.filter(description__icontains=searched, title__icontains=searched).order_by('-id') context = { 'searched': searched, 'sermons': sermons, 'other_sermons': other_sermons, 'books': books, 'other_books': other_books, } if searched == "": return HttpResponse('Please type something in the search input.') return render(request, "search_results.html", context) This is a simplified version of my html template. {% for book in books %} <tr> <td> <a href="{{ book.book_instance.url }}"> {{ book.title }} </a> <p> {{book.author}} </div> <p> {{ book.category }} </p> <p> {{ book.description }} </p> </td> </tr> {% endfor %} <-- ...and the same loops goes for the rest of the other querysets. --> {% for book in other_books %} <-- code here --> {% endfor %} {% for sermon in sermons %} <-- code here --> {% endfor %} {% … -
issues with serving 2 django applications with apache in ubuntu server using wsgi
i'm trying to host a second domain in my ubuntu vps (domain2), i read online that is possible to host 2 domains in one vps (with one ip adress) yet i'm having some issues with it. i have this configuration in apache2 ubuntu under /etc/apache2/sites-enabled/000-default-le-ssl.conf: Define wsgi_daemon1 "domain1" Define wsgi_daemon2 "domain2" <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/my_linux_user/myproject/static <Directory /home/my_linux_user/myproject/static> Require all granted </Directory> <Directory /home/my_linux_user/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> <IfDefine !wsgi_init> WSGIDaemonProcess ${wsgi_daemon1} python-path=/home/my_linux_user/myproject python-home=/home/my_linux_user/myproject/myprojectenv WSGIProcessGroup ${wsgi_daemon1} WSGIScriptAlias / /home/my_linux_user/myproject/myproject/wsgi.py Define wsgi_init 1 </IfDefine> ServerName domain1.tn SSLCertificateFile /etc/letsencrypt/live/domain1.tn/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/domain1.tn/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> <VirtualHost *:443> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error_project2.log CustomLog ${APACHE_LOG_DIR}/access_project2.log combined Alias /static /home/my_linux_user/project2/static <Directory /home/my_linux_user/project2/static> Require all granted </Directory> <Directory /home/my_linux_user/project2/django_project> <Files wsgi.py> Require all granted </Files> </Directory> <IfDefine !wsgi_init> WSGIDaemonProcess ${wsgi_daemon2} python-path=/home/my_linux_user/project2 python-home=/home/my_linux_user/project2/project2ENV WSGIProcessGroup ${wsgi_daemon2} WSGIScriptAlias / /home/my_linux_user/project2/django_project/wsgi.py Define wsgi_init 1 </IfDefine> ServerName domain2 SSLCertificateFile /etc/letsencrypt/live/domain2/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/domain2/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> the first domain is served correctly but the second domain (domain2) is not, it actually still pointing to the default apache2 index page i tried restarting apache2 with: apachectl restart and with apachectl graceful checking the DNS configuration, the domaain … -
modelformset update multiple instance of model
I am trying to update multiple instance of a model using modelformset_factory to render out the said instances im my forms at one but it doesn't work. views.py: def approve(request,pk): user = User.objects.get(id=pk) requests = PendingRequest.objects.filter(member=user) RequestFormset = modelformset_factory(PendingRequest, form=Approve ,extra=0) if request.method == "POST": formset = RequestFormset(request.POST, queryset=requests) if formset.is_valid(): for form in formset: form.save() else: formset = RequestFormset(queryset=requests) return render(request, "books/approve.html",{"formset":formset, "users":requests}) forms.py: class Approve(forms.ModelForm): class Meta: model = PendingRequest exclude = ["member", "book_request", "not_approved"] models.py: class PendingRequest(models.Model): book_request = models.ForeignKey(BorrowBook, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default="", null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default="", null=True) approved = models.BooleanField(default=False) not_approved = models.BooleanField(default=False) approval_date = models.DateTimeField(auto_now=True, null=True) template <body> <form method="post" action="{% url 'approve' pk=users.0.member.id %}"> {% csrf_token %} {% for form in formset.management_form %} {{form}} {% endfor %} <table> <thead> <tr> <th>Book Title</th> <th>Approved</th> <th>Not Approved</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <td>{{ form.book }}</td> <td>{{ form.approved }}</td> </tr> {% endfor %} </tbody> </table> <button type="submit">Update</button> </form> </body> Whenever i click on the submit button in my template, it doesn't post any data to database. Any ideas on how to fix it. I also want to be able to set not_approved field to false if … -
Django: How to go to a URL with select option using views.py GET or POST instead of a JavaScript function
I show two solutions, one with GET, the other with POST. In both I have errors. GET case In templates I have the following form (I omit the JavaScript call that submits the form) <form id="myform" action="{% profiles:profile-detail slug=x.user %}" method="GET"> <select> <option value="view">View</option> </select> </form> In views.py I have class ProfileView(DetailView): model = Profile def get_object(self, *args, **kwargs): slug = self.kwargs.get('slug') user = User.objects.get(username=slug) profile = Profile.objects.get(user=user) return profile This approach takes me to the profile page of {{x.user}}=user1, however when I click the backward button in the browser, it goes from mypath/user1 to mypath/user1?. I don't like this ?. To go back to the previous page I would need to click the backward button twice. I would like to click it only once and remove this ? transition step. POST case In templates: <form id="myform" action="{% profiles:profile-detail slug=x.user %}" method="GET"> {% csrf_token %} <input type="hidden" name="slug" value={{x.user}}> <select> <option value="view">View</option> </select> </form> In views.py class ProfileView(LoginRequiredMixin, DetailView): model = Profile def post(self,request,slug): myslug = request.POST.get(slug) User = get_user_model() user = User.objects.get(username=myslug) profile = Profile.objects.get(user=user) return profile This shows the error DOESNOTEXIST. User matching query does not exist. the error page shows myslug=None and slug=user1. What would be an …