Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django deployment, how change path of uploaded images by admin
I am trying to deploy my site to pythonanywhere and everything works fine except image saving from admin panel. In my local env everything works fine and uploaded images land in static folder, but on pythonanewhere they are saved in different loaction. That's my code and configs: models.py def generate_filename(self, filename): url = "static/galeria/rosliny/%d/%s" % (int(self.nazwa_polska.id_rosliny), filename) return url image = models.ImageField(max_length=255, upload_to=generate_filename) my web urls configuartion for static(pythonanewhere): /static/ - /home/pepikfest/zielnik_karpacki/static files are saving into /home/pepikfes/static/, they misses zielnik_karpacki foler, what I doing wrong? Please help :/ -
My Database model is not showing in admin view
admin view is not showing models.And yes, I am totally new to django. And I am totally new to this site. models.py ----> from django.db import models PUBLISH_CHOICES = ( ('draft','Draft'), ('publish','Publish'), ('private','Private'), ) app_name = 'Blog' class Blog(models.Model): id = models.BigAutoField(primary_key = True) title = models.CharField(max_length = 200) body = models.CharField(max_length = 500, null = True) publish = models.CharField(max_length = 120, choices = PUBLISH_CHOICES, default = 'draft') settings.py ----> INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' Database https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Django: Generating form & passing data
I spend my Sunday on this, but I am still not where I need it to be. What I want to do: Ticketing shop, with ticket data received from the ticket model. The visitor can choose the quantity of different kind of tickets and is then being passed to the checkout form. The challenge: I can't just create a simple form, as the form is depended on ticket model. Therefore I have to combine the ticket model data with a selection for quantity. What's next (after clicking on "Checkout"): I will save this data in a checkout model with a unique cart_id and an entry model with ticket_id, quantity and cart_id(foreign key). The checkout view will then get the ticket data from the ticket model and the quantity from the entry model. Through that, I can calculate total amount etc. Where I need your help: I have problems with creating the form. In know how to save data in the database, but I don't get the data into formset.is_valid() I hope you can help me solving this. Thank you in advance. models.py from django.db import models # Create your models here. class Ticket(models.Model): description = models.TextField() name = models.CharField(max_length=120) price_gross … -
Django Setting up a test from a populated database?
I've been running most of my unit tests from fresh instances of my model, however I would now like to test on my populated model as it's non-trivial to repopulate my database. Is this possible? I'm struggling to find documentation on the subject. Currently using the code: def setUpTestData(cls): create test data for model 1 create test data for model 2 def tests run some tests -
Django React Axios
I am trying to make a post request to a Django server using React with Axios. However, I am getting a redirect 302 on the server side. Just followed all suggestions in this post here CSRF with Django, React+Redux using Axios unsuccessfully :( However, what I have done so far is the following: Sat the default axios CookieName and HeaderName (on the javascript side): axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "XCSRF-Token"; Got this in settings.py as well: CSRF_COOKIE_NAME = "XCSRF-Token" And here is how the post request looks like: axios( { method: 'post', url: `/api/${selectedEntryType}_entry`, data: { "test": "test" }, headers: { 'X-CSRFToken': document.cookie.split('=')[1], 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json', } } ) Another thing that I have tried is to make the post request from the Django rest api UI: and it does work successfully. The only differences in the Request Headers when I make the request from the UI and from JS are: Accept, Content-Length, and Referer, which I don't see how could they be problematic. Please help. -
Django's password_reset keeps returning error
I'm trying to use Django's built in password_reset view, and so far I followed a small tutorial, but in my case, and as I found out, also many other people's, it doesn't work, and everytime I access the specific url, it returns: "Reverse for 'reset_password' not found. 'reset_password' is not a valid view function or pattern name.". I looked for all kinds of solutions, but the only one that actually worked was to move the urls with password_reset and password_reset_confirm to the main urls.py, instead of the one in my subdirectory. Still, if I access the url "raw", aka just typing it instead of rendering the page through link and all, it does indeed work, but If I try to access it through some actual link, it returns the very same error I got from the start. In my main/urls.py : url(r'^reset_password/$', password_reset, name='password_reset'), url(r'^reset_password/done/$', password_reset_done, name='password_reset_done'), ^This one doesn't work in any way, it just returns that error. I checked for possible typos or bad declaration, but it is alright. Like I said, if I take these two urls and put them in urls.py instead of main/urls.py, it does work. But then I tried to implement a link in … -
Loop to render Django view context as table in the template
I want to pass the following dictionary as context to Django template: context = {'prices': prices, 'listings_links': listings_links, 'listings_names': listings_names, 'photo_links': photo_links} The dictionary's values are lists. In the template I want to display those lists as columns in HTML table. However I am not sure how to further develop the following skeleton table code: <table> <tr> <th>Price</th> <th>Link</th> <th>Listing name</th> <th>Photo link</th> </tr> {% for loop start here? %} <tr> <td> {{prices[0] }} </th> <td> {{ listings_links[0] }} </th> <td> {{ listings_names[0] }} </th> <td> {{ photo_links[0] }} </th> </tr> #next rows go here... {% endfor %} </table> -
How can I write a method only used POST or GET?
I wanna divide the program in the case of POST and GET.I am using wide use view in urls.py from django.urls import path from . import views urlpatterns = [ path('top/', views.TopViews.as_view({ 'get': 'getdata', 'post': 'postdata' })), ] in views.py class TopViews(viewsets.ModelViewSet): #what should I write here? I used method like def test():, in that case I think it is ok that decorator like @require_POST is added.But in this case,I am using wide use view, so I really cannot understand how I can write it.How can I write it? -
Switching between templates displayed in Django
I'm beginning to work on a Django application. I'd like to have two different views which switch dynamically when the user clicks on one of the tabs on the screen. Here is essentially what I have: base.html: <head> <script type="text/javascript" src="/static/base.js"></script> </head> <body> <div class="tab"> <button class="tablinks" onclick="changeTab(event, 'teams')">Teams</button> <button class="tablinks" onclick="changeTab(event, 'scenarios')">Scenarios</button> </div> <div class="content container"> <div class="tab-options"> <div class="teams-tab" id="teams-tab"> {% block teams %} {% endblock %} </div> <div class="scenarios-tab" id="scenarios-tab"> {% block scenarios %} {% endblock %} </div> </div> </div> </body> teams.html: {% extends "./base.html" %} {% block teams %} <body> <form action="{% url 'webapp:results' %}" method="get"> <h1>You are on the teams page!</h1> <input type="submit" name="submit" value="Get Results!"><br> </form> </body> {% endblock %} index.html: {% extends "./base.html" %} {% block scenarios %} <body> <form action="{% url 'webapp:results' %}" method="get"> <h1>You are on the scenarios page!</h1> <input type="submit" name="submit" value="Get Results!"><br> </form> </body> {% endblock %} base.js: function changeTab(event, tab) { tabcontent = document.getElementsByClassName("tab-options"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } if (tab == "teams") { document.getElementById("teams-tab").style.display = "block" } else if (tab == "scenarios") { document.getElementById("scenarios-tab").style.display = "block" } } Unfortunately, this doesn't seem to be working. When the page initially … -
In Django, how to save queried object with datetime attribute?
I'm able to save other attributes of a queried object but not time. Am I missing something with q.edited_datetime = timezone.now()? q = SomeObject.object.get(id=3) q.title = 'New Title' q.edited_datetime = timezone.now() q.save() In models: edited_datetime = models.DateTimeField(blank=True, null=True, default=None) That's basically the code I'm using. timezone.now() works if I create the object. -
Updating Django static files to Pythonanywhere seemed to work, but website not showing (Djangogirls Tutorial)
I am very new with Django, PythonAnywhere and coding in general. But I tried to make the question as clear as possible. Here is my problem: I'm trying to learn Django, and I got stuck with one of the final steps of this tutorial: https://tutorial.djangogirls.org/en/extend_your_application/ From the part where it says "Updating the static files to the server" (Scroll down in the link) Everything works fine on my localhost, but it doesn't work on PythonAnywhere. The website is not showing. I've searched on stackoverflow (and on the web) for similar questions, but either the questions/answers are so sophisticated that I can't follow them, or the solutions point to things that I think are already in place, and aren't the solution to my problem. In the PythonAnywhere Bash Console: 13:04 ~ $ cd futuristfuturist.pythonanywhere.com 11:51 ~/futuristfuturist.pythonanywhere.com (master)$ git pull remote: Counting objects: 13, done. remote: Compressing objects: 100% (7/7), done. remote: Total 13 (delta 3), reused 13 (delta 3), pack-reused 0 Unpacking objects: 100% (13/13), done. From https://github.com/futuristfuturist/my-first-blog f2a6cd4..2293337 master -> origin/master Updating f2a6cd4..2293337 Fast-forward blog/static/css/blog.css | 55 ++++++++++++++++++++++++++++++++++++++ +++ blog/templates/blog/base.html | 23 +++++++++++++++++ blog/templates/blog/post_detail.html | 13 ++++++++++ blog/templates/blog/post_list.html | 37 +++++++++------------------ blog/urls.py | 3 ++- blog/views.py | 5 ++++ 6 … -
Django schedule - rely on database or google
So i´m working on a project for university. Basically what i do is writing a website where one can add entries to a calendar which are stored in a google calendar. Therefore the website calender needs access to google to read entries and write new ones. At first the idea was to use google so theres no need to care about where/ how to store data. Now that i started working on it i noticed that django has a lot of calendar modules so now i´m wondering wether there are any pros and cons to using google as a "storage" or storing it myself? I will use google calendar either way because my tutor want the syncronisation between web calendar and google calendar. Thanks for your help =) -
jquery. attr changing url paramet of tag a
I want to change tag a attribute href with jquery but result was not so good than i expected. Problem in that when i change href attribute with attr: $('#doc-menu > li > a').attr('href', '/?child=False'); $('#doc-menu > li > a + ul > li > a').attr('href', '/?child=True') Url cleaning fully. But before query ?child=True i have another django url. <a href="{% url 'docs:nodes_detail' node.id %}" class="parent">{{ node.name }}</a> After this django url should be jquery query. I need url like so 35/?child=True like so But now i have fully cleaned url /?child=True Is there anyway to find solution? Thanks -
Optimize query without distinct
I would like to optimize query without distinct=True. How can I do it? Please help me! )) (Company.objects .filter(visible=True) .annotate(count_users=Count('usercompany', distinct=True)) .annotate(count_vacancy=Count('vacancy', distinct=True)).annotate(count_active_vacancy=Count(Case(When(vacancy__status='In work', then=1)), distinct=True))) -
Django - How to sync model changes with database
I added some Fields to My User Model , then I executed python manage.py makemigrations . it showed me : No changes detected I Searched and found some solutions like : python manage.py migrate --run-syncdb python manage.py makemigrations app_name python manage.py sqlmigrate app_name BUT none of them worked. -
django url how to use questions mark? (class based views)
in my URL for the createview, I want there to be a '?', from where I can pass an argument to the nect page. I am using class based views. For example: www.site.com/appname/appointment/add/?Name=1 And my HTML would be: href={% url 'People:appointment-create' Patient.id %} Currently my URL is like so: re_path(r'appointment/add/$', views.appointmentCreate.as_view(), name='appointment-create'), and my view is: class appointmentCreate(LoginRequiredMixin, CreateView): model = appointment form_class = AppointmentForm def get_initial(self): patient = self.request.GET.get('patient') return { 'Patient': patient, } How would i go about doing this? -
Docker --build-arg env vars not passing at build time
I'm passing env vars at build, but they don't seem to be working. Am I using this incorrectly? The command I'm passing is docker build -f Dockerfile.django --build-arg DJANGO_AWS_ACCESS_KEY_ID=AMKSDFHOSJAODFJ#F@OM . And I'm being returned: /usr/local/lib/python3.6/site-packages/environ/environ.py:422: UserWarning: Engine not recognized from url: {'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''} warnings.warn("Engine not recognized from url: {0}".format(config)) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/environ/environ.py", line 271, in get_value value = self.ENVIRON[var] File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'DJANGO_AWS_ACCESS_KEY_ID' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 194, in fetch_command settings.INSTALLED_APPS File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, … -
styling form render in Django
I'm using Django 2.x I'm using Formset to be able to add multiple records at one. the form is rendered in template file as {{ chapter_questions.as_table }} Which renders template like below which looks ugly. I'm using Bootstrap template to design my template to look like To render template like second image, I'm writing the fields manually as <div class="form-group"> <div class="col-sm-12 col-xs-12"> <label for="question">Word</label> <input name="chapterquestion_set-0-word" type="text" class="form-control border-color-2" placeholder="Word" id="question"> {% if chapterquestion_set.word.errors %} <div class="row"> <div class="col-sm-12"> <div class="alert alert-danger"> <ul> {% for error in chapter_questions.word.errors %} <li>{{ error }}</li> {% endfor %} </ul> </div> </div> </div> {% endif %} </div> <div class="col-sm-12 col-xs-12"> <label for="definition">Definition</label> <input name="chapterquestion_set-0-definition" type="text" class="form-control border-color-3" placeholder="Definition" id="definition"> {% if chapter_questions.definition.errors %} <div class="row"> <div class="col-sm-12"> <div class="alert alert-danger"> <ul> {% for error in chapter_questions.definition.errors %} <li>{{ error }}</li> {% endfor %} </ul> </div> </div> </div> {% endif %} </div> <div class="col-sm-12 col-xs-12"> <label for="audio"></label> <input name="chapterquestion_set-0-audio" type="text" class="form-control border-color-4" placeholder="Audio" id="audio"> {% if chapter_questions.audio.errors %} <div class="row"> <div class="col-sm-12"> <div class="alert alert-danger"> <ul> {% for error in chapter_questions.audio.errors %} <li>{{ error }}</li> {% endfor %} </ul> </div> </div> </div> {% endif %} </div> </div> This way I have to write the … -
Django : Why should I add package name inside INSTALLED_APPS?
In Djano, why should I add third-party package names inside the INSTALLED_APPS for some packages such as django-filter, DRF, debug-toolbar etc, while I don't want to add for some packages such as Celery, Requests etc ? I couldn't figure out why should add them to a specific list, even though they all are similar pip packages and I installed them in the same way. Thanks in advance! -
NoReverseMatch at /polls/top/ Why does such a error happens?
I got an error,NoReverseMatch at /polls/top/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/top/<int:pk>/'] . I wrote in views.py from django.shortcuts import render from .models import Polls def top(request): data = Polls.objects.order_by('-created_at') return render(request,'index.html',{'data':data}) def detail(request): data = Polls.objects.order_by('-created_at') return render(request,'detail.html',{'data':data}) in child app's urls.py from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'app' urlpatterns=[ url('top/', views.top, name='top'), url('detail/<int:pk>/', views.top,name='detail'), ] in parent app's urls.py from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url('admin/', admin.site.urls), url('polls/', include('polls.urls')), ] in index.html <main> {% for item in data %} <h2>{{ item.title }}</h2> <a href="{% url 'polls:detail' item.pk %}">SHOW DETAIL </a> {% endfor %} </main> When I access top method, the error happens.I really cannot understand why I cannot access item.pk.I rewrote pk,but same error happens.What is wrong in my code?How should I fix this? -
from adaptor.model import CsvModel
I am trying to use the CsvModel module from django-adaptors. However, when i use from adaptor.model import CsvModel and makemigrations, below errors occured. Can anyone advise the reason why? my code in the model is as follows: from django.db import models from adaptor.model import CsvModel from adaptor.fields import CharField, DecimalField class User(models.Model): user_name = models.CharField(max_length = 50, null=True, unique=True) def __str__(self): return self.user_name class Profile(models.Model): rubbish = models.DecimalField(max_digits= 1000, decimal_places=3, null=True) user = models.CharField(max_length = 50, unique = True, null=True) hobby = models.CharField(max_length = 50, null=True) job = models.CharField(max_length = 60, null=True) class Trial(CsvModel): rubbish = DecimalField() user = CharField() hobby = CharField() class Meta: dbmodel = Profile delimiter = ',' has_header = True Error message is as follows: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in … -
How to combine a custom date and time field in djano?
I'm looking for a way to combine a custom date value and a time field in django. My model only contains a time field. Now I have to annotate a new field combining a custom date and the time field. I thought the following code will solve my problem, but it only gives the date value. TimeField is ignored. class MyModel(models.Model): my_time_field = TimeField() custom_date = datetime.today().date() objects = MyModel.objects.annotate(custom_datetime=Func(custom_date + F('my_time_field'), function='DATE')) Please advise the right way to solve this issue. -
Field error for django Prefetch() while resolving ManyToMany relations
Here are my models: class Element(models.Model): name = models.CharField(max_length=255) creator = models.ForeignKey(User, related_name='element_creator', on_delete=CASCADE) element_type = models.ForeignKey('ElementType', on_delete=CASCADE) create_date = models.DateTimeField(auto_now_add=True) modif_date = models.DateTimeField() description = models.TextField(blank=True, null=True) class Meta: managed = True class ElementWorkingSet(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, on_delete=CASCADE) create_date = models.DateTimeField(auto_now_add=True) modif_date = models.DateTimeField(auto_now=True) project = models.ForeignKey(Project, on_delete=CASCADE) active = models.BooleanField(default=True) elements = models.ManyToManyField(Element, through='ElementSet2Element', through_fields=('element_working_set', 'elements'), ) class Meta: managed = True class ElementSet2Element(models.Model): element_working_set = models.ForeignKey('ElementWorkingSet', on_delete=CASCADE) elements = models.ForeignKey(Element, on_delete=CASCADE) active = models.IntegerField() element_owner = models.ForeignKey(User, on_delete=CASCADE) approver = models.ForeignKey(User, null=True, related_name='+', on_delete=CASCADE) class Meta: managed = True I'm extracting a list of ElementWorkingSet, and want to display child Elements with element_owner and approver from the ElementSet2Element table. At first, I was performing many relations without using prefetch_related, but it turned out to be extremely inefficient. Until the time when I needed the element_owner and approver, the response time was decent. But extracting those fields made it very slow. I'm trying to modify my query, to perform more efficient query by using following query: query = ElementWorkingSet.objects.filter( project__id=project_id, active=True).select_related( 'owner' ).prefetch_related( Prefetch( 'elements', queryset=ElementSet2Element.objects.select_related( 'elements', 'approver', 'element_owner' ), ), ) The problem is, that Django returns following error: Cannot resolve keyword 'elementworkingset' into … -
regex in django 2.0 re_path
I'm sorry if this is a stupid question I'm fairly new to python and Django, i've been trying to use this in CreateView, but it is not working re_path(r'^<str:pk>/$', indexView.as_view() ,name = 'index'), -
Django forms - hyphens instead of underscores in names of IDs
In HTML, the best practice is to use hyphens instead of underscores in names of ids.For example, this post refers to this issue. However, Django for some reason uses underscores when automatically generating ids from the names of the model fields. Is it possible to override this behaviour somehow ?