Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static (css) and templates folders
I want to organize my the templates and static for each app in project as following: project/ app1/ static/ css/ app1.css templates/ app1_template.html app2/ static/ css/ app2.css templates/ app1_template.html project/ settings.py ... templates/ base.html static/ css/ base.css The intention: base.html uses only css styling from base.css Both app1_template and app2_template.html extend base.html app1_template and app2_template.html use their own .css respectively. My settings.py has these lines: TEMPLATES = [ { ... 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], ... }, }, ] ... STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) In base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> In app1_template.html: {% extends "base.html" %} {% load static %} <link href="{% static "css/app1.css" %}" rel="stylesheet"> With the above setup, my app1_template.htlm does not load app1.css styling at all. If I put the styling from app1.css into base.css, then it loads nicely. What code lines do I change to keep this organization? -
Django- Cannot assign queryset must be a instance
I am trying to make a multiple choice form, but I am getting the error: Cannot assign "<QuerySet [<Session: bbbb>, <Session: jheeyyy>]>": "Booking.session" must be a "Session" instance. I checked some solutions in stackoverflow but I can't solve it. I tried to change ModelMultipleChoiceField as ModelChoiceField but it gives "select a valid choice. that choice is not one of the available choices error." when I did it. I need help. models.py class Booking(models.Model): """ Entry recording a user registration to an event """ event = models.ForeignKey( "Event", related_name="bookings", on_delete=models.CASCADE ) person = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="bookings", on_delete=models.CASCADE ) session = models.ForeignKey( "Session", related_name="bookings", null=True, blank=True, on_delete=models.SET_NULL, ) class Meta: unique_together = ("event", "person") ordering = ["id"] def __unicode__(self): return "{0} : {1}".format(self.event.title, self.person) forms.py class SessionChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.get_label() class BookingSessionForm(ModelForm): session = SessionChoiceField( label="Select your session", queryset=None, required=True, widget = forms.CheckboxSelectMultiple, to_field_name = "title", ) class Meta: model = Booking fields = ["session"] def __init__(self, target_url, *args, **kwargs): super(BookingSessionForm, self).__init__(*args, **kwargs) self.fields["session"].queryset = self.instance.event.sessions.all() self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_action = reverse( target_url, kwargs={"booking_id": self.instance.id} ) self.helper.layout = Layout( "session", FormActions( Submit("save", "Confirm", css_class="btn btn-success"), Reset("reset", "Reset", css_class="btn btn-warning"), ), ) views.py def _booking_update_session(request, booking, form_target_url): """ … -
I am receiving this error when I try to send a file from react to django. (TypeError: __init__() got an unexpected keyword argument 'file')
Please help me solve this error. When I try to get the data on using file_serializer = FileSerializer(request.POST, request.FILES) instead in the picture. I receive error that name field is required even though I have passed it. I am not sure what more I can describe the error but any help would be appreciated. Models.py from django.db import models import uuid # Create your models here. class File_Uploader(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.FileField(blank=False, null=False, max_length=1000000000) name = models.CharField(max_length=64) upload_date = models.DateTimeField(auto_now=True, db_index=True) size = models.IntegerField(default=0) def __str__(self): return self.file.name Serializer.py from rest_framework import serializers from .models import File_Uploader from django.views.decorators.csrf import csrf_exempt @csrf_exempt class FileSerializer(serializers.ModelSerializer): class Meta: model = File_Uploader fields = ("file", "name", "size") views.py # from django.shortcuts import render from rest_framework.parsers import FileUploadParser, MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .serializers import FileSerializer class FileUploadView(APIView): permission_classes = [] parser_class = (FileUploadParser,MultiPartParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file = file_serializer.data.get("file") name = file_serializer.data.get("name") size = file_serializer.data.get("size") queryset = FileSerializer(file=file, name=name, size=size) queryset.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) React File Upload Code submit = (e) => { e.preventDefault(); let file = e.target.files[0]; let … -
How to clear a validation error in Django
I have a simple registration page in my Django web application. Once a user signs up, I am able to query my database and see if the username is already in use, if it is, I display a simple ValidationError. My problem is I can't figure out how to remove the error after a few seconds. I'm pretty good with Python but haven't found any luck, the only thing I can find is this outdated article from 2010 that gives me code that doesn't work anymore. This seems like a really simple fix, just import time and run a while statement, but I can't find the docs to remove a validation error. Bellow is my function for recognizing if the username is already in use. Thank you to everyone who helps! def clean(self): cleaned_data=super().clean() if User.objects.filter(username=cleaned_data["username"]).exists(): raise ValidationError("This username is taken, please try another one") -
Prepend URL to all URLs in Django
Was wondering if there was a way to prepend all URLs with a particular URL. I'll explain the challenge, perhaps I'm going about it all wrong: Imagine I have three sites all built using Django that are run using nginx and within separate docker containers: main_site, project1 and project2. When navigating to https://main_site, this should load the pages in main_site as normal. But when navigating to https://main_site/projects/project_1/, This should navigate to project 1. And similarly, when navigating to https://main_site/projects/project_2/, this should load the pages from project 2. I've managed to make this somewhat work using nginx and docker. I have rules something along the lines of: location / { proxy_pass http://main_site; } location /projects/project_1 { proxy_pass http://project_1; } location /projects/project_2 { proxy_pass http://project_2; } This works perfectly for the homepage (minus the static assets). But, whenever we use template tags in Django, the links in creates is always relative to root (/something/), whenever on any link, it takes me back to the main_site. I get why this is happening, because everything is happening on the same port. Question is, is there a way to prepend a URL to all the URLs (static assets as well) without fundamentally having to add … -
What is problems?
TemplateDoesNotExist at / pages/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: pages/index.html Exception Location: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\ecomsite_web', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\Scripts\python38.zip', 'c:\programdata\anaconda3\DLLs', 'c:\programdata\anaconda3\lib', 'c:\programdata\anaconda3', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages'] Server time: Sat, 05 Jun 2021 21:45:06 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\contrib\admin\templates\pages\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\contrib\auth\templates\pages\index.html (Source does not exist) Traceback Switch to copy-and-paste view C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) -
Why dashboard route is not accessible to me even if I am logged in?
I am using private route in my app to access dashboard. if I am not logged in it worked correctly and redirect me to the sign in page. but even if I am logged in it does not gives access to dashboard. Here is my code. App.js import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './containers/Home'; import Login from './containers/Login'; import Dashboard from './containers/Dashboard'; import PrivateRoute from './components/PrivateRoute'; import { Provider } from 'react-redux'; import store from './store'; const App = () => ( <Provider store={store}> <Router> <Layout> <Switch> <Route exact path='/' component={Home} /> <PrivateRoute exact path='/dashboard' component={Dashboard} /> <Route exact path='/login' component={Login} /> </Switch> </Layout> </Router> </Provider> ); export default App; PrivateRoute.js import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; const PrivateRoute = ({ component: Component, auth, ...rest }) => ( <Route {...rest} render={(props) => { if (!auth.isAuthenticated) { return <Redirect to="/login" />; } else { return <Component {...props} />; } }} /> ); const mapStateToProps = (state) => ({ auth: state.auth, }); export default connect(mapStateToProps)(PrivateRoute); And if I am logged in on react redux tool my … -
On Heroku getting error: python: can't open file 'manage.py': [Errno 2] No such file or directory
I try to push a Django website to Heroku and run it in a Docker container. After running "git push heroku master", I get the error "python: can't open file 'manage.py': [Errno 2] No such file or directory". If I try to run "git push heroku master", I get "Everything up-to-date". But running anything involving "manage.py" such as "heroku run python manage.py migrate", will get stuck in the "connecting" phase. The following is the content of the "heroku.yml" file: setup: addons: - plan: heroku-postgres build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore.wsgi Link to the project github What can be the problem? -
Multiple focus selectors to dinamically show QuillJS toolbar, is it possible?
I'm using Django's QuillJS version, and what I'm trying to do is display the toolbar of the selected text area only. Using JS it kinda worked: const parentDiv = Array.from(document.getElementsByClassName("django-quill-widget-container")); const toolbar = Array.from(document.getElementsByClassName("ql-toolbar")); const editor = Array.from(document.getElementsByClassName("ql-editor")); for (let i = 0; i < editor.length; i++) { toolbar[i].style.display = "none"; parentDiv[i].style.borderTop = "1px solid #ccc"; editor[i].addEventListener("focusin", function () { toolbar[i].style.display = ""; parentDiv[i].style.borderTop = ""; }); editor[i].addEventListener("focusout", function () { toolbar[i].style.display = "none"; parentDiv[i].style.borderTop = "1px solid #ccc"; }); } The problem is that clicking the toolbar to utilize its features also counts as focusout. So yeah, it doesn't work. Any idea? -
How to chain a multi-feature search in Django
I have a 3 filter search for a job. One is for the job title/decription/company, one for job category for e.g Banking and one for the location for e.g New York How do I chain the query such that it should render me the appropriate results if I specified any one filter and if I specified all 3 it should perform an AND. I tried doing it with if else, but it is becoming too long. Is there another way? Here is my code: views.py if request.method == "POST": internship_desc = request.POST['internship_desc'] internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] results = [] if internship_desc != "" and internship_desc is not None: query_results = Internship.objects.filter( Q(internship_title__icontains=internship_desc) | Q(internship_desc__icontains=internship_desc) | Q(recruiter__company_name__icontains=internship_desc) ) if internship_ind !="" and internship_ind is not None: if internship_desc != "" and internship_desc is not None: query_results = query_results.objects.filter( industry_type__iexact=internship_ind) else: query_results = Internship.objects.filter(industry_type__iexact=internship_ind) if internship_loc !="" and internship_loc is not None: if internship_desc != "" and internship_desc is not None and internship_ind !="" and internship_ind is not None: query_results = query_results.objects.filter( industry_type__iexact=internship_ind) query_results = query_results.objects.filter( recruiter__company_region__iexact=internship_loc) -
Limit the amount of user registration in django
I am newbie in django a I have a question. My system, developed in django, needs to register only the amount of user given in a registration page. How I do to verificate and to limit the amount of registered user? Follow my view: from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.utils.decorators import method_decorator from apps.criarusuario.forms import SignUpForm from apps.cadastro.models import CadastroCliente # table with amount of users to be registered @login_required def signup(request): form = SignUpForm(request.POST) count = CadastroCliente.qtde_usuarios #count the size of registered user if request.method == 'POST': if form.is_valid(): if (CadastroCliente.qtde_usuarios == count): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) else: if (CadastroCliente.qtde_usuarios == count): form = SignUpForm() return render(request, 'criarusuario/signup.html', {'form': form}) Thank you very much! -
How to keep duplicate query set in django
Hello i am new to django and i am stuck in one small problem def doctor_view_appointment(request): apptdoctor=models.Appointment.objects.all().filter(doctorId=request.user.id,status=True) pat_identity=[] for a in apptdoctor: pat_identity.append(a.patientId) print(pat_identity) pat_data=models.Patient.objects.all().filter(status=True,user_id__in=pat_identity) print(pat_data) appt_doctor=zip(apptdoctor,pat_data) data={ 'appt_doctor': appt_doctor, } return render(request,'doctor_view_appointment.html',context=data) In this code the print result of pat_identity is [5, 20, 5] (they are appointmetn id) and the result of pat_data is <QuerySet [<Patient: User1>, <Patient: User2>]> but i need the result <QuerySet [<Patient: User1>, <Patient: User2>,<Patient: User1>]> what should i do for this output -
Django adding sub headings to a form (Failed lookup for key)
I have a model form with lots of options(I removed most of them for this). I would like to add sub headings to make it look better and so its more readable. From my research I couldn't find a definitive way to do it but the few posts I found said to use crispy forms with a helper and multiple field sets. forms.py from crispy_forms.helper import FormHelper class PostForm(ModelForm): class Meta: model = Post fields = 'title', 'manufacture', 'model', 'aspiration', 'image', 'content', def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'MY SubHeading ONE' 'title' 'manufacture' ), Fieldset( 'MY SubHeading TWO' 'model' 'aspiration' 'image' 'content' ) ) if 'manufacture' in self.data: try: model_manufacture_id = int(self.data.get('manufacture')) self.fields['model'].queryset = Models.objects.filter(model_manufacture_id=model_manufacture_id)#.order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['model'].queryset = self.instance.country.city_set#.order_by('name') The if 'manufacture' is for a custom dropdown and is not related along with self.fields['model'].queryset = Models.objects.none() post_form.html <div class="content-section"> <form method="post" enctype="multipart/form-data" id="PostForm" data-models-url="{% url 'ajax' %}" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {% crispy PostForm PostForm.FormHelper %} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> … -
Receive email from the another sender not myself
I use my Gmail account to receive an e-mail when a visitor submits the contact form on my website. This is how I have set the parameters in my views.py: email_from = f'{sender_name} <{sender_email>' email_to = ['myemailaddress@gmail.com', ] send_mail(email_subject, '', email_from, email_to, html_message=html_message) And I receive the email and everything is fine — except that the email is coming from myself (the from is myself) not the name and email address of the person submitted the form as I've set in email_from field. How to fix this? -
How to escape the ? character in django using path
I have a title section for one of my models, and in there, when I add a ? in it, and redirect the page with that URL, it adds an extra / in the URL, and leads me to a 404 Not Found. So my question is: How can I escape this character without having to replace it. Also, the extra requirement is, how can I do this with path()? In the urls.py. I am not using regex for this. Please let me know. Thanks! -
Post default to form django
I have a car rental project, in each DetailView of a car, there is form that allows the user to book the car. My problem is i want to send the car model and brand of the car from where the reservation form was used. Here is my code : models.py : class Car(models.Model): trans = (('Manual','Manual'),('Automatic','Automatic')) Fuel = (('Essence','Essence'),('Diesel','Diesel')) brand = models.CharField(max_length=100, blank=False, null=False) model = models.CharField(max_length=100, blank=False, null=False) Transmission = models.CharField(max_length=100, blank=False, null=False, choices=trans, default='Manual') Seats = models.IntegerField(blank=False, null=False, default= 2) fuel = models.CharField(max_length=100, blank=False, null=False, choices=Fuel, default='Essence') features = models.ManyToManyField('Features',blank=False, null=False, related_name='cars') featured = models.BooleanField(default=False) price = models.IntegerField(blank=False, null=False, default= 0) image = models.ImageField(upload_to="media/carimages/", default=None,blank=True,) thumbnail_image = models.ImageField(upload_to="media/thumbnailcarimages/", default=None, blank=True, null=True) def __str__(self): return self.brand + ' ' + self.model class Reservationform(models.Model): pickup = models.CharField(max_length=50, blank=False) pickup_date = models.CharField(max_length=50, blank=False) pickup_time = models.CharField(max_length=50, blank=False) phone = models.CharField(max_length=50, blank=False) treated = models.BooleanField(default=False) b = models.ForeignKey(Car,on_delete=models.CASCADE, default=Car.brand) m = models.ForeignKey(Car,on_delete=models.CASCADE, default=Car.model) forms.py class ReservationForm(forms.ModelForm): class Meta: model = Reservationform fields = ('pickup','pickup_date','pickup_time','b','m','phone',) widgets ={'pickup': forms.TextInput(attrs={'class': "form-control", 'placeholder': "Aéroport Tunis Carthge"}), 'pickup_date': forms.TextInput(attrs={'class': "form-control","id":"book_pick_date" }), 'pickup_time': forms.TextInput(attrs={'class': "form-control", "id":"time_pick"}), 'b': forms.TextInput(), 'm': forms.TextInput(), 'phone': forms.TextInput(attrs={'class': "form-control", "placeholder": "Your contact number"}), } Views.py : class SingleCar(generic.DetailView, FormMixin): model = Car context_object_name … -
Permission denied error while trying to save image inside Django views
I'm trying to save an image that I'm scraping from IMDB(using bs4) but I'm getting this error: [Errno 13] Permission denied: '/media/Django-Unchained.webp' My code was working fine and I could save the images inside the media directory until I changed some other parts of my code which are completely unrelatable to saving image objects or permissions. When I restarted the server I suddenly faced this error. Why would such a thing happen? Thanks in advance for your ideas on solving this. -
Django urls relation
Whenever I add any '/' in front of the action parameter or after the action parameter then a '?' is always included in the URL. What is the relation between '/' and '?'.It doesn't happen with an anchor tag. <form action="about"> <button type="submit"> hello world </button> -
how to remove html encodings from a string in django
I have used the strip_tags function. It removes tags like "<p>, <b>", etc but things like "&nbsp; &ldquo;" and other html encodings remain. How to remove them ? -
Error getting ManyToMany field from an object
How to execute some functionality, after creating an object in the admin area? I'm trying to use post_save signal and trying to get all objects from my field, which has type ManyToMany, I also use sorting package (sortedm2m). When I save the object I try to output this field, but when I create I get an empty queryset, and when I edit I get the old queryset, without the current changes. class Servers(models.Model): name = models.CharField(max_length=120, default="name") content = SortedManyToManyField(Content) @receiver(post_save, sender=Servers) def create_server(sender, instance, **kwargs): print(instance.content.all()) -
While building a DRF package, unable to import dependencies from Django packages
I am writing a package for reusable APIs and want to later publish it on PyPI. I have already published a basic python package which has a helloworld() to understand how this would work. I have a set of APIs in my DRF app. I moved that app in a my packaging directory of setup.py. Also, I have added external dependencies to the setup.py. setup( name="django_restframework", version="0.0.1", description="Some description", long_description=get_doc(), long_description_content_type="text/markdown", url="https://github.com/some/path.git", py_modules=['manager', 'serizalizer', 'models', 'services', 'tests', 'urls', 'views'], package_dir={'': 'django_restframework_2fa'}, author='Jeet Patel', author_email='********@gmail.com', python_requires='>=3.7', include_package_data=True, zip_safe=False, packages=find_packages( exclude=['tests', 'tests.*', 'licenses', 'requirements']), classifiers=[ "Environment :: Web Environment", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Framework :: Django", "Framework :: Django :: 3.1", "Framework :: Django :: 3.2", 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP', ], install_requires=[ "djangorestframework", "django", "djangorestframework-simplejwt", "pyjwt", "twilio==6.55.0", "djangorestframework-simplejwt==4.6.0", "django-phonenumber-field==5.2.0", "phonenumbers==8.12.24", ], extra_requires={ "dev": [ "pytest>=3.7", "twine 3.4.1", ] } ) Now, I created settings.py in the the app directory and it has this - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'phonenumber_field', 'rest_framework', 'django_restframework_2fa', … -
Why is this django views code not working?
hi I'm having trouble with the image Field in Django forms module, I'm trying to create a form in a website where the users are able to upload images to the database and I'm using Django built in form module to create a form page in the HTML page and once the user upload their data which include some images they would press submit and this should upload it in the backend but for some reason I'm not getting anything can anyone help??? Here is my code: def CreateQueries(request): queryform = QueryForm() if request.method == 'POST': queryform = QueryForm(request.POST, request.FILES) if queryform.is_valid(): title_question = queryform.cleaned_data.get('title') first_question = queryform.cleaned_data.get('Query1') second_question = queryform.cleaned_data.get('Query2') first_image = queryform.cleaned_data.get('Image1') second_image = queryform.cleaned_data.get('Image2') queries = Queries.objects.create( Topic=title_question, Q1=first_question, Q2=second_question, Qimg1=first_image, Qimg2=second_image ) queries.save() print(queries) return render(request, 'Querie/CreateQueries.html', {'form': queryform}) -
Django - Dynamically generating pdf files, storing them, and allowing users to download them in a .zip archive
I made a django app which allows users to complete multiple-choice question tests and saves the given answers to the database. What I would like to do is for the staff to be able to download, for each test created, at the end of it, a zip archive containing a pdf file for each participant, showing their answers to the questions in the test. My first idea was to generate the pdf files and save them to a binary field in a model, but I think creating an actual file would be better and make things smoother for the zip creation too. Problem is, every time I worked with static file management, it was user-uploaded files. I don't know how to dynamically generate and save files inside of a view. This guide explains how to return pdf files as an http response, but what I'm looking for is a way to permanently store them on my server. Is it as easy as just opening a file and saving it or is there anything to be done beyond that? I see django has a File class but I'm still kinda unsure how to go about this and if there are any … -
Create a dataframe from the model
I am writing an application using Django and I ran into a problem. I have models that are as follows: class Feature(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) feature_name = models.CharField(max_length=300) feature_code = models.CharField(max_length=50, unique=True) feature_predictable = models.BooleanField(default=False) def __str__(self): return self.feature_name def breed_name_based_upload_to(instance, filename): return "breeds/{0}/{1}".format(instance.breed_name, filename) class Breed(models.Model): breed_name = models.CharField(max_length=300) breed_features = models.ManyToManyField(Feature) breed_image = models.ImageField(default='no_image.png', upload_to=breed_name_based_upload_to) breed_visible = models.BooleanField(default=True) def __str__(self): return self.breed_name class FeatureValue(models.Model): breed = models.ForeignKey(Breed, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) feature_value = IntegerRangeField(min_value=1, max_value=3, default=1) class Meta: unique_together = ('breed', 'feature') In the 'Feature' model, I have 3 records with feature_code with values for example 'value1', 'value2', 'value3'. In the 'Breed' model I also have 3 records, with each of these records assigned values for each record from the 'Feature' model (I use the FeatureValue model for assigning values). Now I need to use the Breed model to create a DataFrame that would look like this: id breed_name value1 value2 value3 0 name1 2 1 3 1 name2 1 2 2 2 name3 3 3 3 At the moment, using this code: dataframe = pandas.DataFrame().from_records(list( Breed.objects.all().values( 'id', 'breed_name', 'featurevalue__feature_value' ) )) I managed to achieve something like this: id breed_name featurevalue__feature_value 0 name1 2 0 … -
How to run django admin app without media files on local env?
I dont have media files on local machine, how to disable Error FileNotFoundError? Without simulating folder structure in MEDIA.