Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Create and Use New Database for Neo4j Unit Test?
For my Django REST project, I need to perform unit test on my neo4j database to ensure the data outputted is in the correct format. However, I must perform these unit test on a testing database that is different than the actual database. Currently the settings.py is arranged in such a way that the views.py will access the default database. How can I have the Unit test access the test database instead without changing the settings.py? -
What the heck is this programming? [closed]
Firstly I started with java and learnt a bit code and after sometime I say programming career guide videos on Youtube. Someone said C++ is nice or someone said Java and Javascript. Some days later I selected Python for my programming language as it is easy for beginners and can be used in many fields e.g., Machine learning, Web-development, Android or Desktop development and even in hacking (I love Hacking @_@). I started with web-development. I didn't learnt completely and someone other developer said if you want to develop a webapp you'll also have to learn HTML, CSS, Javacript (The language, I hate the most) and also framework like Django. I thought Ohhh..! Ok, What the hell is this. I left taking all tutorials, I was following because of all of that worries, How I'll do this and who'll teach me and stuff like that. After some days I realize its ok man you can do it. I started again and after facing many problems as learnt all from Youtube because I don't have enough money to buy courses. Now with the thank of GOD, I created a web app using Django, HTML, CSS and a little bit of JS … -
How can I pass a string into a the .close() method of the FileResponse object?
I am altering the behavior of the .close() method of the FileResponse object. FileResponse is a subclass of StreamingHttpResponse which is very similar to the HttpResponse object. What I am trying to do is take a string of text, save it into a .docx, send that docx to the browser, then delete that docx. Everything is working great until I try to delete the .docx. It doesn't look like I can delete the file before the response is sent because the response needs the file, but I can't do anything at all after the response has been sent because the view has completed its task and sent a response. A potential solution I have found is to modify the .close() method of the FileResponse object (similar to the HttpResponse object) to delete the file. Great. However, I do not know how to pass the path to the file to the .close() method. This might be an elementary question, but I generally avoid editing built in class methods. Code below. import logging from django.http import FileResponse import os logger = logging.getLogger("django") #editing the default closing behavior of the file response object to delete the file that it just sent. class SendAndDeleteExport(FileResponse): … -
Django Python Makemigrations and Runserver do Nothing
I downloaded a .zip template from github of a blog web app built in django and am trying to deploy it to my local server... I have tried running the following lines in my command line, but am not getting any response back... nothing happens except that it just moves to the next line. Any idea why this is occurring? I am able to create a new project using django, I am able to install requirements via command line, and I can run other python scripts fine. C:\Users\xxx>cd C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master>python manage.py runserver 8080 C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master>python manage.py makemigrations C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master>python manage.py migrate C:\Users\xxx\Desktop\Python\Django\Blog\django-diy-blog-master> -
Django Cors Headers settings not working with vue and axios
This is my settings.py CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8000", "http://192.168.225.206:8080" ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES' : ( 'rest_framework.permissions.IsAuthenticated', ) } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'apps.client', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] at least where rest_framework is set. This is my main.js from <vue_project>/src import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import axios from '../node_modules/axios' axios.defaults.baseURL = 'http://127.0.0.1:8000' createApp(App).use(store).use(router, axios).mount('#app') But when I tried this code which is clients.vue <script> import axios from 'axios' export default { name: 'Clients', data(){ return { clients: [] } }, mounted(){ this.getClients(); }, methods: { getClients(){ axios.get('/api/v1/clients/') .then(response => { const token = response.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common["Authorization"] = "Token" + token localStorage.setItem("token", token) for(let i = 0; i < response.data.length; i++){ this.clients.push(response.data[i]) } }) .catch(error => { console.log(JSON.stringify(error)) }) } } } </script> I get a Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1/clients/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authoriaxation is not allowed by Access-Control-Allow-Headers in preflight response. Then I checked if I get the same … -
Deploying Django App on Heroku. While Pushing the App on heroku it gives the error
My Django App working well in localhost, but when I am pushing it on the Heroku by using the Git Bash terminal, the following error is shown. What is GCC?. Why these errors are showing up while deploying it on Heroku. Is there any library missing? remote: Building wheel for pyyaml (setup.py): started remote: Building wheel for pyyaml (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-qb9qpcl0/pyyaml/setup.py'"'"'; __file__='"'"'/tmp/pip-install-qb9qpcl0/pyyaml/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-s5u8j4v7 remote: In file included from /app/.heroku/python/include/python3.9/unicodeobject.h:1026, remote: from /app/.heroku/python/include/python3.9/Python.h:106, remote: from ext/_yaml.c:4: remote: /app/.heroku/python/include/python3.9/cpython/unicodeobject.h:446:26: note: declared here remote: 446 | static inline Py_ssize_t _PyUnicode_get_wstr_length(PyObject *op) { remote: | ^~~~~~~~~~~~~~~~~~~~~~~~~~ remote: error: command '/usr/bin/gcc' failed with exit code 1 remote: ---------------------------------------- remote: ERROR: Failed building wheel for pyyaml remote: Running setup.py clean for pyyaml remote: Building wheel for strict-rfc3339 (setup.py): started remote: Building wheel for strict-rfc3339 (setup.py): finished with status 'done' remote: Created wheel for strict-rfc3339: filename=strict_rfc3339-0.7-py3-none-any.whl size=18119 sha256=169b25d50478fa157faaa6b19e8714b42c42c771ca6926bb2d728a8fe20e9be8 remote: Stored in directory: /tmp/pip-ephem-wheel-cache-wyzbci7g/wheels/25/38/74/7ec7f77ec64b2907430120931ba588b40e6e26f02d4df5be35 remote: Building wheel for Kivy-Garden (setup.py): started remote: Building wheel for Kivy-Garden (setup.py): finished with status 'done' remote: Created wheel for Kivy-Garden: filename=Kivy_Garden-0.1.4-py3-none-any.whl size=4532 … -
trying to run django server but ip and port is not showing up after this statement
python manage.py runserver Watching for file changes with StatReloader it is a projext ive downloaded from my git acconunt -
Creating User using Djoser is not storing data for all fields (
I am using DRF to create a ReST API. I am using Djoser for user management. I am using the default django user model as it serves my purpose. When I hit the endpoint to register new user, only username, password and email are getting stored. I am passing all data like first_name, last_name and is_staff but only username, password and email are being stored. I have attached Djsoer settings. DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'USER_CREATE_PASSWORD_RETYPE': True, #Designed to propote good programming practice 'SET_PASSWORD_RETYPE': True, #Designed to propote good programming practice 'PASSWORD_RESET_CONFIRM_RETYPE': True, #Designed to propote good programming practice 'LOGOUT_ON_PASSWORD_CHANGE' : True, #Note : Logout only works with token based authentication. djoser 2.10 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system 'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system 'token': 'djoser.serializers.TokenSerializer', 'token_create': 'djoser.serializers.TokenCreateSerializer', } What I am doing wrong? -
Django nested if statement giving me a strange error
I have 2 if statements right next to each other to check for to see if a user is following another user. I am getting a weird error when I attempt to close both of the if statements. I have a block content and endblock at the top and bottom of the page. I also have a load humanize tag. I have attempted to add a endblock tag and I tried reshuffling things around. I am kinda stuck but I know I'm forgetting something. Can any help me out? Here is the code <h1 class="title">{{ request.user.username }}</h1> <p>Followers: {{ user.foxyprofile.followed_by.count }}</p> <p>Follows {{ user.foxyprofile.follows.count }}</p> {% if user != request.user %} {% if request.user.foxyprofile in user.foxyprofile.followed_by.all %} <a href="{% url 'unfollow_foxy' user.username %}" class="button is-danger">Unfollow</a> {% else %} <a href="{% url 'follow_foxy' user.username %}" class="button is-success">Follow {{ user.username}}</a> {% endif %} {% endif %} and the error I'm getting... Invalid block tag on line 17: 'endif', expected 'endblock'. Did you forget to register or load this tag? -
I need to separate my main App from celery, in different servers. How could i achieve this goal?
Today i have a AWS EC2 instance where i run my main App (Django). I'm using docker to containerize my services, which are: Django, Nginx, Mysql, Redis, Celery. I now that all those services in one instance is the wrong path to follow and i want to make things right. I would like to start by separating the workers from my main App, because the App consumes a lot of processing in some tasks and i want to isolate those tasks from main App, in another server. Let's call it of Server B. How could i achieve this, using a Server A, running the main App, and Server B, handling i/o bound tasks with celery? Did i was clear? Sorry about my english. -
Why the content of my object disappeares when I submit the form instead of being saved in the database?
I'm trying to create a tweeter app using Django3.2 and Python3.9 and I stumble upon a difficult problem to solve. When I try to save a tweet, it's content disappear. If I manually save the content of a tweet using the Python shell directly, the content is saved properly. However, if I submit the tweet from the /home page or from the /create-tweet/, the id is created but with an empty content. It is not saved in the db.sqlite3 database neither. So it seems that the form is not being submitted properly but I can't figure out why exactly? my file structure is the following: tweeterapp ┣ db.sqlite3 ┣ manage.py ┣ templates ┣ components ┃ ┣ footer.html ┃ ┣ form.html ┃ ┗ navbar.html ┣ pages ┃ ┗ home.html ┣ tweets ┗ base.html ┣ tweeterapp ┣ settings.py ┣ urls.py ┣ wsgi.py ┗ __init__.py ┣ tweets ┣ migrations ┣ admin.py ┣ apps.py ┣ form.py ┣ models.py ┣ tests.py ┣ views.py ┗ __init__.py form.hmtl: <form method='POST'>{% csrf_token %} {{ form.as_p }} <button type='submit' class='btn btn-secondary'>Save</button> </form> home.html: {% extends 'base.html' %} {% block head_title %} Test {% endblock head_title %} {% block content %} <div class='row text-center'> <div class='col'> <h1> Welcome to the … -
How to alter Django widget validation behavior for conditionally required fields?
I have a mixed set of formsets. Let's say that I have formsets A and B, and that there are 3 full forms of type A and 2 full forms of type B all in the same html form. All formsets are submitted (because I want to save all entries), but only one set of formsets is ever validated. I have it all worked out, except for the display of {{ forms.A.errors.val }}. The val field is a TextInput field that is required based on a javascript-created select list at the top where they choose to search using formsets A or B. If they choose A, the forms of formset A are shown and B are hidden. Both are submitted because I want them to be able to switch to their previous entries in formset B when the results are presented. The problem is that when they switch to formset B after seeing the results of the search using A, the "This field is required." error is shown next to any empty val fields. I thought that I'd successfully avoided that field validation... I have tried multiple means of preventing that error from displaying. I tried overriding clean to only … -
populate django database, txt or CSV file
How to populate django database, with txt(delimited by "|") or CSV file? From admin panel on site? the customer asked to make it so that he could replenish the site database, txt document or CSV table -
I can't make a single project in django in my vs code after installing all the extensions
enter image description here I have installed python extension as well as installed django also in my VS code still I can't make any project in it.It's showing the following error -
i want to know how to use models id to fetch the right data in django
i create two model name subject and section so what i want for user is if a user click on a subject only the section related to that subject open up but it opens all the section of all the subject no matter which subject link you are clicking i hope you get it here is my models.py class Subject(models.Model): name = models.CharField(max_length=80, blank=False,) thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False) about = models.TextField(default='SectionWise' ) total_Section = models.FloatField(default='100') joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Section(models.Model): subject = models.OneToOneField(Subject, on_delete=models.CASCADE) sub_section = models.CharField(max_length=500, blank=True) title = models.CharField(max_length=5000, blank=False) teacher = models.CharField(max_length=500, blank=False) file = models.FileField(upload_to='section_vedios', blank=False) about_section = models.TextField(blank=False, default=None) price = models.FloatField(blank=False) content_duration = models.DurationField(blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject.name my views.py for sections @login_required def sections(request): section_list = Section.objects.all() return render (request, 'sections.html', {'section_list': section_li my html code for viewing section acc to click of subjects <div> {% for section in section_list %} <li class="sub"> <a name='thumb' class="thumb" href="#"> <span><strong> {{ section.title }} </strong> </span> </a> <p>Name: {{ subject.section.teacher }} </p> {{ subject.section.price }} </li> </div> {% endfor %} my html for viewing subject in template {% for subject … -
How to change template in Django class based view
If i have a class based view like: class equipmentdashboardView(LoginRequiredMixin,ListView): context_object_name = 'equipmentdashboard' template_name = 'equipmentdashboard.html' login_url = 'login' def get_queryset(self): #some stuff How can I change the template name depending on a query? I want to do something like: class equipmentdashboardView(LoginRequiredMixin,ListView): context_object_name = 'equipmentdashboard' if self.request.user.PSScustomer.customerName == 'Customer X': template_name = 'equipmentdashboard_TL.html' else: template_name = 'equipmentdashboard.html' login_url = 'login' def get_queryset(self): #some stuff But you can't access the request before the get_queryset. Or maybe there is an even simpler way of achieving the same behavior? -
Where does my django signals look for a missing argument Created in the createprofile function?
I am using django signals to create a profile after a user is created but I get this wird error telling that the create profile function is missing the created argument I even tried without a decorator but It didn't work. I don't know what I am missing. here is the model and the signal itself. class Profile(models.Model): user = models.OneToOneField( User, verbose_name="user", related_name="profile", on_delete=models.CASCADE ) full_name = models.CharField(max_length=150, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) bio = models.TextField() location = models.CharField(max_length=100, blank=True, null=True) picture = models.ImageField( default="media/profile_pics/default.jpg", upload_to="media/profile_pics" ) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username}'s profile" @receiver(pre_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(pre_save, sender=User) def create_profile(sender, instance, **kwargs): instance.profile.save() And I am using django allauth for the authentication and authorization. Here is the the error from the terminal File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\allauth\account\adapter.py", line 246, in save_user user.save() File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\base.py", line 750, in save_base pre_save.send( File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) TypeError: create_profile() missing 1 required positional argument: 'created' [09/Jul/2021 18:54:00] "POST /accounts/signup/ HTTP/1.1" 500 136997 -
Static files not served when using docker + django + nginx
I am trying to dockerize a django project and use nginx to serve static files. Everything seems to be working except the static files are not served. When I go to the admin page, always get Not Found: /django_static/rest_framework/css/prettify.css for files in django_static folder. folder structure: backend server apps django_static media ... docker backend Dockerfile wsgi-entrypoint.sh nginx production default.conf development default.conf Dockerfile Here is my docker-compose: services: nginx: build: ./docker/nginx ports: - 1234:80 volumes: - ./docker/nginx/production:/etc/nginx/conf.d - django_static:/app/backend/server/django_static - media:/app/backend/server/media depends_on: - backend restart: "on-failure" backend: build: context: . dockerfile: ./docker/backend/Dockerfile entrypoint: /app/docker/backend/wsgi-entrypoint.sh ports: - "8001:8001" volumes: - django_static:/app/backend/server/django_static - media:/app/backend/server/media expose: - 8001 volumes: django_static: media: dockerfile for django: FROM python:3.7-slim WORKDIR /app ADD ./backend/requirements.txt /app/backend/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN pip install gunicorn RUN pip install -r backend/requirements.txt ADD ./backend /app/backend ADD ./docker /app/docker wsgi-entrypoint.py #!/bin/sh until cd /app/backend/server do echo "Waiting for server volume..." done until ./manage.py migrate do echo "Waiting for db to be ready..." sleep 2 done ./manage.py collectstatic --noinput gunicorn server.wsgi --bind 0.0.0.0:8001 --workers 1 --threads 1 #./manage.py runserver 0.0.0.0:8003 nginx docker file: FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf CMD ["nginx", "-g", "daemon off;"] nginx config file: server … -
Why I get an operational error even I migrate
I'm building a blog with django and I tried to add new field to models.And also I makemigrations and migrate to database.And also I tried many other things like these stackoverflow,stackoverflow question 2 But I finally got a operational error. from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = RichTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title -
Error: <circle> attribute r: Expected length, "NaN" for d3js bubble chart
I am using a jsonresponse from a django backend to create a bubble chart. The data is reaching the script properly but the chart is not showing as there is an issue with one of the attributes. Here's the code: <script type="text/javascript"> dataarr = d3.json("{% url 'find_arr'%}", function(dataarr){ dataarr.forEach(function(d){ console.log(d) }) }) dataset = { "children": dataarr }; var diameter = 600; var color = d3.scaleOrdinal(d3.schemeCategory20); var bubble = d3.pack(dataset) .size([diameter, diameter]) .padding(1.5); var svg = d3.select("body") .append("svg") .attr("width", diameter) .attr("height", diameter) .attr("class", "bubble"); var nodes = d3.hierarchy(dataset) .sum(function(d) { return d.Count; }); var node = svg.selectAll(".node") .data(bubble(nodes).descendants()) .enter() .filter(function(d){ return !d.children }) .append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); node.append("title") .text(function(d) { return d.Name + ": " + d.Count; }); node.append("circle") .attr("r", function(d) { return d.r; }) .style("fill", function(d,i) { return color(i); }); node.append("text") .attr("dy", ".2em") .style("text-anchor", "middle") .text(function(d) { // return d.Name.substring(0, d.r / 3); return d.Name; }) .attr("font-family", "sans-serif") .attr("font-size", function(d){ return d.r/5; }) .attr("fill", "white"); node.append("text") .attr("dy", "1.3em") .style("text-anchor", "middle") .text(function(d) { return d.Count; }) .attr("font-family", "Gill Sans", "Gill Sans MT") .attr("font-size", function(d){ return d.r/5; }) .attr("fill", "white"); d3.select(self.frameElement) .style("height", diameter + "px"); </script> The console … -
Http Error 500 Django on Ubuntu server 20.04
I build a django app that later deploys to ubuntu 20.04 server (office's private server) and i using Apache2 as web-server. I update all settings such as WSGI and etc and enable conf file i just updated. I try to run manage.py runserver 0.0.0.0:8000 and access it via browser ipaddress:8000 and it works just fine. But i can't access with just ipaddress only, it throw an Internal Server Error (500). before that, i follow this tutorial to set up apache2 server before deploying my django app. Any idea what i missed? -
How do I keep a list of 100 secret keys safe on heroku (django), to be given out only to people with a secret link/password?
I have 100 signed messages that I want to give out to people on twitter randomly. So I want to be able to give them a password or a link on twitter, and then when they enter that password or click that link they get one specific secret key from my website. Obviously if that link leaks then it's fair game for anyone, but each link would only give them access to one secret signed message. Where can I store this? I wanted to store it in a static file and then serve it to complex urls. Like if they go to mywebsite/123SatoshiGoodPassword or whatever, it gives them the 4th secret signed message, and if they go to mywebsite/928VitalikGoodPassword it gives them the 12th secret signed message. (I'm doing this so they can submit an ethereum transaction for a free mint of a token or whatever by the way. They can copy the signed message to send with their transaction or I can use the link to prompt them to submit it on their own. I already have that part worked out.) I don't really want to mess with database stuff as I'm new at all of this. I was … -
How to best submit multiple Django formset_factory forms at once?
This is probably too broad/complex of a question for stack, but I had to go through the process of asking this to clarify my thoughts. I'm very open to suggestions on how to break it up or narrow it down. ATM, I'm not sure how to do that without all this context... I'm fairly new to Django, and I just finished a proof of concept advanced search page that took 2 weeks for me to get working how I want - and it works (pretty well, in fact), but it's really kludgey, and now that I have the proof of concept working, I'm interested in learning how to do it properly, and am looking for suggestions on how to refactor this to make it more straightforward. To summarize the functionality, the interface allows the creation of a complex search query using a dynamic hierarchical form. It does this (currently) for 1 of 2 output formats (which is effectively results in the rendering of a join of 5 or 6 tables in the model, depending on the selected output format), but it submits all the hierarchies and performs the search on the selected one. Here's a gif demo of the interface, … -
media file not found in a simple django-admin application
I have seen many questions here regarding media files in Django, but honestly I can't find a valid solution for my problem. So I have decided to streamline the environment to a very simple application. You can find it here: github project I have created a project with django-admin and I called 'documents' and then I have created an app called 'docs'. Then I defined a simple class: def get_path(instance, filename): fn, ext = os.path.splitext(filename) ts = str(int(time.time())) return os.path.join('{}_{}{}'.format(fn, ts, ext)) class doc(models.Model): doc_name = models.CharField(max_length=30, verbose_name=u"doc name", help_text=u"name of the doc") doc_document = models.FileField(upload_to=get_path, verbose_name=u"document", help_text=u"document") class Meta: unique_together = ("doc_name", ) def __str__(self): return f"{self.doc_name}" This changes the filename and it adds a timestamp. I also changed the urls.py file adding the following: path(r'', admin.site.urls), Now the question is: without using MEDIA_URL and MEDIA_ROOT is it possible to make this working? I have tried to add a files and it works: and it properly save the file in the root of the project. But when I go to the link and click I am getting the following: Now is it possible to know where is it looking for the file? Do you think that adding MEDIA_URL and … -
django deployment crashed with error code H10 (heroku)
After a lot of tries I was finally able to deploy my django app on heroku, but it gave me application error. I tried logging error it was - 2021-07-09T15:43:59.937940+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=examtaker-001.herokuapp.com request_id=b3758753-7826-49b6-b22d- c5b1aba1b903 fwd="223.233.68.190" dyno= connect= service= status=503 bytes= protocol=https 2021-07-09T15:44:00.824183+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=examtaker-001.herokuapp.com request_id=8085f766-548e-4dde- 852f-8ae40db54afa fwd="223.233.68.190" dyno= connect= service= status=503 bytes= protocol=https I dont really know where the problem is, Exam- Exam- settings.py urls.py wsgi.py main- migrations static- js css admin.py urls.py views.py apps.py templates- index.html manage.py Procfile requirements.txt This is my directory. Inside my Procfile - web: gunicorn Exam.wsgi --log-file- In settings.py - import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['examtaker-001.herokuapp.com', '127.0.0.1'] MIDDLEWARE = [ #other defaults 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' django_heroku.settings(locals()) Rest most of the things remain default. Not sure but I think problem is with BASE_DIR. Any help would be appreciated.