Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building wheel for psycopg2 ... error pip3 install psycopg2?
When I'm running pip3 install -r requirements.txt then show me errors I show you bellow I'm using python version 3.8 PostgreSQL 13.0 (Ubuntu 13.0-1.pgdg20.04+1) see my requirement.txt files here certifi==2018.4.16 chardet==3.0.4 click==6.7 croniter==0.3.24 Django==2.0.5 django-rq==1.1.0 et-xmlfile==1.0.1 idna==2.7 jdcal==1.4 lxml==4.2.3 openpyxl==2.5.4 #pkg-resources==0.0.0 psycopg2==2.7.5 psycopg2-binary==2.8.5 python-dateutil==2.7.3 python-decouple==3.1 pytz==2018.5 redis==2.10.6 requests==2.19.1 rq==0.12.0 rq-scheduler==0.8.3 six==1.11.0 Unipath==1.1 urllib3==1.23 so show me this error in terminal I share with you complete command message that i typed already pip3 install -r requirements.txt ✔ 2186 17:28:42 Requirement already satisfied: certifi==2018.4.16 in /usr/local/lib/python3.8/dist-packages (from -r requirements.txt (line 1)) (2018.4.16) Requirement already satisfied: chardet==3.0.4 in /usr/lib/python3/dist-packages (from -r requirements.txt (line 2)) (3.0.4) Requirement already satisfied: click==6.7 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 3)) (6.7) Requirement already satisfied: croniter==0.3.24 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 4)) (0.3.24) Requirement already satisfied: Django==2.0.5 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 5)) (2.0.5) Requirement already satisfied: django-rq==1.1.0 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 6)) (1.1.0) Requirement already satisfied: et-xmlfile==1.0.1 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 7)) (1.0.1) Requirement already satisfied: idna==2.7 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 8)) (2.7) Requirement already satisfied: jdcal==1.4 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 9)) (1.4) Requirement already satisfied: lxml==4.2.3 in /code/data/.local/lib/python3.8/site-packages (from -r requirements.txt (line 10)) … -
A Value Error As "attempted relative import beyond top-level package"
My Project looks like this : https://imgur.com/B7fHzb4 how do I import the views.py in the pages app onto urls.py file of the trydjango app? when I do : import pages.views gives ValueError: attempted relative import beyond top-level package. when i do: from ..pages import views it says no module pages as hint. -
How are many-to-many relationship handled in Django?
I have a shirt which can contain multiple colors, and multiple colors which can have multiple shirts. Normally I would express it the following way: In django I have the many-to-many (https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/) Example: publications = models.ManyToManyField(Publication) -- Can I create the table "Item_colors" consisting of 2 columns (no "ID" primary key) and design the models according to my diagram using the composite key: class Item_colors(models.Model): class Meta: unique_together = (('cloth_item_id', 'color_id'),) cloth_item_id = models.ForeignKey(Cloth_item, on_delete=models.CASCADE) color_id = models.ForeignKey(Color, on_delete=models.CASCADE) How is the many-to-many relation handled in a DB context, and does it yield better performance? -
Should I use environmental variables or decouple to store sensitive data in Django?
What would be the best option to store sensitive information in a Django project? What’s the difference between Environmental variables or decouple and when should I use each? -
Defining get_queryset in a view, attribute error
I'm trying to write a custom get_queryset function because I want to access the user's email from 'request.user.email', and use that to form another query, that i want to display using my view cartv(generic.ListView). First time asking a question here, scoured the site but haven't found anything similar, but if you do find something just direct me there i''l delete this asap Environment: Request Method: GET Request URL: http://192.168.24.169:8000/products/cart/ Django Version: 3.1.2 Python Version: 3.6.9 Installed Applications: ['products.apps.ProductsConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/home/nirman/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/nirman/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/nirman/.local/lib/python3.6/site-packages/django/views/generic/list.py", line 142, in get self.object_list = self.get_queryset() File "/home/nirman/Desktop/login/products/views.py", line 91, in get_queryset self.user = request.user Exception Type: AttributeError at /products/cart/ Exception Value: 'cartv' object has no attribute 'user' views: class cartv(generic.ListView): model = cart context_object_name = 'cart_list' template_name='products/cartview.html' def get_queryset(request): qs = cart.objects.filter(user__email=request.user.email) #error points here if qs.exists(): c = qs[0] return c.items.all() else: return redirect('failure') -
Django Admin Panel Choices from Database
I have a model that has a IntegerField and in the admin. I want to add choices to the widget as "University" field. There is no problem if i add the universities in list as "uniList". But I do not know how can add these universities from UniversityList Class. I want to add new universities to UniversityList on admin panel and then i want to choose these added universities in Mainland2 admin page. In this case i recieved error massage as "in get raise self.model.MultipleObjectsReturned(mainpage.models.MultipleObjectsReturned: get() returned more than one UniversityList -- it returned 5!" Thank you for in advance... from django.db import models from django import forms from django_countries.fields import CountryField from django.core.exceptions import ValidationError class UniversityList(models.Model): name = models.CharField(max_length=50) class Mainland2(models.Model): unilist = [ (0, "---"), (1, "Uni 1"), (2,"Uni 2"), (3,"Uni 3"), ] graduatedList=[ (0, "Diğer"), (1, "Lise"), (2, "Lise (Öğrenci)"), (3, "Ön Lisans"), (4, "Ön Lisans (Öğrenci)"), (5, "Lisans"), (6, "Lisans (Öğrenci)"), (7, "Yüksek Lisans"), (8, "Yüksek Lisans (Öğrenci)"), (9, "Doktora"), (10, "Doktora (Öğrenci)") ] def validate_digit_length(idName): if not (idName.isdigit() and len(idName) == 11): raise ValidationError('%(idName)s en az 11 karakter olmalıdır', params={'idName': idName}, ) name = models.CharField(max_length=20, verbose_name="Ad") midName = models.CharField(max_length=20, verbose_name="Orta Ad", null=False, blank=True) surName … -
full join 3 django models with ORM
I have following models Django: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=48, blank=True) bio = models.CharField(max_length=60, blank=True) about = models.TextField(blank=True) class SocialItem(models.Model): """ Renders available social network icons and placeholders on UI. Can only be added by admins """ name = models.CharField(max_length=64, unique=True) icon = models.ImageField(upload_to='social_icons', unique=True) placeholder = models.CharField(max_length=128, unique=True) class AccountSocialLink(models.Model): """Adds social network url to user's account""" account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='social') item = models.ForeignKey(SocialItem, on_delete=models.PROTECT) url = models.URLField() I have an account endpoint that returns the account data in this way: { "id": 5, "nickname": "Constantine", "bio": "Bio", "about": "" "social": [ { "id": 1, "item": 2, "url": "https://www.youtube.com/constantine" }, { "id": 2, "item": 3, "url": "https://www.instagram.com/constantine" }, { "id": 3, "item": 5, "url": "https://www.twitter.com/constantine" } ] } The SocialItem model is used for rendering on UI like in a form. For example, there are 5 social items available, but user has only 3 like above. But I do need to give the user options to fill out the remaining 2. What I need is an aggregation of these 3 models in one output so that the user can update their account by one request. The desired output is: { "id": 5, "nickname": "Constantine", … -
Django manage.py failing. module not found but actually installed in virtualenv
This is a very weird situation. I've been using django and venv for a while and during my last pull of code, when trying to run python manage.py collectstatic I ran into a "module not found" problem. however, this module is installed and if I try to reinstall it pip tells me I already have it. The strange thing is I'm seeing importlib using my system python path ("/usr/lib/python3.6...") which I think it should be my virtualenv path... If I run which python I get the correct venv python path... please help. I attach the error below: File "/home/ubuntu/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-mailbox' -
How to use SQL database and noSQL database in the same django app?
Is there a good practice to use a SQL database like PostgresSQL with a No SQL database like MongoDB in the same Django app? I know I can define more databases in the settings.py, but how do I tell my models which database to use? Is it a good idea after all or should I use one database in a given Django app? -
Enable to login into the application in Django tests
I am writing the test cases to my application. Please find below code snippet of tests.py class TestGetDetailsPositive(SimpleTestCase): def setUp(self): self.credentials = { 'username': '****', 'password': '****' } @responses.activate def test_get_details(self): self.client.login(username='****', password='****') response = self.client.get('/accounts/selectdetails/') self.assertContains(response, 'National', status_code=200) self.assertTemplateUsed(response, 'accounts/select-details.html') def test_view_url_exists_at_desired_location(self): url = reverse('selectdetails') self.assertEquals(resolve(url).func.view_class, SelectDetails) I am getting below error as follows. AssertionError: Database queries to 'default' are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add 'default' to accounts.tests.tests.TestGetBanksPositive.databases to silence this failure. Database configuration looks like below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****', 'USER': '****', 'PASSWORD': '****', 'HOST': '****', 'PORT': '****', } } Where I am doing wrong? -
create foreignkey object w/ extra actions on post
I have a financials serializer and nested serializers for balancesheets, income statements and cashsflows statements which have their own serializers for each respective componennt I am trying to post through an extra action on the Stock object to create a Financials instance, but receive the error below. what am I doing wrong ? BalanceSheet Serializer 309 class BalanceSheetSerializer(WritableNestedModelSerializer): 310 assets = AssetsSerializer() 311 liab_and_stock_equity = LiabAndStockEquitySerializer() 312 313 class Meta: 314 model = BalanceSheet 315 316 fields = [ 317 # "ticker", 318 "periodicity", 319 "assets", 320 "liab_and_stock_equity", 321 "end_date", 322 "start_date", 323 ] Stock Extra Action 25 @action(detail=True, methods=["post", "get"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 stock = self.get_object() 34 serializer = FinancialsSerializer(request.data) 35 Financials.objects.create(serializer.data) 36 Financials.save() ERROR web_1 | AttributeError: Got AttributeError when attempting to get a value for field `assets` on serializer `BalanceSheetSerializer`. web_1 | The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. web_1 | Original exception text was: 'str' object has no attribute 'assets'. web_1 | [14/Oct/2020 11:23:26] "POST /stocks/aapl/financials/ HTTP/1.1" … -
'Select a valid choice' error in Dependent/Chained Dropdown List even if its valid
i'm trying to implement this tutorial:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html on how to Implement Dependent/Chained Dropdown List with Django he said that we will get an error about select a valid choice i implemented the fix that he provided but the error still there i have been verifying my code from yesterday and it looks fine and the same as the tutorial here is my view class GlobalLessonView(CreateView): model = Lesson form_class = GlobalLessonForm success_url = reverse_lazy('globalform') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs forms.py from django.conf import settings db_name = settings.DATABASES['default']['NAME'] class GlobalLessonForm(forms.ModelForm): class Meta: model = Lesson fields = '__all__' def __init__(self, request, *args, **kwargs): school_id = request.session['school_id'] super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects self.fields['level'].queryset = Level.objects.filter(school__id= school_id) if 'level' in self.data: try: level_id = int(self.data.get('level')) self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')']) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subject'].queryset = self.instance.level.subject_set lesson_form.html <form method="post" id="globallessonform" data-subjects-url="{% url 'ajax_load_subjects' %}" novalidate> {% csrf_token %} <table> {{ form.as_table}} </table> <button type="submit">Save</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_level").change(function () { var url = $("#globallessonform").attr("data-subjects-url"); // get the url of the … -
"Cannot import ASGI_APPLICATION module %r" % path channels problem
I got this error: ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) Here is my routing.py: from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack from django.urls import path from messanger.contacts.consumers import ChatConsumer application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ path('user-notification', ChatConsumer) ] ) ) ) }) When i remove this line of code, runserver work: from messanger.contacts.consumers import ChatConsumer But i don't understand what's wrong with my consumers file in contacts app: from channels.consumer import AsyncConsumer class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", "text": event["text"], }) -
Django compilemessages doesn't work with some uft-8 characters
I'm setting up internationalization in a Django project using i18n. In /landing/locale/es/LC_MESSAGES, I created a po file with phrases and started python manage.py compilemessages, it worked fine, but when starting the server I get this error: File ".../venv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module> from django.contrib.auth.models import User File "...venv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 33, in <module> class Permission(models.Model): File ".../venv/lib/python3.6/site-packages/django/db/models/base.py", line 111, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This occurs only in Spanish, or with the '`' symbol. If you delete the .mo translation file, the server starts normally. I think the problem is the encoding. Is there any way to set UTF-8 encoding for translation files? I use UTF-8 encoding for .po files -
Django: Duplicate in result API storing DB
I hope you're well. I'm using an API. Everything works well. Except one thing. When I try to store my category related to API result I got a duplicate... I've tried to add a .distinct() but that does not work. For each post I got got a duplicate Typerepas. Assume we got a salad (Typerepas: Main courses), If we click on Main courses we'll have two times the same post... I've tried to do it manually with Admin panel. There is no duplicate, so I guess the issue is in the code. class Typerepas(models.Model): name = models.CharField(max_length=20) ... class Post(models.Model): title = models.CharField(max_length=190) typederepas = models.ManyToManyField('Typerepas',blank=True, related_name='typederepas_posts') ... if result_title: response_title_data = result_title.json() try: for dishtypes in response_title_data['results'][0]['dishTypes']: if dishtypes == "main course" or dishtypes == "marinade" or dishtypes == "salad" or dishtypes == "main dish": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Main courses") current_post.typederepas.add(typerepas) elif dishtypes == "soup" or dishtypes == "fingerfood": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Starters") current_post.typederepas.add(typerepas) elif dishtypes == "beverage" or dishtypes == "drink": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Drinks") current_post.typederepas.add(typerepas) elif dishtypes == "side dish": current_post = get_object_or_404(Post, slug=self.slug) typerepas = Typerepas.objects.get(name="Trimmings") current_post.typederepas.add(typerepas) elif dishtypes == "dessert": current_post = get_object_or_404(Post, slug=self.slug) typerepas = … -
Setting a property into request in Django test client
I have a middleware (tenant_schemas.BaseTenantMiddleware) that will inject tenant property into the request object. I can't use that middleware when unit testing. In a view I can then get the tenant object from the request. This view is mapped to the URL "myapp:member_info". class MemberView(TemplateView): template_name = 'myapp/member.html' def get_context_data(self, member_id=None, *args, **kwargs): ctx = super().get_context_data(*args, **kwargs) tenant = self.request.tenant ctx['tenant_name'] = tenant.name return ctx This view works when the project is run normally as the middleware will set request.tenant correctly. Now, if I want to test this view I try to write following test: class MemberViewTest(TestCase): def setUp(self): self.tenant = Tenant(name="test tenant") self.member = Member.objects.create( first_name='Test', last_name='Person') def test_saldo(self): self.client = Client(tenant=self.tenant) # Here I try to inject the tenant into the request print(self.client.defaults) # This will print {'tenant': <Tenant: test tenant>} response = self.client.get(reverse('myapp:member_info', kwargs={ 'tenant': self.tenant, 'member_id': self.member.token })) This test fails to error: File "myapp/views.py", line xxx, in get_context_data tenant = self.request.tenant AttributeError: 'WSGIRequest' object has no attribute 'tenant' So, the django.tests.Client class is not injecting the defaults to the request. One thing I tried is to override the RequestFactory (https://github.com/django/django/blob/ac6c4260074de43a978e5c6553ef89441e1d6748/django/test/client.py#L308) so that it would inject the tenant. class TenantRequestFactory(RequestFactory): def request(self, **request): req = super().request(**request) … -
Why firstname and lastname fields are stored after fail validation which password doesn't
I have a registration form there are have few fields including first name, last name, password and password confirm. I'm wondering why first name and last name value still in the form after the form fail in validation while password field doesn't. What makes those fields behave differently from each other. -
how to test a graphene mutation with **kwargs on mutate function?
I am testing a mutation that creates a user something like this: def test_create_user(self): user_mutation = """ mutation($id: ID!, $group: GroupInput!, $address: AddressInput!){ createUser(id: $id, group: $group, address: $address) { user { id } } } """ group = { 'name': 'GroupA', 'contact': '1231323131' } address = { 'street': '123', 'city': 'Test City' } resp = self.client.execute(user_mutation, variable_values={ 'id': str(uuid.uuid4()), 'group': group, 'address': address }) The Mutation Class: class CreateUser(graphene.Mutation): class Arguments: id = graphene.String(required=True) group = GroupInput(required=True) address = AddressInput(required=True) ...more input here user = graphene.Field(UserType) def mutate(self, info, **kwargs): user = create_user(**kwargs) return CreateUser(user=user) The problem is that when I try to run this test is it return an error: test_create_user {'errors': [{'message': "create_user() got an unexpected keyword argument 'group'", 'locations': [{'line': 4, 'co lumn': 25}], 'path': ['createUser']}], 'data': OrderedDict([('createUser', None)])} I'm not sure how should I go about this and I use kwargs because there is much more input to be added here. Any ideas and suggestions is greatly appreciated! -
The submitted data was not a file. Check the encoding type on the form. This error showing up while submitting image through react hook forms
Hi guys I am getting this error while submitting this form with an image through react hook form. This is the error I am getting from the backend. {image: ["The submitted data was not a file. Check the encoding type on the form."],…} image: ["The submitted data was not a file. Check the encoding type on the form."] 0: "The submitted data was not a file. Check the encoding type on the form." But I am able to make it work without any problems through postman. I am new to react, can anyone help to solve this. I am using django in the backend and django rest framework for api endpoints. form. import React, { useState } from 'react'; import axiosInstance from '../../axios'; import { useForm } from 'react-hook-form'; //MaterialUI import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(9), display: 'flex', flexDirection: 'column', alignItems: 'center', }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, input: { display: "none", … -
only one slug provided but URL is taking two parameters
I am trying to test my application and found out the I provided only one parameter as a slug but the URL is using two. I have added slug in the urls.py and in the HTML form as well. Here is the code example: URLs: urlpatterns = [ ... path('edit/<slug:loanid>/', views.edit, name="edit"), path('edituser/<int:userid>/', views.edituser, name="edituser"), ] Views: def edit(requests, loanid): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent'): loan = Loan.objects.get(loanid=loanid) history = loan.history.all() # print(history) loanstatus = Loan.objects.filter(loanid=loanid).values('loanstatus') if loanstatus[0]['loanstatus'] == 'Approved' or loanstatus[0]['loanstatus'] == 'Rejected': return JsonResponse({"message": "Loan is approved Cannot Edit"}) else: return render(requests, 'edit.html', {'loan': loan, 'history': history}) else: return HttpResponseForbidden() def edituser(requests, userid): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent' or requests.user.userrank.userstatus == 'Admin'): user = User.objects.get(pk=userid) return render(requests, 'edituser.html', {'user': user}) else: return HttpResponseForbidden() Here are the templates and form used to render: <form action="/edituser/{{eachuser.id}}/" method="GET" class="status"> <input type="hidden" value="{{eachuser.id}}" name="loanid"/> <input type="submit" value="Edit" class="btn btn-primary"/> </form> <form action="/edit/{{eachloan.loanid}}/" method="GET" class="status"> <input type="hidden" value="{{eachloan.loanid}}" name="loanid"/> <input type="submit" value="Edit" class="btn btn-primary"/> </form> URLs that are showing in the browser: http://127.0.0.1:8000/edituser/19/?loanid=19 http://127.0.0.1:8000/edit/a38aa1b6-9158-4d71-a725-dc5406184aec/?loanid=a38aa1b6-9158-4d71-a725-dc5406184aec -
How to Keep Django Project Running after Closing terminal?
I have Very Comman issue might looks easy.I have Pushed my Django project on Live Digital Ocean server.I have done all the Configuration using Putty terminal.My project is Working Fine but when i close my Terminal,Project stopped working.I am using Digital Ocean Server.my Question is How to Keep Project Running after closing terminal? i will be Thankful if anyone can Help me with this issue. -
search results are not displayed on the search page in django
I have a search form on the index page and I want to display the result inside the search page when it does a search. I hope help me. urls.py path('search/', views.search, name='results'), veiw.py def get_queryset(self): booksearchlist=Book.objects.all() query = self.request.GET.get('q') object_list = Book.objects.filter( Q(Titel__icontains=query) ) return render(request,'search.html',{'object_list':object_list,'booksearchlist':booksearchlist}) model.py class Book (models.Model): BookID= models.AutoField(primary_key=True) Titel=models.CharField(max_length=150 ) Author=models.ForeignKey('Author',on_delete=models.CASCADE,verbose_name="نام نویسنده") Price= models.IntegerField(null='true',blank='true') Image=models.ImageField(upload_to ='upload/bookimage' ) result.html {% if object_list %} {% for Book in object_list %} <section id="card" class="col-md-6 col-lg-3 col-sm-6 col-xs-12"> <a href=""><img src= {{Book.Image.url}}></a> <h1 id="bookname">{{Book.Titel}}</h1> <p id="price">{{Book.Price}}</p> <p>{{Book.Author}}</p> </section> {% endfor %} {% else %} <p>No search results for this query</p> {% endif %} index.html <form class="searchform "method="GET" action="{% url 'results' %}" value="{{request.GET.q}}" > <input type="search" name="q" class="search-box" value="{{request.GET.q}}" formnovalidate autocomplete="off" placeholder="جست و جوی کتاب، نویسنده، ناشر"> <button type="submit" class="searchbtn" value="search"> <i class="fas fa-2x fa-search"></i> </button> </form> -
Custom sorting on model property django-table2
I use django-table2. Now I want to create custom sorting on property of my model. My models are: class Department(models.Model): Department_TYPE_CHOICES = ( (1, 'branch'), (2, 'unit'), (3, 'center'), ) title = models.CharField(max_length=128) identity = models.IntegerField(choices=global_vars.Department_TYPE_CHOICES) reference = models.ForeignKey('self', on_delete=models.PROTECT,null=True) class Enrollment(models.Model): title = models.CharField(max_length=128) department = models.ForeignKey('department', on_delete=models.PROTECT,null=True) @property def unit(self): department = self.department if department.identity == 2: return department.title elif department.identity == 3: return department.reference.title My table is: class MyTable(tables.Table): unit = tables.Column(order_by=("department")) class Meta: model = Enrollment fields = ("title") sequence = ('unit', "title") All things are good except that I want to sort on unit property. I used order_by on unit property, but sorting didn't done on unit and done on department field. So, How can I define sorting for my property? -
Django & Vuejs Issue while downloading excel file
I tired to download Excel file from Django REST API I created and the Excel file downloaded after opening it gives me the <xlsxwriter.workbook.Workbook object at 0x000001D627EF7A90> object in the first cell. Here's the code for django for generating Excel file: @csrf_exempt def export_to_excel(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Report.xlsx' xlsx_data = WriteToExcel() response.write(xlsx_data) return response Here's the function of creating Excel file: def WriteToExcel(repo_data): workbook = xlsxwriter.Workbook('Expenses01.xlsx') worksheet = workbook.add_worksheet() # Some data we want to write to the worksheet. expenses = ( ['Rent', 1000], ['Gas', 100], ['Food', 300], ['Gym', 50], ) # Start from the first cell. Rows and columns are zero indexed. row = 0 col = 0 for header in headers: worksheet.write(0,col,header) col += 1 workbook.close() return workbook in Vuejs file, here's the axios request I do to download the file: export_to_excel: function () { axios .post(this.$apiServer + "/export_to_excel", { headers: { "Content-Type": "application/vnd.ms-excel", "Access-Control-Allow-Origin": "*", }, }) .then((response) => { var fileURL = window.URL.createObjectURL(new Blob([response.data])); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'Expenses01.xlsx'); document.body.appendChild(fileLink); console.log(response.data); fileLink.click(); }).catch(error => { console.log(error); }) }, What's wrong with this code? -
Apache Process Memory Leaking
I have a Apache server running with Django API and this API is serving only images . There are opencv and dlib libraries are using to crop the image . But when there is a spike in traffic Apache process the requests but memory somehow not released here is graph of memory showing how server memory act during spike and after spike when there is not process running memory utilization is very high enter image description here My distribution is Ubuntu 18 hosted on and ec2 with 2vcpu and 4GB Ram . using below command its says 204 mb but in time of spike it increase to 450MB or more ps -ylC apache2 --sort:rss | awk '{sum+=$8; ++n} END {print "Tot="sum"("n")";print "Avg="sum"/"n"="sum/n/1024"MB"}' Tot=2514524(12) Avg=2514524/12=204.632MB Here are my Apache configurations for keepalive and timeout /etc/apaache2/apach2.conf Timeout 65 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 0 # # …