Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO - Extract filtered data to excel
I have a view for filtering data and display it in a table. I would like to export the filtered data to excel. I wrote the view for exporting but I don't know how to connect the two. OrderFilter is a django-filter Views.py def data(request): orders= Order.objects.all() filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date','-Hour') return render(request, 'template.html',{'orders':orders,'filter': filter}) def export_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Hour', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Order.values_list('Date', 'Hour', 'Category', 'Item__Item') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
How to declare common variables for all methods of a Django class-based view?
I have a class-based view in my Django application and it works fine. But I guess it is not coded well, because it violates the DRY principle. Specifically, I have two absolutely similar declarations of the posts_list variable inside get() and post() methods: class TopicView(View): def get(self, request, topic_id): post_form = PostForm() posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date') return render(request, 'discussions/topic.html', {'posts_list': posts_list, 'post_form': post_form, 'topic_id': topic_id}) def post(self, request, topic_id): post_form = PostForm(request.POST) if post_form.is_valid(): post = post_form.save(commit=False) post.author = request.user post.topic = Topic.objects.get(pk=topic_id) post.save() return redirect('discussions:topic', topic_id=topic_id) posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date') return render(request, 'discussions/topic.html', {'posts_list': posts_list, 'post_form': post_form, 'topic_id': topic_id}) Is there a way how I can declare this variable as a class attribute instead of a simple variable inside each of the methods? When I declaring it, I use topic_id as a filter for objects, and I extract topic_id from the URL (self.kwargs object, self is passed to both get() and post() as an input parameter). This is the main issue. -
How do I display user profile pic if saved in custom directory?
I have created an app called users and have created a custom method called get_upload_path. I am using this method to allow users to upload profile pics to a custom path for better organization of images. What should I change in MEDIA_URL so that these images will be displayed on a custom template? users/models.py: from django.db import models from django.contrib.auth.models import User def get_upload_path(instance, filename): return '%s/%s' % (instance.user.username, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # make bio and other stuff here image = models.ImageField(default='default.jpg', upload_to=get_upload_path) def __str__(self): return f'{self.user.username} Profile' settings.py: # Directory where uploaded files will be saved MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' users/templates/users/profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.first_name }} {{ user.last_name }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <!-- FORM HERE --> </div> <p class="text-muted">Joined on: {{ user.date_joined|date:"F d, Y" }}</p> <p class="text-muted">Last logged in on: {{ user.last_login|date:"F d, Y" }}</p> {% endblock content %} File Structure: -
how to serve django with react frontend using webpack?
I used webpack to convert react to static files and render them in django templates but even though the static files are changed the website rendered by django is same -
Errors with models in django, creating events registration app
i am creating django app that allows users to register to different events. I created one Registration model in .models and added specific views but i have got some model errors. Wondered if anyone could help out a little? I am also not 100% sure if i have done all code correctly because i am quite new to django. Thanks a lot! Here is my model file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse import datetime class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) hardness_level = models.TextField(max_length=20, default='easy') author = models.ForeignKey(User, on_delete=models.CASCADE) location = models.CharField('location', max_length=150) info = models.TextField() starts = models.DateTimeField('Starts') ends = models.DateTimeField('Ends') arrive_when = models.DateTimeField('Arrival time', null=True, blank=True) arrive_where = models.CharField('Arrival location', null=True, max_length=150, blank=True) registration_starts = models.DateTimeField('Registration start') registration_limit = models.IntegerField('Guest limit', default=0, choices=[(0, u"No limit")] + list(zip(range(1, 100), range(1, 100))), on_delete=models.CASCADE()) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = "event" verbose_name_plural = "events" ordering = ['-starts'] def __str__(self): if self.starts.date() != self.ends.date(): return u"%s, %s - %s" % (self.title, self.starts.strftime("%a %H:%M"), self.ends.strftime("%a %H:%M")) else: return u"%s, %s - %s" % (self.title, self.starts.strftime("%H:%M"), self.ends.strftime("%H:%M")) def get_registrations(self): return EventRegistration.objects.filter(event=self) … -
How to add a row ID in django-tables to get the selected radio button from the specific row
I am trying to use the jQuery to get the row that selected radio is in and also the selected radio button value when using django-tables2. So, I have three columns in a table and I rendered it with django-tables2. The third columns is templatecolumn with the HTML template (buttons.html: <form class="myForm"> <input type="radio" class="Yes" name="result" value="Yes"> <label for="Yes">Yes</label> <input type="radio" class="No" name="result" value="No"> <label for="No">No</label><br> </form> I then add templatecolumn to the table ( I created my own table class by inheriting from tables.Table): myTableCol={} mylist = [] for i in queryResults: mydic = {} for j in i: className=str(type(j)).split(".")[1] mydic.update({className: j.name}) myTableCol.update({className: tables.Column()}) mylist.append(mydic) myTableCol.update({'Action': tables.TemplateColumn(template_name="buttons.html", verbose_name=("Actions"), orderable=True)}) Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},}) myTableCol.update({'Meta':Meta}) QueryTable2=type('QueryTable', (tables.Table,), myTableCol) The table is then rendered using {% render_table table %} that gives the html below. I am trying to get which radio button that was selected for the row. $(document).ready(function () { $('input').click(function() { var $selectedButton = $('input[name=result]:checked').val(); var $row = $(this).closest("tr"); var $rowData = $row.children("td").map(function() { return $(this).text(); }).get(); alert($selectedButton); });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <div class="table-container"> <table class="paleblue"> <thead class="thead-default" > <tr> <th class="orderable"> <a href="?sort=UseCase">UseCase</a> </th> <th class="orderable"> <a href="?sort=MainFlow">MainFlow</a> </th> <th class="orderable"> <a href="?sort=Action">Actions</a> </th> </tr> </thead> … -
Android-Django image upload:- App closes after image capture, Caused by: java.lang.NullPointerException: uri
I am making an Android app to capture an image and upload to Django development server, which will do some decoding on the uploaded image. Following are my Android side codes: MainActivity.java package com.example.original; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.loader.content.CursorLoader; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.original.apiinterface.APIInterface; import com.original.decoder.response.MyResponse; import java.io.File; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.provider.Settings; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.File; import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { Button camera_open_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); camera_open_id = (Button)findViewById(R.id.camera_button); camera_open_id.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent camera_intent = new Intent(MediaStore .ACTION_IMAGE_CAPTURE); startActivityForResult(camera_intent, 100); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 100 && resultCode == RESULT_OK && data != null) { //the image URI Uri selectedImage … -
HttpResponseRedirect в Django. Can't do redirect on 'done' page
After filling the page should appear 'done', but i have a error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/candidate/done.html The current path, candidate/done.html, didn't match any of these. Can't configure redirect to 'done' page. Here views.py: from django.http import Http404, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import AnketaForm from .models import Anketa def anketa_create_view(request): if request.method == 'POST': form = AnketaForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('candidate/done.html') else: form = AnketaForm() return render(request, 'candidate/anketa_create.html', {'form': form}) urls.py (apps/candidate) from django.urls import path from . import views urlpatterns = [ path('', views.anketa_create_view, name = 'anketa_create_view'), ] urls.py from django.contrib import admin from django.urls import path, include from candidate.views import anketa_create_view urlpatterns = [ path('done/', anketa_create_view), path('', anketa_create_view), path('grappelli/', include('grappelli.urls')), path('admin/', admin.site.urls), ] -
How can I show auto_now_add field in Django admin?
I have a model (as below) and in that, I've set auto_now_add=True for the DateTimeField class Foo(models.Model): timestamp = models.DateTimeField(auto_now_add=True) From the doc, As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set. Q: How Can I show this auto_now_add field in Django Admin? (by default Django Admin doesn't show auto_now_add fields) -
Where does the value 'form' in 'form.as_p' in Django template come from?
I know this question was asked before, but the accepted answer does not really answer the question: where `form.as_p`in django templates come from? In Django doc: Example myapp/views.py: from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] Example myapp/author_form.html: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The question is, where does the template get the 'form' context from, since we did not explicitly define a render() function inside the AuthorCreate class? Thanks. -
Django: Select a valid choice. <choice> is not one of the available choices
I'm trying to make use a choice field to all users to add permissions to a role. The permissions are defined in their own class and are displayed in the drop-down box correctly, however when submitting the form, it says that the option selected isn't an available choice. forms.py from django import forms from .models import RolePermission, Permission class AddPermissionForm(forms.ModelForm): class Meta: model = RolePermission fields = ['permission'] permission = forms.ChoiceField(choices=Permission.choices) def __init__(self, *args, **kwargs): super(AddPermissionForm, self).__init__(*args, **kwargs) self.fields['permission'].widget.attrs.update({'class': 'form-control'}) views.py def role_view(request, role_id): role = Role.objects.get(id=role_id) add_permission_form = AddPermissionForm(request.POST) if request.method == 'POST' and add_permission_form.is_valid(): new_permission = add_permission_form.cleaned_data['permission'] # is_already_permission = RolePermission.objects.filter(role_id=role_id, permission=new_permission) # if is_already_permission: new_role_permission = RolePermission(role_id=role_id, permission=new_permission) new_role_permission.save() return redirect('core:role_view role_id=role_id') return render(request, 'role_view.html', {'role': role, 'form': add_permission_form}) Permissions class class Permission(models.TextChoices): PAGE_CREATE = 111 PAGE_EDIT = 112 PAGE_PUBLISH = 113 PAGE_DELETE = 114 I've tried changing the choice field to a select field, but that doesn't solve the problem. -
Use a single function for multiple serializer fields with different arguments
I have a serializer for a model with an image field, for which I have saved multiple different sized thumbnail images. I access them by returning their URL using the SerializerMethodField: class GalleryImageSerializer(serializers.ModelSerializer): image_sm = serializers.SerializerMethodField() image_md = serializers.SerializerMethodField() image_lg = serializers.SerializerMethodField() image_compressed = serializers.SerializerMethodField() def get_image_sm(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/sm.jpg') def get_image_md(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/md.jpg') def get_image_lg(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/lg.jpg') def get_image_compressed(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/compressed.jpg') This code works, but it kind of violates the "don't repeat yourself" guideline. As you can see, these are all duplicate SerializerMethodFields, with the only difference being the filename, eg 'lg.jpg', 'md.jpg', etc. I'd much prefer to have only one function that I call with an argument for the filename, as an example(pseudocode): class GalleryImageSerializer(serializers.ModelSerializer): image_sm = serializers.SerializerMethodField(filename='sm.jpg') image_md = serializers.SerializerMethodField(filename='md.jpg') image_lg = serializers.SerializerMethodField(filename='lg.jpg') image_compressed = serializers.SerializerMethodField(filename='compressed.jpg') def get_image(self, obj, filename=''): return default_storage.url(f'{splitext(obj.image.name)[0]}/{filename}') Currently I am unable to find any way to achieve this. Reading the source code of SerializerMethodField, it doesn't seem to support it. Is there any way to avoid creating duplicate functions for fields with arbitrary differences? -
Django Form Instance not showing the Uploaded Image
I am making a CMS platform in Django. I want to create the EDIT Post method so that anyone can edit their post. The main problem is the ImageField. As ImageField is required in Django's Models.py.So, while creating edit Post method for the user the ImageField, the image which was uploaded at the time of post creation, is empty. Here is Edit Post View def updatePost(request,pk): getEditPost= get_object_or_404(Post,pk=pk) if request.method=="POST": form = CkEditorForm(request.POST,request.FILES,instance=getEditPost) try: if form.is_valid(): form.save() except Exception as e: print(e) else: form = CkEditorForm(instance=getEditPost) context= { 'myForm':form, 'post':getEditPost, } return render(request,"post/editPost.html",context) Here is my forms.py class CkEditorForm(ModelForm): ..... ..... featuredImage = forms.ImageField(required=True) My models.py class Post(models.Model): ..... ..... featuredImage = models.ImageField(upload_to="featured_image/") -
sqlite3 works well in centos7 and python shell,but can't work in Uwsgi
I have a question need your help~ I have a django program run in a vps(centos7,django2.2),it works well with Nginx+Uwsgi. I edit three files(like a.py b.py c.py),and upload to the vps by winscp.exe,the program can't work now. I found these logs in the uwsgi.log file. File "/mnt/datasource/<privacy_hidden>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 68, in <module> check_sqlite_version() File "/mnt/datasource/<privacy_hidden>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 65, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). unable to load app 0 (mountpoint='') (callable not found or import error) I wrote "sqlite3 --version" in centos7 shell, it show version = 3.30.1 I wrote "python >>> import sqlite3 >>>print sqlite3.sqlite_version" it show version=3.30.1 I wrote "python manage.py runserver --noreload 0.0.0.0:80",it works well, no info show sqlite error. But the program can't work in uwsgi,I think the uwsgi.ini is correct. What can I do ? Thank you! -
How to save null value to date field
I have a model class League(models.Model): league = models.IntegerField(primary_key=True) season_start = models.DateField(null=True) I create objects from League model from json data which I extract from external API and save them to database. response = requests.get(leagues_url, headers = header) leagues_json = response.json() data_json = leagues_json["api"]["leagues"] for item in data_json: league_id = item["league_id"] season_start = item["season_start"] b = League.objects.update_or_create(league = league_id,season_start = season_start) Sometimes json data for season_start field have not value that is none and this none field cause error while I create league objects and save them to database. How I can solve problems caused by none values while saving them to date field -
Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. AWS Elastic Beanstalk
I tried following this tutorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html but after I execute eb create django-env I get this error: Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. AWS Elastic Beanstalk I found similar questions about the same issue but none of them solved the problem. I can't figure out what is wrong. I would greatly appreciate any insights. 🙂 -
How to get value from class Car to class Order
I'm need to get "Make" from class Car to "Make" in Order Class: class Car(models.Model): Make = models.CharField(max_length=64, null=True) #that i need to get in Order class Model = models.CharField(max_length=64, null=True) def __str__(self): return str(self.Make) + " " + str(self.Model) class Order(models.Model): #make = Car.Make - like that, but it is not work #make1 = models.ForeignKey(Car.Make, null=True, on_delete=models.SET_NULL) # it doesn't work either car = models.ForeignKey(Car, null=True, on_delete=models.SET_NULL) # that's work but it's give me return of __str__ def __str__(self): return str(self.Order_amount) + " " + str(self.Order_status) P.S. I just started to learn django, and I can not find any information about it -
Add more button in JS not woking
I am trying to add rows in my django template using JavaScript but it is not working like it's supposed to: HTML <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/static/jquery.formset.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form id="myForm" action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.player.management_form }} <h3> Product Instance(s)</h3> <table id="table-product" class="table"> <thead> <tr> <th>player name</th> <th>highest score</th> <th>age</th> </tr> </thead> {% for player in form.player %} <tbody class="player-instances"> <tr> <td>{{ player.pname }}</td> <td>{{ player.hscore }}</td> <td>{{ player.age }}</td> <td> <input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"> </td> </tr> </tbody> {% endfor %} </table> <button type="submit" class="btn btn-primary">save</button> </form> </div> <script> var i = 1; $("#input_add").click(function() { $("tbody tr:first").clone().find(".data_input").each(function() { if ($(this).attr('class')== 'tr_clone_add btn data_input'){ $(this).attr({ 'id': function(_, id) { return "remove_button" }, 'name': function(_, name) { return "name_remove" +i }, 'value': 'Remove' }).on("click", function(){ var a = $(this).parent(); var b= a.parent(); i=i-1 $('#id_form-TOTAL_FORMS').val(i); b.remove(); $('.player-instances tr').each(function(index, value){ $(this).find('.data_input').each(function(){ $(this).attr({ 'id': function (_, id) { var idData= id; var splitV= String(idData).split('-'); var fData= splitV[0]; var tData= splitV[2]; return … -
Django: DatePicker with "django-widget-tweaks"
Good day, I'm trying "create" a DatePicker for one of my Inputfields in Django but it's not working! In my models.py: class Customer(models.Model): ... name = models.CharField() date = models.DateField() In my views.py: def Page(request): CustomerFormSet = modelformset_factory(Customer, fields='__all__') formset = CustomerFormSet (queryset=Customer.objects.none()) ... context = {'formset': formset} return render(request, 'app/base.html', context) In my template: {% extends 'app/base.html' %} {% load widget_tweaks %} <form actions="" method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.id }} ... {% render_field form.name class="form-control" %} ... {% render_field form.date class="form-control" %} ... Now my first Inputfield works fine! It returns a fitting Field in Bootstraps "Form-Group"-Layout. But my InputField for Dates remains a simple TextInput with no calendar apearing to choose from. My Question is: am I doing something wrong or is it still impossible to obtain such a function in this way? Thanks and a nice evening to all of you. -
Setting the static files for Gunicorn Django deployment
I am trying to deploy a Django project with Nginx and Gunicorn, but Gunicorn cannot find the static files when I run it. My File structure is like this: user@testing:~$ ls db.sqlite3 main manage.py project static templates This is the nginx file for the project server { listen 80; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/static; } location / { include proxy_params; proxy_pass http://localhost:8000; } } Settings.py file STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' Thanks in advance! -
Render different templates for ListView
I have a ListView with some good functionality that i want to use from another app. The way i did it was using get_template_names. def get_template_names(self): referer = self.request.META['HTTP_REFERER'] if "/mwo/order/" in referer: return ['invent/use_part.html'] return ['invent/part_list.html'] Which i access from two different apps: path('inventory/', PartListView.as_view(), name='partlist'), ... path('mwo/order/<int:pk>/add_part/', PartListView.as_view(), name='add_part'), But it causes a bug if i use a direct link to 1st url from navbar and not from another app. Now i'm new to django and i'm pretty sure there should be a better way for this. What can i use instead of request referrer to render different template for ListView when i access it from another view. -
How to reuse effectively Django models
I have 2 type of Products , 1 is Product and 1 is sub product (child of product) but it will use same attribute of product . so my product table is like class Activity(models.Model): owner = models.ForeignKey(owner, on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=False, blank=False) and now it have like 4 tables of its properties for example I will paste 2 here. class workinfDatDates(models.Model): agenda = models.ForeignKey(Activity, on_delete=models.CASCADE) Date = models.DateField() and class BlockedDates(models.Model): agenda = models.ForeignKey(Activity, on_delete=models.CASCADE) blockDate = models.DateField() Now Sub Product is child of it like class SubActivity(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) subName = models.CharField(max_length=50 , null=False, blank=False) it should have same attributes like block dates and working dates etc . Now I should create new tables for it ? or is there any good way to use by including something to already defined tables ? -
Scale page to standard letter fomat with CSS
With regards to a webpage generated using Django, I would like to just print the page as a PDF in chrome. But when I do so, the view does not fit onto a standard 8.5/11 papersize. Is there a straightforward method of using CSS/HTML to scale items so that when you select print, it will fit everything onto a standard letter size sheet? So for desktops, if I have something like: @media only screen and (min-width: 768px) { /* For desktop: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;} .col-3 {width: 25%;} } Would it be something like this for paper sizes? @media only screen and (min-width: 8.5in) { /* For printing: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;} .col-3 {width: 25%;} } Or is there a much better way of accomplishing this? -
django v2.2:python manage.py runserver always reload
I have a question about django,can you help me ? I has write a django program ,it works well in my pc(windows10) and the vps(centos7,django 2.2). When I changed some code in 3 files,it works well in my pc,but can't work in the vps. I write this command in vps:" python manage.py runserver 0.0.0.0:80 ",it cames this: ***\a.py changed, reloading. Watching for file changes with StatReloader ***\b.py changed, reloading. Watching for file changes with StatReloader ***\c.py changed, reloading. Watching for file changes with StatReloader ***\a.py changed, reloading. Watching for file changes with StatReloader ***\b.py changed, reloading. Watching for file changes with StatReloader In the fact,these files only changed once,not changed after the command, It continued reloading... I must input " python manage.py runserver --noreload 0.0.0.0:80 ". I think it's something error ? Thank you! -
Django foreign key on many to many field
A company can have many job categories. A job has to be related to that company's job categories. How can I do it correctly? class Company(models.Model): job_categories = models.ManyToManyField(JobCategory,blank=False) class Job(models.Model): category = models.ForeignKey(Company, on_delete=models.CASCADE)