Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Inline indirect
i have an app caso and it has an inline from casov, this is possible because casov has a fk from caso, but now i have aggressor that has a fk to casov so it is indirectly connected to caso, i need to make an inline in caso, help please. hola, tengo una app caso y esta tiene un inline de casov, esto se puede por que casov tiene una fk de caso, pero ahora tengo agresor que tiene una fk hacia casov por lo cual esta indirectamente conectado a caso, requiero hacer un inlines en caso, ayuda por favor. -
Adding historical field value in Django queryset using django-simple-history and django-queryable-properties
So some quick background: I'm trying to build a queryset to link to admin panels and incorporate it across the full application stack. It would help me provide my end-users with the information they need on-demand while reducing the need for me to create and share reports manually. I'm try to accomplish the following: from queryable_properties.properties import queryableproperty from simple_history.models import HistoricalModel from datetime import date, timedelta from django.db import models class DataReport(models.Model): history = HistoricalRecord() formatted_date = models.DateTimeField(verbose_name="FormattedDate") date = models.CharField(verbose_name="Date", max_length=255, null=True) report_title= models.CharField(verbose_name="Report Title", max_length=255, null=True) severity_score = models.IntegerField(blank=True, null=True) @queryableproperty def get_prev_score(self): exclude_filters = { "severity_score__isnull": True, "date__lte": date.today() - timedelta(30) } hist_qs = self.history.exclude(**exclude_filters) prev_score = hist_qs.order_by('date').first() return prev_score.severity_score if prev_score else return None from here I would ideally run DateReport.objects.filter(severity_score__gt=F('get_prev_score') but this would not work since it would require annotation and you can't annotate without explicitly referencing a data field via F objects, and you can't use HistoricalRecord with F objects. I've tried using subqueries but can only get null values returned when annotating. Any ideas, hivemind? -
Sort results by a part of a fields' string in django
I have such Django models: class SavedVariant(models.Model): family = models.ForeignKey('Family', on_delete=models.CASCADE) class Family(models.Model): family_id = models.CharField(db_index=True, max_length=100) family_id is of such a pattern: CCNNNNNN_CCC_CCCC where C is a character and N is an integer, e.g. SF0637658_WGS_HGSC. I want to order (django order_by?) my SavedVariant models first by preceding chars - CC - then by the number - NNNNNN - and finally by the last chars. Is it possible to do in Django? What would you recommend? -
Is there a way to save each value several times? Please help me
great developers. I'm a student learning Django. I am implementing the product registration part, and I want to register after receiving the price twice in the designated part of the model. One is the price of the product itself, and the other is the product option cost added. The problem is that when I checked with admin, the price is two fields, so it's not stored one by one, but only one with one price. I would like to be registered with two pieces of information, one with the price of the product and one with the price of the option. How can I solve this part? In addition to this issue, if there is an option called 'color', you should specify an option value such as 'red' and 'blue' that corresponds to 'color' and save only one option value that corresponds to 'option'. How can I save this problem? Great developers, please reply. In short, for example, ex) Price 1, if you have Price 2, you have 1 information that is different from Price 1, and you have 1 information that is different from Price 2, and you have 1 information that is different from Price 2. Model.py # … -
Notification when a certain point in time is exceeded (Python)
I would like to create a To-Do list in which I can schedule date and time of each task. My goal is to get some sort of response whenever the supplied datetime is equal to the current time. For example I scheduled Do laundry for Monday at 6pm on a Saturday evening. Two days later (on Monday at 6pm) I would like to get a notification that I should Do laundry. Notice that the key idea can be found in the index() function in views.py in the first rows including the if-statement. Here is my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details"), path("add/", views.add, name="add"), path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"), path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"), path("update/<int:aufgabenzettel_id>", views.update, name="update") ] models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) Datum = models.DateTimeField(auto_now_add=True) Geplant = models.DateTimeField(auto_now_add=False, auto_now=False) def __str__(self): return f"{self.Aufgabeselbst}" views.py (the important part can be found in the index function in the first rows including the if-statement) from django.db.models.fields import DateTimeField from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.utils import timezone from datetime import datetime from .models import Aufgabenzettel # … -
How many foreign keys can a table have in postgreSQL?
I am working on a Django project with a database in PostgreSQL. During my schema design, I have noticed that one table is referencing many foreign keys from other tables. Just curious that how many foreign keys can be referenced from/to one table? I also searched and found that the SQL server 2014 can reference up to253 foreign keys. -
in django ecommerce project, the question is I can't display category and sub category in template html
how can display category and sub category in product template what is missing in bellow code this is a part of View.py according product view, shows filtering category and subcategory from model.py class ProductView(View): def get(self,request,*args,**kwargs): categories=Categories.objects.filter(is_active=1) categories_list=[] for category in categories: sub_category=SubCategories.objects.filter(is_active=1,category_id=category.id) categories_list.append({"category":category,"sub_category":sub_category}) merchant_users=MerchantUser.objects.filter(auth_user_id__is_active=True) return render(request,"admin_templates/product_create.html",{"categories":categories_list,"merchant_users":merchant_users}) this is part of model.py according model after migrate, class Products(models.Model): id=models.AutoField(primary_key=True) url_slug=models.CharField(max_length=255) subcategories_id=models.ForeignKey(SubCategories,on_delete=models.CASCADE) product_name=models.CharField(max_length=255) brand=models.CharField(max_length=255, default="") product_max_price=models.CharField(max_length=255) product_discount_price=models.CharField(max_length=255) product_description=models.TextField() productTemplate.html <div class="col-lg-6"> <label>Category</label> <select name="sub_category" class="form-control"> {% for category in categories %} <optgroup label={{ category.category.title }}> {% for sub_cat in category.sub_category %} <option value="{{ sub_cat.id }}">{{ sub_cat.title }}</option> {% endfor %} </optgroup> {% endfor %} </select> </div> -
Can we use longest common subsequene algorithm(LCS) for searches?
LCS in searches? Websites like olx which has search bar to search item for buyer.So,like that if i want build some application which is similar to olx.Can i use LCS for searching any item?if no,what else can you all suggest? -
Weaseyprint, Cairo, Dajngo on Pythonanywhere 25MAY21 can not pass a warning
Sorry I know there seems to be a lot about this topic. But I do not see a real resolution? I am trying to place a Django ecommerce pizza shop for learning Django on the website. Locally this works great no issues. I matched my environment locally to that on the ENV for the server. I got this issue resolved locally when I updated Cairo on my computer. So the emulated server works great. Python 3.8.0 Server Pythonanywhere Here is the error and follow on info. Error from error log on ther server. 2021-05-28 16:13:41,156: /home/williamc1jones/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/weasyprint/document.py:35: UserWarning: There are known rendering problems and missing features with cairo < 1.15.4. WeasyPrint may work with older versions, but please read the note about the needed cairo version on the "Install" page of the documentation before reporting bugs. http://weasyprint.readthedocs.io/en/latest/install.html views.py file in order app import weasyprint from django.urls import reverse from django.shortcuts import render, redirect from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import get_object_or_404 from django.conf import settings from django.http import HttpResponse from django.template.loader import render_to_string from cart.cart import Cart from .models import OrderItem, Order from .forms import OrderCreateForm from .tasks import order_created def order_create(request): cart = Cart(request) if request.method == 'POST': form = … -
I'm trying to get my data from database in React-Native app
If I put .then(data =>{console.log(data)}), I can see the data but is not displayed in my app. What should I do? Thanks function Home(props) { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const loadData = () => { fetch(url, { method: "GET" }) .then(resp => resp.json()) .then(data => { setData(data) setLoading(false) }) .catch(error => Alert.alert('error', error.message)) }; useEffect(() => { loadData(); }, []) {/* return ( <View style={styles.homeText}> <FlatList data={data} renderItem={({ item }) => { return renderData(item) }} onRefresh={() => loadData()} refreshing={loading} keyExtractor={item => `${item.id}`} /> )} My model in Django view is: view.py class MeasurementsViewSets(viewsets.ModelViewSet): queryset = Measurements.objects.all() serializer_class = MeasurementsSerializer My urls.py is: router = DefaultRouter() router.register('measurements', MeasurementsViewSets) #router.register(r'measurements', views.MeasurementsViewSets) // this doesn't work either In Django I get: "GET /api/measurements/ HTTP/1.1" 200 -
ckeditor upload image option not showing up in django
I know this question has been asked many times and I have tried to apply the solutions. Still, the image upload option won't show up and allow me to upload an image in my post. Please help on how to fix this here are the files: settings.py INSTALLED_APPS = [ 'jobs_app', 'django_extensions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from django.conf.urls import include from . import views urlpatterns = [ path('', views.home, name="home"), path('login/', views.user_login, name="login"), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to close a css stylesheet?
I am working on a project which uses multiple templates. This means I have to load multiple stylesheets in my project. A lot of them are copied from the internet. Some of these css stylesheets have overlapping styling like more than 1 sheets will contain styling for a p or a body tag. And if I load one css sheet I only want it to work on a part of website and then close itself. However I cant find a way to close a stylesheet. -
Django migration is creating extra table
I am beginner for Django and i am working on my final year project but i am stuck at one thing. here is my model.py class MatchList(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user") matches = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="matches") class Meta: app_label = "matchsystem" Also my here is my migration file as well. class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='MatchRequest', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_active', models.BooleanField(default=True)), ('times_tamp', models.DateTimeField(auto_now_add=True)), ('receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='receiver', to=settings.AUTH_USER_MODEL)), ('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='MatchList', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('matches', models.ManyToManyField(blank=True, related_name='matches', to=settings.AUTH_USER_MODEL)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)), ], ), ] but when i migrate the data it create an extra table with added name. I want the first table but it doesnt have the correct columns Any response is much appricated. -
Django Template Language Shows Up In Webpage
My Django template language tags are showing up when the webpage is run on the test server. Does anyone know why that may be happening? (Everything else on the webpage is displaying properly, and the tags are even doing their jobs. I just don't know why the text is there. The page's html: <% extends "base.html" %> <% block page_title %> Challenges <% endblock %> <% block content %> <ul> {% for month in months%} <li> <a href="{% url 'month-challenge' month %}">{{month|title}} </a></li> {% endfor %} </ul> <% endblock %> The template that the page is inheriting from: <!DOCTYPE html> <html lang="en"> <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"> <title>{% block page_title %} {% endblock %}</title> </head> <body> {% block content %} {% endblock %} </body> </html> What the output looks like: I've looked at similar posts on here and none of those fixes seemed to apply here (opening the html doc directly, Leaving a space between the { and %, etc. -
Unable to authenticate using factory-boy Django
I'm quite new to factory-boy and I'm trying to send a request to an API endpoint in my unit test, which requires a user to be authenticated. I've looked at a few examples online and this is what I've come up with so far in my unit test: test_user.py class UserFactory(factory.Factory): class Meta: model = user username = factory.LazyAttribute(lambda t: "myuser") password = factory.PostGenerationMethodCall('set_password', 'my_super_secret') is_staff = True is_active = True class UserViewSetTest(TestCase): def setUp(self): pwd = 'my_super_secret' self.user = UserFactory(password=pwd) self.client = Client() self.assertTrue(self.client.login(username=self.user.username, password=pwd)) def test_user_list(self): response = self.client.get(reverse('user', kwargs={'fromdate': '2017-01-01', 'todate': '2017-04-01'})), format='json') self.assertEqual(response.status_code, 200) The initial error is the fact that this assertion self.assertTrue(self.client.login(username=self.user.username, password=pwd)) is false so the test fails right away. Even if I remove that line, the API call returns a 401 because the authentication isn't successful. How can I successfully authenticate a user in this API call with factory-boy? -
Use existing django users with Auth0
I'm trying to connect Auth0 with django, but I want to use the users that already exists in the system. I want them to sync by their email, but Auth0 creates new users. I used the Auth0 documentation to do so. https://auth0.com/docs/quickstart/webapp/django/01-login -
in python django if else not working either showing both or only the first field is showing
I am working in Django python and written these two statements to check if email or username exists in database or not but the message is coming from both email is taken and username is taken but I want it should show it seperately if enter any one if I give input in my sign up form if User.objects.filter(email=email).exists(): # error_message = '' email_error = ('', 'Email is taken. ')[User.objects.filter(email=email).exists()] messages.success(request, email_error) elif User.objects.filter(username=username).exists(): username_error = ('', 'Username is taken. ')[User.objects.filter(username=username).exists()] messages.success(request, username_error) return redirect('/register/') -
There is a link in django but not found in heroku
i have a link to admin in urls.py. i have tried to change and re deploy in heroku but it's always seems like that. but when i try in another project with same code it will running urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('api.urls')), path(r'admin/', admin.site.urls), ] but when i deploy in heroku, it says [1]: https://i.stack.imgur.com/pMllj.png this is my code in setting.py setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-ce0poynbkw!0s^-=1u783+utj^s$%f66@*cew&@oc==epcrdl#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['project-2-anisa.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'api' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'api.wsgi.application' # Database # … -
Redirecting error in Python Django while using NEXT parameter
website used to redirect as www.example.com/login/?next=/ but now its redirecting as www.example.com/login/?next=/login/ didn't make any changes in the code but now the problem has been created as throwing ERR_TOO_MANY_REDIRECTS, redirected too many times. as I was using NEXT parameter I tried changing to **@login_required(/login) to @login_required** , but changes are not reflecting, couldn't understand why, its throwing "GET /login/?next=/login/ HTTP/1.1" 302 0 have used django.contrib.auth hope someone could help, thanks in advance -
Celery doesn`t start task python django
My application doesn`t call celery task my settings.py: CLICKHOUSE_HOST = '127.0.0.1' CLICKHOUSE_PORT = '6379' CELERY_BROKER_URL = 'redis://' + CLICKHOUSE_HOST + ':' + CLICKHOUSE_PORT + '/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60} CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = "Australia/Tasmania" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' Here is init.py in referal_app directory: from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app',) Here is my view that must call celery task: class DefineView(View): def get(self, request): create_points.delay(1, 2) return render(request, 'main/homepage.html', {}) Here is my task (just test for working): from celery import shared_task from referal_app.celery import app @shared_task def create_points(a, b): with open('e:\\txt.txt', 'w') as file: for _ in range(1): file.write(f'{a + b}') return 1 Here is celery settings in referal_app directory: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'referal_app.settings') app = Celery('referal_app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') -
How to send data from python client to Django web server?
I'd like python3 program to send JSON data to Django web server and print them on web page. This is what I have in Views.py: def receive_json(request): if request.method == 'POST': received_data = json.loads(request.body.decode("utf-8")) return StreamingHttpResponse('it was post request: ' + str(received_data)) return StreamingHttpResponse('it was get request') And the python code: import requests import json url = "http://127.0.0.1:8000/" data = {"data": [{'key1':'val1'}, {'key2':'val2'}]} headers = {'content-type':'application/json'} r = requests.post(url, data=json.dumps(data), headers=headers) r.text However, it shows this message: Forbidden (CSRF cookie not set.): / [28/May/2021 16:51:31] "POST / HTTP/1.1" 403 2864 -
Pending request on Django
I'm building a website using Django. I have the register and login sessions working, so any user can create an account and login. But now I want a situation whereby when someone creates an account, the account will be inactive and pending until the admin accepts the user. However, I haven't implemented any code that does that before and I want to know if Django has a built-in package for that. If not, how do I go about it? -
Django stop restarting the server if change in html
I created a website using django, in the webpage I linked a refresh button, when a user clicks the refresh button, it runs python script and update the static html page. But what happening is, the django server restarts after each change in the html and that leads to user unable to access during that particular time, because the service is down at that particular time. Could someone please tell me, how can I disable restarting the django if any change in html. I'm starting django server as follows. python manage.py runserver -
How to upload file to s3 bucket with django rest framework api
I am trying to upload a file to AWS bucket in Django project @api_view(['POST']) def upload_image(request): image = request.FILES['image'] file_name = request.POST.get('file_name') access_key = settings.AWS_ACCESS_KEY_ID access_secret_key = settings.AWS_SECRET_ACCESS_KEY bucket_name = settings.AWS_STORAGE_BUCKET_NAME # bucket_name value is "https://s3.region.amazonaws.com/bucket_name/sub_bucket_name/" # I am not sure if it is correct way to give bucket name where I want my file to be uploaded client_s3 = boto3.client( 's3', aws_access_key_id = access_key, aws_secret_access_key= access_secret_key ) client_s3.upload_file( file_name, bucket_name, image ) url = f'{end_point}{bucket_name}/{file_name}' return Response({'success': True, 'message': "File has been uploaded", 'url': url }, status=status.HTTP_200_OK) and this is how I am passing the file and file name to the api through the postman. The error that I am getting is - "FileNotFoundError: [Errno 2] No such file or directory: "name of file"" I have read the tutorial, It is fairly simple to uploading a file to s3 bucket with boto3. some how I am able to upload the file. -
Django Rest Framework - Delete API CORS error in production mode (OVH web cloud)
I know this is a classic issue but I did not find a solution for my particular case. All APIs work fine, while the DELETE API fails with CORS error. This happens only in production environment (OVH web cloud) This is my python backend code: class UserDetail(APIView): permission_classes = (IsAuthenticated,) def get_object(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: raise Http404 def get(self, request, pk, format=None): userSet = User.objects.filter(id=pk) serializer = UserSerializer(userSet, many=True) return Response(serializer.data) def post(self, request, pk, format=None): userSet = self.get_object(pk) serializer = UserUpdateSerializer(userSet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): user = self.get_object(pk) user.delete() return Response({'deleted user': pk}, status=status.HTTP_204_NO_CONTENT) This is the .htaccess file put in django root folder: If needed, I also share the response header content as displayed by the browser :