Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to save image to databse using modelForm django?
models.py class Organization(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) logo = models.ImageField(null=True, upload_to='media', default='avatar.png') forms.py class OrganizationForm(forms.ModelForm): logo = forms.ImageField( widget=forms.FileInput, label='Company Logo', required=False) class Meta: model = Organization exclude = ['user'] views.py def addorganization(request): if request.method == "POST": fm = OrganizationForm(request.POST,request.FILES, label_suffix='', auto_id=True) if fm.is_valid(): org = fm.save(commit=False) org.user = request.user org.save() return redirect('organization') else: fm = OrganizationForm(label_suffix='', auto_id=True) return render(request, 'crm/manageorganization.html', {'form': fm}) I am not able to upload images to MEDIA_ROOT programatically.But if i upload through admin it gets uploaded -
RichTextField doesn't load in the website
I try to use RichTextField to import image into my content. The admin site is ok but when I open it the website, it onlys load like this. I had import it from ckeditor.fields, and also inside "INSTALLED_APPS". Please help me, thanks guysenter image description hereenter image description here -
IntegrityError at /admin/main/post/add/ NOT NULL constraint failed: main_post.status
How fix this? This after when i create new post #models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model):enter code here title = models.CharField(max_length=200) slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now= True) def __str__(self): return self.title #admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',), } admin.site.register(Post,PostAdmin) -
How can i load Vue components with Django using Webpack-Loader?
I'm just getting started to Vue and i decided to add it to my Django project using the Webpack-Loader approach, in order to get the best of Django and Vue both. When i'm developing, i run two development servers: one for django using manage.py runserver, and another one for vue using npm run serve. Now i'm trying to deploy a very simple Django+Vue application that i found on Github, to see how does that work on production, but i'm having some problems: I cloned and deployed this code on Digital Ocean using Nginx+Gunicorn. Everything works on the Django side but i can't see the Vue components loading, i can only see the standard Django templates. Why is that? I thought that, when on production, i would not need to run two servers. Am i doing something wrong? -
Reason why CSS file not reflecting on PDF using Weazprint
I am trying to add style to my PDF file using a CSS file which for some reason is not linking to it. I have tried the following: PDF template {% load static %} <link rel="stylesheet" href='{% static "css/pdf.css" %}' media="all" /> I have tried to link it through the views page: views.py @staff_member_required def admin_order_pdf(request, order_id): -------------------------------------------- weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) return response I am using the followig config in the settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') -
Django shows valid object as NoneType
views.py def profile(request, username): user = User.objects.filter(username=str(username)).first() posts = Post.objects.filter(user=user).count() followers = User.objects.filter(following=user).count() following = user.following.all().count() return render(request, "network/profile.html", { "user": user, "posts": posts, "followers": followers, "following": following }) urls.py path("<str:username>/", views.profile, name="profile"), models.py class User(AbstractUser): following = models.ManyToManyField("self") django shows this error- File "C:\Users\Mufaddal\Desktop\cs50w\project4Network\network\views.py", line 98, in profile following = user.following.all().count() AttributeError: 'NoneType' object has no attribute 'following' The website shows the username, posts, following, followers correctly which means the query is returning a valid user. Then why does django show this error? -
Django Exif Data: 'IFDRational' object is not subscriptable
I got an issue with the code: 'IFDRational' object is not subscriptable Here is the trace: lat = get_decimal_from_dms(geotags['GPSLatitude'], geotags['GPSLatitudeRef']) degrees = dms[0][0] / dms[0][1] the is issue is: Variable Value dms (45.0, 46.0, 34.29) ref 'N' {'GPSAltitude': 22.90324416619237, 'GPSAltitudeRef': b'\x00', 'GPSDateStamp': '2020:10:17', 'GPSDestBearing': 18.1919587128, 'GPSDestBearingRef': 'M', 'GPSHPositioningError': 65.0, 'GPSImgDirection': 108.199192887128, 'GPSImgDirectionRef': 'M', 'GPSLatitude': (12.0, 26.0, 14.09), 'GPSLatitudeRef': 'N', 'GPSLongitude': (1.0, 47.0, 39.38), 'GPSLongitudeRef': 'E', 'GPSSpeed': 0.0, 'GPSSpeedRef': 'K', 'GPSTimeStamp': (12.0, 58.0, 42.0)} That what I get from an image for instance. I think the code assimilate GPSLatitudeRef to degrees = dms[0][0] / dms[0][1]. The thing is GPSLatitudeRef is a letter none a number. def get_geotagging(exifgps): geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exifgps: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exifgps[idx]: geotagging[val] = exifgps[idx][key] return geotagging def get_decimal_from_dms(dms, ref): degrees = dms[0][0] / dms[0][1] minutes = dms[1][0] / dms[1][1] / 60.0 seconds = dms[2][0] / dms[2][1] / 3600.0 if ref in ['S', 'W']: degrees = -degrees minutes = -minutes seconds = -seconds return round(degrees + minutes + seconds, 5) def get_lat_coordinates(geotags): lat = get_decimal_from_dms(geotags['GPSLatitude'], geotags['GPSLatitudeRef']) return lat def get_lon_coordinates(geotags): lon = get_decimal_from_dms(geotags['GPSLongitude'], geotags['GPSLongitudeRef']) return … -
Why doesn't the debug output in my views.py file get printed when there is a database constraint violation in Django?
I have three forms which have one submit button. The three forms represent employers, job listings and job listing categories. When a user enters the employer name in the form, I want to check if it already exists in the database. If it does, I want to use that employer database row and have it tied to the newly added job listing. Here are the relevant parts of my forms.py file: from django.forms import modelform_factory from .models import Employer, JobListing, Category_JobListing EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"]) JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "due_date", "job_application_url"]) Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"]) models.py file: class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES) short_bio = models.TextField(blank=True, null=True) website = models.URLField() profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) def __str__(self): return self.name class JobListing(models.Model): employer = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=100) job_description = models.TextField() job_requirements = models.TextField(); what_we_offer = models.TextField(); due_date = models.DateField(); job_application_url = models.URLField() admin_approved = models.BooleanField(default=False) def __str__(self): return self.job_title class Category_JobListing(models.Model): job_listing = models.ForeignKey(JobListing, on_delete=models.CASCADE) category = models.CharField(max_length=MAXIMUM_INTEREST_LENGTH, choices=INTEREST_CHOICES) views.py file: def submitJobListing(request): if request.method == "POST": employer_form = EmployerForm(request.POST, request.FILES) job_listing_form = JobListingForm(request.POST, request.FILES) category_job_listing_form = Category_JobListingForm(request.POST, request.FILES) if employer_form.is_valid() and job_listing_form.is_valid(): … -
Django check buttons send to models backend
I am creating a Django web site in which a user has to select a skill category and then skill or skills in the same category that selected category and skill or skills have to be stored in model with a username which is logged in... how can I do it?? <form method="post"> {% csrf_token %} <div class="row"> <div class="col-4"> <div class="list-group" id="list-tab" role="tablist"> <a class="list-group-item list-group-item-action active" id="list-lead_generator-list" data-toggle="list" href="#list-lead_generator" role="tab" aria-controls="lead_generator"><i class='fas fa-users'></i>Lead generator</a> <a class="list-group-item list-group-item-action" id="list-content_creator-list" data-toggle="list" href="#list-content_creator" role="tab" aria-controls="content_creator"><i class='fas fa-pen'></i>Content Creator</a> <a class="list-group-item list-group-item-action" id="list-social-social_media_handler-list" data-toggle="list" href="#list-social_media_handler" role="tab" aria-controls="social_media_handler"><i class='fas fa-icons'></i>Social Media Handler</a> </div> </div> <div class="col-8"> <div class="tab-content" id="nav-tabContent"> {% comment %} <input class="bg-white rounded border border-gray-400 focus:outline-none focus:border-indigo-500 text-base px-4 py-2 mb-4" placeholder="Skill" name="Skill" type="text"> {% endcomment %} <div class="tab-pane fade show active" id="list-lead_generator" role="tabpanel" aria-labelledby="list-lead_generator-list"> <label class="container">Lead Generator <input type="checkbox" name="lead_generator" class="lead_generator"> <span class="checkmark"></span> </label> <input type="hidden" name="skill" id="txt_lead_generator"> </div> <div class="tab-pane fade" id="list-content_creator" role="tabpanel" aria-labelledby="list-content_creator-list"> <label class="container">instagram <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> </label> <label class="container">facebook <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> </label> <label class="container">linkedin <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> </label> <label class="container">twitter <input type="checkbox" name="content_creator" class="content_creator" > <span class="checkmark"></span> </label> <label class="container">youtube <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> … -
How to serialize nested objects?
I have Django models: class Client(models.Model): name = models.CharField() class Office(models.Model): name = models.CharField() class HolidayOffer(models.Model): name = models.CharField() class Booking(models.Model): holiday_offer = models.ForeignKey(HolidayOffer, null=True) office = models.ForeignKey(Office, null=True) client = models.ForeignKey(Client, null=True) start_date = models.DateField() end_date = models.DateField() How to construct django-rest-framework serializer for API JSON to get a response similar to the example below: { "offices": [ { "name": "New York Office", "clients": [ { "name": "Client A", "bookings": [ { "holiday_offer": { "name": "Cyprus - Exclusive Vacation f> } "start_date": "20180608", "end_date": "20180615" } ] } ] } ] } Changing of the model relations is ofc possible. -
How to change join and group by SQL to ORM in Django
I'm new in Django. So, I want to join two model which is company and client and count the number of client for each of the company. Here the SQL SELECT Company_company.name, count(Client_client.cid) FROM Company_company LEFT JOIN Client_client ON Company_company.comid = Client_client.comid_id GROUP BY Company_company.name; But since in Django we use ORM. So I'm a little bit confusing since I'm beginner. I already refer few SQL to ORM converter website such as Django ORM and do some try and error. But, I didn't know where the problem since I want the output from the ORM to be classify into different array. Here is my code: labels = [] data = [] queryClientCompany = client.objects.values('comid').annotate(c=Count('cid')).values('comid__name','c') for comp in queryClientCompany: labels.append(comp.comid__name) data.append(comp.c) The error stated that the comid__name is not defined. So actually how to append the result? I hope someone can help me. Thank you for helping in advanced. -
How to Access URL Params in Django Channels Consumers
If i had the following url in routing.py: /rooms/<int:id>/ How would I access the id parameter from withing a JSONWebsocketConsumer? -
How to solve a 405 error in a class based view
I am currently working on my first website. But I am experiencing this problem. I have this class: class TranslatorView(View): def translator(self, request, phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return translation, render(request, 'main/translator.html') And the url for this class is path('translator/', TranslatorView.as_view(), name='translator'), When I enter to the website, it appears a HTTP 405 error. I think I have the problem in the class. But Idk how to solve it -
Django - no module named config
I'm trying to deploy a Django application using Gunicorn, but whenever i try to start the Gunicorn Daemon, i get the following error: ModuleNotFoundError: No module named 'config' Here is my daemon: [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/tes/tes ExecStart=/tes/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/tes/tes.sock config.wsgi:application Restart=always SyslogIdentifier=gunicorn User=root Group=django [Install] WantedBy=multi-user.target Here is my folder: tes |-tes |-venv |-staticfiles |-config |-urls.py |-wsgi.py |-__init__.py |-settings |-base.py |-production.py |-local.py I'm struggling to find the error here, can anyone help me? -
Django comments and add comment form same page
I want to to display my comments on the post detail page. After trying hard I ran the codes. But I think there are some problems with my code. I am not particularly sure that I am using the redirect function correctly. Also, do I need to define the get function like post? view.py model = Post template_name = 'blog/post_detail.html' form_class = AddCommentForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['comments'] = Comment.objects.filter(is_active=True) context['form'] = AddCommentForm return context def post(self, request, *args, **kwargs): post = get_object_or_404(Post, slug=kwargs['slug']) # List of active comments for this post new_comment = None if request.method == 'POST': # A comment was posted comment_form = AddCommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = AddCommentForm() return redirect('blog:post_detail', kwargs['slug']) ``` url.py `` path('detail/<slug:slug>/', PostDetailView.as_view(), name='post_detail'), ``` -
How can i write this if statement on my template Django
I would like to write something in the form of an entry to a particular tournament where the user after clicking on the "join" button is moved to a sheet where the user is asked to enter their name and choose which tournament they want to join. Is it possible to write a conditional instruction that checks if the name of a given tournament is equal to the name of the tournament that the user has chosen and using it to list the users assigned to the given tournament. my views.py file def content(request, pk): tournament = Tournament.objects.get(id=pk) users = TournamentUsers.objects.all() return render(request, 'ksm_app2/content.html', {'tournament': tournament, 'users': users}) my models.py file class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) tournament_info = models.TextField(max_length=10000) def __str__(self): return self.tournament_name class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name {% for user in users %} {% if user.user_tournament == tournament.tournament_name %} <p>{{ user.user_first_name }} {{ user.user_last_name }}</p> {% else %} <p>no one takes part in this tournament </p> {% endif %} {% endfor %} if u have any idea what i can do i will … -
How to do a calculation using angular
I am new to angular and I am trying to calculate the salary of an employee when his ID, his basic salary and the relevant month is given. For this, I should add the total additions and substract the total deductions from the basic salary to calculate the final salary. Currently I am having this angular form where the id, basic salary and the month is provided. <div class="row justify-content-center"> <div class="col-md-11"> <nb-card> <nb-card-header>Add Salary</nb-card-header> <nb-card-body> <form class="form-horizontal"> <fieldset> <legend>Details</legend> <br> <div class="form-group row"> <label for="id" class="label col-sm-3 form-control-label">Name</label> <div class="col-sm-9"> <nb-select id="id" name="id" [(ngModel)]="salary.id" placeholder="Select ID" [(selected)]="selectedItem"> <nb-option *ngFor="let usr of users" value="{{usr.id}}">{{usr.username}}</nb-option> </nb-select> </div> </div> <div class="form-group row"> <label for="month" class="label col-sm-3 form-control-label">Month</label> <div class="col-sm-9"> <input type="number" nbInput fullWidth id="month" name="month" [(ngModel)]="salary.month" placeholder="Month"> </div> </div> <div class="form-group row"> <label for="date" class="label col-sm-3 form-control-label">Issue Date</label> <div class="col-sm-9"> <input nbInput type="date" id="date" name="date" [(ngModel)]="salary.issueDate" placeholder="Date"> </div> </div> <div class="form-group row"> <label for="basicsal" class="label col-sm-3 form-control-label">Basic Salary</label> <div class="col-sm-9"> <input type="text" nbInput fullWidth id="basicsal" name="basicsal" placeholder="BasicSalary"> </div> </div> <div class="form-group row"> <div class="col-md-3 offset-md-3"></div> <div class="col-md-3 offset-md-3"> <button nbButton hero status="success" (click)="onCalculate()">Calculate</button> </div> </div> </fieldset> <div class="form-group row"> <div class="col-6"> <fieldset> <legend>Additions</legend> <br> <div class="form-group row"> <label for="addition" class="label col-sm-3 form-control-label">Total … -
Django copy pdf to s3bucket
I am in trouble saving my local file to s3bucket. I have a corn job in my Django project, after a certain time, it generates a pdf file. And I want to save the file in s3bucket. Currently, Django s3bucket is working very well like saving my uploaded file to s3bucket and lots more thing is working. But I am not getting how to copy local file and save in s3bucket. CURRENTLY I AM SAVING THIS IN MY LOCAL MACHINE LIKE THIS WAY: shutil.copyfile('/var/www/local.pdf' ,'media/newfileins3bucket.pdf') But it will not works that way i want to save it directly to s3bucket. Can anyone help me in this case? -
Django Rest API that takes in SQL query and return the result of the executed query from Database
I'm trying to design a dynamic API with Django Rest and the requirement is slightly unique. The API is meant to take in an SQL query and execute that query and return the result of that query. So basically it can be a GET request that returns some data, or a POST request that inserts some data. I currently have no idea how this can be achieved so any advice/example would be greatly appreciated. And also, will it be simpler to go with plain Django, or with Django Rest Framework? Thank you! -
Custom User model does not follow with the extended BaseUserManager implementation in django admin
I am a a newbie in django and currently I am exploring with creating Custom User model subclassing the AbstractBaseUser in django. I wrote the following code for the userModel and BaseUserManager implementation. from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.contrib.auth.base_user import BaseUserManager from django.utils import timezone class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): values = [email] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError("The {} value must be set".format(field_name)) email = self.normalize_email(email) extra_fields.setdefault("username", email) #this line of code here user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) extra_fields.setdefault("username", email) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) username = models.CharField(unique=True, max_length=200) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) address = models.CharField( max_length=200, ) latitude = models.FloatField(default=0.00, blank=True) longitude = models.FloatField(default=0.00, blank=True) … -
The view lessons.views.login didn't return an HttpResponse object. It returned None instead
i started to learn django, im getting The view lessons.views.login didn't return an HttpResponse object. It returned None instead. i dont know where i'm making mistake. my HTML codes <div class="formBx"> <form method="POST"> {% csrf_token %} <h2>Sign In</h2> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="" value="Login"> <p class="signup">Don't have an Account?<a href="#" onclick="toggleForm();">Sign Up.</a></p> </form> </div> </div> <div class="user signUpBx"> <div class="formBx"> <form method="POST"> {% csrf_token %} <h2>Create an account</h2> <input type="text" name="username1" placeholder="Username"> <input type="email" name="email" placeholder="E-mail"> <input type="password" name="password1" placeholder="Create Password"> <input type="password" name="confirm" placeholder="Confirm Password"> <input type="submit" name="" value="Register"> <p class="signup">Already Have an Account?<a href="#" onclick="toggleForm();">Sign In.</a></p> </form> </div> <div class="imgBx"><img src="{% static 'img/logbg2.jpg' %}"></div> </div> </div> My views.py codes def login(request): if request.method == "GET": return render( request,"login.html") if request.method == "POST": if request.POST.get("submit") == "Login": if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(username = username,password=password) if user is None: messages.info(request,"Username or password is incorrect") return render(request,"login.html") messages.success("Logged In") login(request,user) return render(request,"index.html") elif request.POST.get("submit") == "Register": if request.method == "POST": username = request.POST["username1"] email = request.POST["email"] password = request.POST["password1"] confirm = request.POST["confirm"] if password and confirm and password != confirm: newUser = (User.objects.create_user(username,email,password)) newUser.save() login(request,newUser) return render(request,"login.html") … -
How to make notification system with django framework?
Well i am actually wanting to build notification system with Django, When someone follow to some other people than they get notify or when someone like other people posts than those people also get notify. I just to want know which will be the best approach for building this notification system with Django framework and which Django tools i suppose to use such as Django signals or Django built in messages etc? please tell me the best and easy way to build such notification system with Django quite similar to Instagram or Facebook notification system since Instagram also use Django for its back-end so at least i know this is possible with Django but i don't know the path or complete track of building that system. Many thanks in advance!. -
Secured connection with Heroku and CORS
I have a Django/ Vue.js app deployed on Heroku. When I open the app for the first time it's none secured (http://) and I have issues with the CORS because my app won't permit connections from an insecured website to my secured endpoints. But as soon as I log in, my site turns into a secured one and I have no more issus with the CORS. As I log out, no issues whatsoever. My question is what can I do to have my website secured as soon as it's open? Do I have to change the CORS settings? Or the Heroku settings? -
Django Models get all models with the objects with the a ForeignKey's
I would like to have a method which I can call and the return will be something like this (dict, list or queryset doesn't matter to me): { 'name': 'test', 'long': '1.2345', 'lat': '1.2345', 'measurements': [ { 'time': datetime 'value': 3245.2 }, { 'time': datetime 'value': 3213.1 }, ] } I have the following models: class Block(models.Model): id = models.AutoField(primary_key=True, auto_created=True) long = models.DecimalField(default=0.0, max_digits=9, decimal_places=7) lat = models.DecimalField(default=0.0, max_digits=9, decimal_places=7) class BlockMeasurement(models.Model): block = models.ForeignKey(Block, on_delete=models.SET_NULL, null=True) value = models.DecimalField(default=0.0, max_digits=9, decimal_places=2) time = models.DateTimeField(default=datetime.now, blank=True) I could make a function that would loop through all of the Blocks and then add measurements to an array and later add the list of measurements to the dict, but there must be a nicer way to handle this. -
How to diagnose a segfaulting Apache ModWSGI Django site?
How do you diagnose and fix a segmentation fault in a Python process running behind Apache? I have a Django web app being served via a fairly standard Apache+ModWSGI server on Ubuntu 20. After a recent code deployment, the site's worker process now immediately crashes upon startup, with the error: [core:notice] [pid 32373:tid 140340980481088] AH00051: child pid 32375 exit signal Segmentation fault (11), possible coredump in /etc/apache2 I've roughly identified the Python code that appears to trigger the crash, which is a new O365 package import. However, the package is pure Python, and only references a few generic external packages like requests and python-dateutil. There's nothing exotic or unstable in it that would cause Apache to crash. I've encountered this type of issue before with Apache, but it's very rare, and none of my past tricks have fixed it. I've tried upgrading all system packages, tweaking some Apache settings like KeepAlive, disabling some unnecessary modules, and changing the location of the import to load dynamically during the request, but nothing's had any effect. I have LogLevel debug set but Apache still isn't outputting anything besides the above line and the normal "Starting process" type messages.