Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx, Django Static files, Docker, Oh My
First, everything works great in my development system. On my deployment server I'm running Nginx in a docker and gunicorn serving my django app in a second docker. I've configured Nginx to serve up the static files. If I don't copy the contents of my static_cdn folder (of static files) to the Nginx docker, I see this error in the console window, GET http://<my_ip>:1337/static/pb_django/home.css net::ERR_ABORTED 404 (Not Found) and my web page text is left aligned. If I do copy the static files folder into the Nginx docker, I don't get the error message and my text is centered (as instructed by my css). However, if I then change my css, it seems to have no effect on the displayed page. Thoughts or suggestions? Here's my code: Nginx Dockerfile where static_cdn contains my static files FROM nginx:alpine RUN rm -f /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d/default.conf COPY static_cdn /static nginx.conf upstream pb_django { server web:8000 fail_timeout=0; } server { root /; listen 80; location / { proxy_pass http://pb_django/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_read_timeout 10m; proxy_connect_timeout 10m; client_max_body_size 700m; } location /static/ { } } -
To print products ,categories ,subcategories from django database in table form by retrieving it from databse
views.py enter code here from django.shortcuts import render enter code here#from django.template.defaulttags import registerenter code here enter code here#from django.http import RequestContext enter code herefrom django.http import HttpResponseRedirect enter code herefrom django.db import models enter code herefrom django.conf import settings enter code herefrom .models import Category,WebSubCategory,ProductMan,Inherit1 enter code here# Create your views here. enter code heredef home(request): enter code here #context = RequestContext(request) enter code here#category_list = Category.objects.order_by('-name')[:5] enter code here# subcategory_list = WebSubCategory.objects.order_by('-category')[:5] enter code here# product_list = ProductMan.objects.order_by('-subcategory')[:5] enter code here# inherit = Inherit1() enter code here# category_list.save() enter code here#subcategory_list.save() enter code here# product_list.save() enter code herecategory_list = Category.objects.all() enter code heresubcategory_list = WebSubCategory.objects.all() enter code hereproduct_list = ProductMan.objects.all() enter code hereinherited = Inherit1.objects.all() enter code here context_dict = {'webcat': category_list, 'websubcat':subcategory_list,'Product': enter code hereproduct_list,'Inherited' : inherited} enter code here print(context_dict) enter code hereprint(category_list) enter code hereprint(subcategory_list) enter code hereprint(product_list) enter code here# print(inherited) enter code here return render(request,'registration.html', {'dict' :context_dict} ) enter code heremodels.py enter code here from django.conf import settings enter code herefrom django.db import models enter code hereclass Category(models.Model): enter code here name = models.CharField(max_length=50, unique=True,null=True) enter code hereid = models.AutoField(primary_key=True,unique=True ,null =False) enter code here#slug = models.SlugField(verbose_name='Slug') enter code hereclass Meta: enter code … -
Create functional GIN index for FTS in Django with solely Django-orm
I want to create a GIN index for full-text search in Djnago. Is it possible to express something like this in Django ORM? Index on function(expression): CREATE INDEX index_name ON table_name USING GIN (to_tsvector(config_name, field_name)); without custom migrations with RUNSQL and staf... Thank you. P.S. SearchVectorField is not an option as i dont want to deal with triggers. -
How to group_by() column(RID) in Django
How to gourp_by() column based on RID. My Actual output Whatever values are displayed in the Months Names like [Jan, Feb,...., Des], all the values come from the one table column. I want to display all values in one particular column like the below image. Expected output -
django JsonResponce gives json with slaches as a string
I use django for sending some data in json but i get json string with slashes This code class LevelsSerialiser(Serializer): def end_object(self, obj): # self._current has the field data indent = self.options.get("indent") if not self.first: self.stream.write(",") if not indent: self.stream.write(" ") if indent: self.stream.write("\n") data = {} data['id'] = self._value_from_field(obj, obj._meta.pk) data.update(self._current) json.dump(data, self.stream, **self.json_kwargs) self._current = None class LevelsView(MainView): def get(self, request, *args, **kwargs): serializer = vocabulary.customserializers.LevelsSerialiser(); return JsonResponse(serializer.serialize(vocabulary.models.Level.objects.all()), safe=False) gives me this json with slashes as string "[{\"id\": 1, \"name\": \"Upper Intermediate\", \"code\": \"B1\"}]" But i need something like this, [ { "id": 1, "name": "Upper Intermediate", "code": "B2" } ] what i am doing wrong? -
how to pre run rest APIs and store into Redis Cache with Django
I have a dashboard where customers can request forms which runs a REST API. But when they request the form it takes a while (around two minutes) to come back if it's the first time running the request. However, if I create a program/dashboard that pre runs these API calls which preloads the forms into our Redis Cache it would speed up the customer request to around (5 seconds) because we clear our Redis Cache once a week. -
Wrong Rendering in Html?
I am using my website to send emails and the email is an html page... when i view the html page in the browser it looks as follows when i send the email it looks as follows I'll share my html file now.. .product_title { font-size: 20px; text-transform: uppercase; letter-spacing: .2em; padding-top: 15px; padding-bottom: 10px; } .text-center { text-align: center; margin: 0 auto; } .table-bordered th, .table-bordered td { border: 1px solid #dee2e6 !important; } .table { border-collapse: collapse !important; } .text-left { text-align: left !important; } .text-right { text-align: right !important; } .r { float:right; } .text-center { text-align: center !important; } .d { display: inline; } <div class="container"> <span style="float: left;"> <h1 style="color:#003366;">Wiss</h1> <br></span> <span style="float: right;"><h1 style="color:#003366;">Order Customer</h1> <br></span> <br> <table class="table"> <tr> <td class="text-left" colspan="2"> <b>Street: </b>Nii Martey Tsuru St <br> <b>Address: </b>Spintex Road <br> <b>City: </b>Accra <br> <b>Phone: </b>Phone Num <br> <b>Email: </b> Email <br> </td> <td class="text-left r" colspan="2"> <b>Customer: </b> {{ order.customer }} <br> <b>Address: </b>{{ adr.address }} <br> <b>City: </b>{{ adr.city }} <br> <b>zipcode: </b>{{ adr.zipcode }} <br> <b>Phone: </b>{{ order.customer.phone}} <br> <b>Email: </b>{{ order.customer.email}} <br> </td> </tr> </table> <div class="text-center"> <br> <h1 class="product_title"> Order Details </h1> <br> <table class="table table-bordered"> <tr> … -
Django Rest Framework simple Endpoint to receive json without Serializer and Model
I'm pretty new to django and trying to create a simple Post-Endpoint for receive the raw Json from body and response with an own json string. My structure looks like following : I have already seen some snippets here in SO so I know its possible. But I miss the steps how to do and where to do. I would like to do : Add new controller in pfc App that listen for request Define the Endpoint Wire up an routing for this controller Everything i could found is always to do with serializers and models. But I need only the Bodys JSON. -
How to get results of only the primary key and not all results in django-rest-framework?
In my django app, i need to check if a user exists using a phone number. The login is done using phone number and OTP. I can check if the user exists by a get request to "/api/profiles/<primary key here>/". However if I request "/api/profiles/" i get a list of all the users in the database. I need my app to return nothing if requesting "/api/profiles/" and user details if requesting "/api/profiles/<primary key here>/" How do I do this? -
Pre-populate Django form with CreateView using reverse relationship
I've searched the forums and various other places and can't really find what I'm looking for. I have five models: Hydrant, Meter, AssetType, WorkOrderActivity and Workorder. # models.py class Hydrant(models.Model): uniqueId = GISModel.CharField(max_length=100) geom = GISModel.PointField() def__str__(self): return self.uniqueId class Meter(models.Model): uniqueId = GISModel.CharField(max_length=100) geom = GISModel.PointField() def__str__(self): return self.uniqueId class AssetType(models.Model): typeChoices = ( ('Hydrant', 'Hydrant'), ('Meter', 'Meter'), etc... ) name = models.CharField('Asset Type',max_length=30,choices=typeChoices) def __str__(self): return self.name class WorkOrderActivity(models.Model): assetType = models.ForeignKey( 'AssetType', related_name='workorderactivities', on_delete=models.SET_NULL, blank=True, null=True ) activityChoices = ( ('Paint Hydrant', 'Paint Hydrant'), ('Flush Hydrant', 'Flush Hydrant'), ('Read Meter', 'Read Meter'), etc... ) activityType = models.CharField('Activity Type', choices=activityChoices ,max_length=50) def __str__(self): return self.activityType class Workorder(models.Model): assetType = models.ForeignKey(AssetType, related_name='typeOfAsset', on_delete=models.SET_NULL) woActivity = models.ForeignKey(WorkOrderActivity, on_delete=models.SET_NULL) hydrant = models.ForeignKey(Hydrant, related_name='workorders', on_delete=models.SET_NULL) meter = models.ForeignKey(Meter, related_name='workorders', on_delete=models.SET_NULL) description = models.TextField('Description', max_length=250, blank=True, null=True) def __str__(self): return self.description What I'm trying to do is from a leaflet map where I see all of my assets (Hydrants and Meters), click on an asset to see the popup information where I have a button to 'Create Workorder'. In my normal 'create_workorder' view, where the user would not be creating the workorder from the map, all of my dropdowns are chained, meaning based … -
Decode uft8 in html (template) [closed]
I have a problem I get a queryset of Items by: ingredients = Zutaten.objects.filter(rezept=rezept_id) And inside my context: "ingredients_queryset" : ingredients, And I use it in HTML like this: {% for i in ingredients_queryset %} <li>{{i.zutat}}</li> {% endfor %} But now I have the problem that inside of the queryset strings are which are encoded with utf8 and now I need to decode them. I'm not sure how I can do it. So I hope you can help me. Thank you! -
How to show javascript alert via Django
I want to show alert after the user successfully logs in and call some other javascript function. -
How to render table from from csv file into django templates?
I have a problem with rendering table in django templates with data form csv file. I'm reading data from file: with open('data/file.csv', encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) and rendering the template: return render(request, 'search/search.html', {'data': reader}) and in the template: <table> <thead> <tr> <th>...</th> </tr> </thead> <tbody> <tr> {% for row in data %} <td>{{row}}</td> {% endfor %} </tr> </tbody> and I have error operation on closed file Firstly I thought about using pandas but in Django it gave me circular import :/ Could anyone let me know how can I fix it? -
Running multiple threading process in background using django / python parallel or async to each other
I'm currently building a modbus data scrapper tool in which i want it to get data from device continuously and parallel to each other. Here's the example code that i'm working with def get_data(self): connection_port = len(connection_ports) connection_count = 0 while connection_count != connection_port: timestamp = datetime.datetime.now() print('Timestamp: ', timestamp) client = ModbusTcpClient(connection_ports[connection_count][0], port=connection_ports[connection_count][1]) # Specify the port. connection = client.connect() count = 0 data_info = [] data_object = [] limit = len(registers) loop = 0 if connection: while loop < limit: if count == limit - 1: break address = registers[count] response = client.read_holding_registers(address, count=10, unit=connection_ports[connection_count][2]) try: register_value = response.registers[0] bin8 = lambda x: ''.join(reversed([str((x >> i) & 1) for i in range(12)])) modbus_value = register_value / scaling[count] timestamp = datetime.datetime.now() if count == limit: count = 0 else: count = count + 1 data_object.append(registers[count]) data_info.append(round(modbus_value, 2)) csv_name = str(connection_ports[connection_count][0]) + "-Slave-" + str( connection_ports[connection_count][2]) + ".csv" with open(csv_name, 'a+', newline='') as f: driver_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) driver_writer.writerow([label[count], str(address), round(modbus_value, 2), timestamp]) except Exception: print("Unable to Get Data from Device, Please Check Device Connection") exit # self.writeGui(data_object, data_info) else: print('unable to connect to device') connection_count = connection_count + 1 client.close() What i'm currently doing in this code … -
Fetch and return one field from database using django_restframework
So I have been trying to make an API with Django rest_framework that will return only 1 field from a table. I have been trying to follow the example from Django Rest Framework: Dynamically return subset of fields, but have been unable to recreate it. whenever I write "http://localhost:8000/api/students/fields=id/", I get a 404 error with "details": "not found" I have also been experimenting with adding an extra method in the view class, like in this example: @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('created_at').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) with something like "get_id_list" instead, but I haven't quite figured it out. Also, does anyone know if these methods will first retrieve all fields from the database, and then filter out what it needs, or will the query adjust to only ask for the specified fields? The tables can get quite large, so it might save a lot of time if it doesn't fetch unnecessary data. Here is the code in serializer.py from rest_framework.serializers import ModelSerializer from .models import Student, Coverage class DynamicFieldsModelSerializer(ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up … -
python django Mock SAML Response from onelogin.saml.auth library using python3-saml
I have implemented for our django back-end application (SP) possibility to login via SAML, as IDP im using Keycloak. It works fine, but I want to write tests to be sure that all logic is being executed correctly. For this I want to generate a post request with SAML as body and mock (unittest.mock.patch) the real request. But i stuck. Here is my django view, which accepts get and post requests when I try to login via SAML: class SamlLoginView(View): @staticmethod def prepare_django_request(request): if 'HTTP_X_FORWARDED_FOR' in request.META: server_port = 443 else: server_port = request.META.get('SERVER_PORT') result = { 'https': 'on' if request.is_secure() else 'off', 'http_host': request.META['HTTP_HOST'], 'script_name': request.META['PATH_INFO'], 'server_port': server_port, 'get_data': request.GET.copy(), 'post_data': request.POST.copy(), } return result @never_cache def get(self, *args, **kwargs): req = SamlLoginView.prepare_django_request(self.request) auth = OneLogin_Saml2_Auth(req, settings.SAML_IDP_SETTINGS) return_url = self.request.GET.get('next') or settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(auth.login(return_to=return_url)) @never_cache def post(self, *args, **kwargs): req = SamlLoginView.prepare_django_request(self.request) print(req['post_data']['SAMLResponse']) auth = OneLogin_Saml2_Auth(req, settings.SAML_IDP_SETTINGS) auth.process_response() errors = auth.get_errors() if not errors: if auth.is_authenticated(): logger.info("Login", extra={'action': 'login', 'userid': auth.get_nameid()}) user = authenticate(request=self.request, saml_authentication=auth) login(self.request, user) return HttpResponseRedirect("/") else: raise PermissionDenied() else: return HttpResponseBadRequest("Error when processing SAML Response: %s" % (', '.join(errors))) In my tests, I wanted to directly call the post method, in which there will be … -
IntegrityError at /new_food/(?P6\d+)/ : NOT NULL constraint failed: food_entry.refer_id
views.py : def new_entry(request, food_id): food=Food.objects.get(id=food_id) if request.method != 'POST': form=EntryForm() else: form=EntryForm(data=request.POST) if form.is_valid(): new_entry=form.save(commit=False) new_entry.food=food new_entry.save() return HttpResponseRedirect(reverse('food',args=[food_id])) context={'food':food,'form':form} return render(request,'new_entry.html',context) forms.py : from django import forms from .models import Food , Entry class FoodForm(forms.ModelForm): class Meta: model= Food fields= ['name'] labels= {'text':''} class EntryForm(forms.ModelForm): class Meta: model=Entry fields=['item'] labels={'text':''} models.py from django.db import models # Create your models here. class Food(models.Model): name=models.CharField(max_length=200) type=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Entry(models.Model): refer=models.ForeignKey(Food,on_delete=models.CASCADE) item=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural='entries' def __str__(self): return self.item[:50] Even after going through a lot of similar posts , I'm not being able to figure to out where is it going wrong , may be something is wrong in views.py but even after spending hours I'm not able to figure it out. Any help would be much appreciated . -
while deploying project getting error : cannot stat '/tmp/build_d2196d1a_/requirements.txt': No such file or directory?
I'm using python django with pipenv environment project hierarchy structure I have created a project, i pushed it to github successfully. When i deploy it to heroku the build completed successfully but while building it shows ----> Requirements file has been changed, clearing cached dependencies cp: cannot stat '/tmp/build_d2196d1a_/requirements.txt': No such file or directory heroku build log because of which i think packages are also not installed listed in requrements.txt and i'm getting application error while viewing application how can i solve this? -
Django cookie banner / consent
regarding cookies in django, is there any solution for the banner/consent, is there someone who can help me with the code or report me a secure package? thanks in advance thanks in advance -
Social network models architecture
I want to create the social network that should work as Reddit, but idk how to implement one thing. I did Communities model(subreddits) and also did Posts model. And it works fine, but i want to add the feature that will let you to create posts not only for one of the communities, but also for your profile, I mean that Here is my models models.py class Community(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, null=True, blank=True) description = models.TextField(max_length=500) cover = models.ImageField(upload_to='c_covers/', blank=True, null=True) admins = models.ManyToManyField(User, related_name='inspected_c') subscribers = models.ManyToManyField(User, related_name='subscribed_c') banned_users = models.ManyToManyField(User, related_name='forbidden_c') created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, null=True, blank=True) body = models.TextField(max_length=5000, blank=True, null=True) photo = models.ImageField(upload_to='post_photos/', verbose_name=u"Add image (optional)", blank=True, null=True) author = models.ForeignKey(User, related_name='posted_p', on_delete=models.CASCADE) community = models.ForeignKey(Community, related_name='submitted_p', on_delete=models.CASCADE) points = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liked_p', blank=True) mentioned = models.ManyToManyField(User, related_name='m_in_posts', blank=True) rank_score = models.FloatField(default=0.0) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) -
Reverse for 'vote' with arguments '('', '')' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
I've been working with Django doc and ther is this code which works: <body> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> <--------- {% for choice in question.choice_set.all %} <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"><br> {% endfor %} <input type="submit" value="Vote"> </form> </body> Django code: class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) Now, i am trying to make this code working in DRF, but it gives me an error. Here i found the code Here is code of drf: class DetailViewDRF(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'polls/detail.html' def get(self,request, pk): queryset = get_detail_queryset() return Response({'question': queryset}) Am i missing something vital in documentation? P.S. Why it suggests me to make get method static? -
Django Rest Framework Testing - OrderedDict instead of a number Error
So, I'm building an API with Django and rest-framework and when I try to send a post test request it keep getting this error where it's expecting a number but got a OrderedDict, if someone could help me it would be great. test_api.py def setUp(self): self.client = APIClient() self.sensor = Sensor(54545) self.sensor.save() self.company = Company(name='MOCK') self.company.save() def test_create_valid_user_success(self): """Test creating a user with valid payload is successful""" payload = { 'email': 'test@gmail.com', 'password': 'pass123', 'name': 'Test', 'registration': 144545, 'sensor': { 'id': 455465, 'battery': 100 }, 'company': self.company.id } res = self.client.post(CREATE_USER_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) self.assertNotIn('id', res.data) *already tried json.dumps(payload), content_type='application/json' for the post serializers.py class SensorSerializer(serializers.ModelSerializer): class Meta: model = Sensor fields = ('id', 'battery',) class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" sensor = SensorSerializer() class Meta: model = get_user_model() fields = ( 'email', 'password', 'name', 'registration', 'sensor', 'company', ) extra_kwargs = { 'password': {'write_only': True, 'min_length': 5}, 'id': {'write_only': True} } def create(self, validated_data): """Create a new user with encrypt password and return it""" sensor_data = validated_data.pop('sensor') sensor = SensorSerializer.create(SensorSerializer(), validated_data=sensor_data) return get_user_model().objects.create_user(sensor=sensor, **validated_data) views.py class CreateUserView(generics.CreateAPIView): """Create a new user in the system view""" serializer_class = UserSerializer Error: TypeError: Field 'id' … -
Slow Serializion process Django rest framework
Im using django_rest_framework for my project and i have a problem. models.py: from django.db import models class RelatedField3_2(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class RelatedField3(models.Model): name = models.CharField(max_length=100) relfield3_2 = models.ForeignKey(RelatedField3_2, on_delete=models.CASCADE) def __str__(self): return self.name class RelatedField2(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class RelatedField1(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class MainTable(models.Model): owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) field1 = models.IntegerField() field2 = models.IntegerField() field3 = models.IntegerField() field4 = models.DecimalField(max_digits=10, decimal_places=1) field5 = models.IntegerField(null=True) field6 = models.IntegerField() relfield1 = models.ForeignKey(RelatedField1, on_delete=models.CASCADE) relfield2 = models.ForeignKey(RelatedField2, on_delete=models.CASCADE) relfield3 = models.ForeignKey(RelatedField3, on_delete=models.CASCADE) serializers.py: from rest_framework import serializers from main.models import MainTable, RelatedField1, RelatedField2, RelatedField3 class MainTableRelatedFields(serializers.RelatedField): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): return self.queryset.model.objects.get(name=data) class MainTableSerializerList(serializers.ListSerializer): def create(self, validated_data): records = [MainTable(**item) for item in validated_data] return self.child.Meta.model.objects.bulk_create(records) class MainTableSerializer(serializers.ModelSerializer): class Meta: model = MainTable list_serializer_class = MainTableSerializerList id = serializers.IntegerField(write_only=False, required=False) owner = serializers.ReadOnlyField(source='owner.username') relfield3 = PartnerPropRelatedFields(queryset=RelatedField3.objects.all()) relfield2 = PartnerPropRelatedFields(queryset=RelatedField2.objects.all()) relfield1 = PartnerPropRelatedFields(queryset=RelatedField1.objects.all()) def create(self, validated_data): return self.Meta.model.objects.create(**validated_data) views.py: from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .serializers import MainTableSerializer class MainTableUploadView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) @action(['post'], detail=False) def upload_records(self, request, *args, **kwargs): … -
Django + Apache + Windows Server 2016, mod_wsgi unable to run wsgi.py file
I am trying to deploy a django project on a windows machine using Apache 24. Apache works. But the log file shows that mod_Wsgi is stuck while reading the wsgi.py file without throwing any error: Here is the last entry in my log file: [Thu Sep 03 14:13:33.708094 2020] [wsgi:info] [pid 17684:tid 908] [client ::1:53338] mod_wsgi (pid=17684, process='', application='l'): Loading Python script file 'C:/.../wsgi.py'. And the webpage keeps loading till infinity. Following is what I am using in my httpd.conf file: LoadFile "c:/python37/python37.dll" LoadModule wsgi_module "c:/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIScriptAlias / "C:/...../wsgi.py" <Directory "C:/...../"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/.../static/" <Directory "C:/..../static/"> Require all granted </Directory> No changes in the httpd-vhost.conf file. I am frustrated with the issue and have tried a lot of tweaks, but the webpage just wont load. Also, my Apache Debug level is 'debug'. What am I missing? -
Django - Use foreign keys as choices for choice-field
Suppose I have the following models (Does not really matter, any model whatsoever will do) class Model0(models.Model): pass class Model1(models.Model): pass How can I pass them as choices to another Model, something like this: class Model3(models.Model): CHOICES = [ (models.ForeignKey(Model0,related_name='model_0',on_delete=models.CASCADE),'model0'), (models.ForeignKey(comment,related_name='model_1',on_delete=models.CASCADE),'model1'), ] choice_collumn = models.ForeignKey(choices=REPORT_TYPES) #it actually has a choices keyword argument The idea is that it will either have a Foreign key relationship to Model 0 or to Model 1. The way I am dealing with this is by setting one of them to null model_0_relationship = models.ForeignKey(Model0,null=True) model_1_relationship = models.ForeignKey(Model1,null=True) But what if I have way more than 2? is there a better solution?