Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the difference between yoyo migrations and django migrations?
Can someone please explain the difference between yoyo migrations and django migrations? Why can't we just use the built-in migrations in Django using python manage.py migrate? I'm trying to move my Django application forward to staging but our DevOps team is saying we need a database migration tool--specifically, they recommended yoyo since it's in Python like Django. But, I'm confused as to why we need this when Django has built-in migrations. What am I missing? Not sure if it matters, but we're using a PostgreSQL db. We have an organization-wide db and all our tables exist in a schema specific to our project. -
Error 500 when user upload files - Django & Ajax
As in the title, when user upload some file I get 500 error. What is the most interesting thing the problem appear after I added 'sender' to the 'data' dictionary. Here is my code #models class Document(models.Model): name = models.CharField(max_length=100, unique=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #forms class FileForm(forms.ModelForm): class Meta: model = File fields = ('file',) #views class BasicUploadView(View): def get(self, request, pk): pk = pk files_list = File.objects.all() return render(self.request, 'upload/basic_upload/index.html', {'files': files_list, 'pk': pk,}) def post(self, request, pk): form = FileForm(self.request.POST, self.request.FILES) if form.is_valid(): form.instance.course = pk form.instance.sender = request.user file = form.save() data = {'is_valid': True, 'name': file.file.name, 'url': file.file.url, 'sender': file.sender,} else: data = {'is_valid': False} return JsonResponse(data) #js file $(function () { $(".js-upload-photos").click(function () { $("#fileupload").click(); }); $("#fileupload").fileupload({ dataType: 'json', done: function (e, data) { if (data.result.is_valid) { $("#gallery tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" +"<tr><td>" + data.result.sender + "</td></tr>" )}}});}); -
How to integrate configurable Django app with existing Django project?
The link given below directs to a git repo where there's a configurable Django app. How can I use this in my own project? I'm an absolute beginner in Django framework, your help will be very much appreciated. https://github.com/tomwalker/django_quiz -
Generate download path for generated files in Django
I have a Django server in which I generate files that I want to be downloaded to an Android app I'm also creating. Each of these files has an ID number, which the Android app will have. The android app will not know the name of the files. How can I generate download urls so that url is something like mysite.com/download/"int id of file"/ and then my Android app will be able to download it via DownloadManager? Below is the code that I want to use to accomplish that but any suggestions on other ways to accomplish this are welcome. String url = "customurl"; DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setTitle("Downloading"); request.setDescription("Downloading new titles"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "" + System.currentTimeMillis()); request.allowScanningByMediaScanner(); request.setAllowedOverMetered(true); request.setAllowedOverRoaming(true); long downloadReference = downloadManager.enqueue(request); if (downloadReference != 0) { Toast.makeText(getApplicationContext(), "download started", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(getApplicationContext(), "no download started", Toast.LENGTH_SHORT).show(); } -
How can I install Vuejs with django on cpanel shared server?
I am learning web development and want to develop a project using Vuejs as frontend with Django as backend on cPanel shared service. Please help me. -
Django update_or_create is updating even if there is no change?
I have a user with the name field "jule". If i do this : obj, created = Person.objects.update_or_create(first_name='jule') Will this make an action in my database? Or does the django ORM detect that there is no change to make (and not do any action in my database then) ? I need this to optimize my code wihtin a loop :) Thank for your help ! -
Retrieve data from database without using extra page
In my 'django' project, I need to retrieve / insert data from multiple tables of my (mysql)database. However because of the code I used, I had to use an extra .html page for each table operation. I want to be able to access multiple tables on a single html page. In order to better explain the situation, I write the relevant codes of the project below. Project/views.py def home_view(request, *args, **kwargs): print(args, kwargs) print(request.user) return render(request, "home.html", {}) @login_required() def admin_view(request, *args, **kwargs): print(args, kwargs) print(request.user) return render(request, "adminPage.html", {}) @login_required() def doctor_view(request): return render(request, 'doctorPage.html', {'doctors': doctor_view()}) appointments/views.py from django.views.generic import DetailView, ListView class list_of_appointments(ListView): model = Appointment template_name = 'appointments/appointment_list.html' class list_of_patients(ListView): model = Patient template_name = 'appointments/patient_list.html' appointments/urls.py urlpatterns=[ url(r'^appointment_list/$', list_of_appointments.as_view(), name='list1'), url(r'^patient_list/$', list_of_patients.as_view(), name='list2') ] So, in order to access the operations related to the tables, I have to use the following url code. <a href={% url 'appointments:list2' %}> Therefore, I can create a second html file and extract the data I want to extract from the database with this method. {% for appointment in object_list %} <tr> <td>{{ appointment.patient.name }}</td> <td>{{ appointment.doctor.name }}</td> <td>{{ appointment.Date }}</td> <td>{{ appointment.time }}</td> <td>{{ appointment.province }}</td> <td><a href="#"> <button … -
how to send extra context in wagtail Page
Currently I Am Using Like This But Nothing Works.... I tried to check in Both the Classes but nothing works (UserPage and UserPageCarousel) But Nothing Works . class UserPageCarousel(Orderable): def get_context_data(self, request): context = super(UserPageCarousel, self).get_context(request) products = UserPageCarousel.objects.all() print(products) n = len(products) nslides = n // 4 + ceil((n / 4) - (n // 4)) context['no_of_slides'] = nslides context['range'] = range(1, nslides) context['product'] = products return context page = ParentalKey("user.UserPage", related_name="carousel_videos", null=True) carousel_video = models.ForeignKey( "wagtailvideos.Video", related_name="+", null=True, blank=False, on_delete=models.SET_NULL) panels = [ VideoChooserPanel('carousel_video') ] class UserPage(Page): content_panels = Page.content_panels + [ MultiFieldPanel([ InlinePanel('carousel_videos', label="Video") ], heading="Add Videos To List") ] class Meta: verbose_name = "User Page" verbose_name_plural = "User Pages" and here is my template (path is user/user_page.html) Code:- <p> Welcome Hi </p> {% if request.user.is_authenticated %} {{ user.username }} {% endif %} {% for loop_cycle in self.carousel_videos.all %} <p>{{ loop_cycle.carousel_video.url }}</p> {% endfor %} {% for i in range %} <p> {{ i }}</p> {% endfor %} All Template Code is Running But for i in range gives nothing Means my get context is not working in any case Current Output: - Welcome Hi Hahaha puneet /media/original_videos/horse_rolling_farm_animal_equine_1067.mp4 /media/original_videos/horse_rolling_farm_animal_equine_1067_ME9ybb0.mp4 /media/original_videos/horse_rolling_farm_animal_equine_1067_Ix4pCIa.mp4 /media/original_videos/Horses_2.mp4 /media/original_videos/horse_rolling_farm_animal_equine_1067_rhDf82J.mp4 -
Django Error in using jinja code inside style tag
An error is generated while using jinja code inside html style tag error statement at-rule or selector expectedcss(css-ruleorselectorexpected) code <style> {% block css %} {% endblock %} </style> -
File Upload with Text Insertion in Django
I'm fairly new to Django and I was trying to create a form with both file upload and text insertion. I was able to configure the form to support file upload functionality. However,I'm having problems with implementing the text area insertion in which I want the user to specify the job industry and then save this text input. Any advice on how to implement a form in which I can perform both file upload and saved text insertion is greatly appreciated! Here is my code: models.py from __future__ import unicode_literals from django.db import models from django import forms from django.forms import ClearableFileInput # Enabling the ability to delete files from django.db.models.signals import post_delete from django.dispatch import receiver class Resume(models.Model): # Allow user to upload a PDF resume resume = models.FileField('Upload Resume', upload_to='media/') # Define an industry specification with bound max length of 50 chars industry = models.CharField(max_length = 50, blank = False, null = False) # Deleting the entry def delete(self, *args, **kwargs): self.resume.delete() super().delete(*args, **kwargs) # Deleting duplicate submissions automatically @receiver(post_delete, sender=Resume) def submission_delete(sender, instance, **kwargs): instance.resume.delete(False) forms.py from django.forms import ModelForm from django import forms from web_application.app_core.models import Resume from django.forms import ClearableFileInput # Class of a form … -
How can I translate the following SQL query into django querysets?
How can I translate the following SQL query into django querysets? SELECT pk FROM User; I've searched how to do it and can't find anything. -
How to access objects as values in different ways for nested context dictionary in django?
I'm a little new to django so bear with me. I'm doing a naive fuzzy search, nvm how it works, but the resulting context I get from my view is the following: context = {plst : {0 : { player : playerObject; performance : PerfObject; salary : SalaryObject; socialMedia : socialMediaObject}; 1: {....}; ... } } The way I get each of those objects is through functions like: performance = get_object_or_404(PlayerPerformance, player_name=player_name), although I don't think that matters. What it should tell you though is that each object has somewhat different "attributes". Hence I don't think the standard for loop can work. The problem comes when I try to visualize it in player.html. I can do this, standard for-loop, right: {% for iter, values in plst.items %} <p> {{iter}} </p> {% for k, v in values.items %} <p> {{k}} : {{v}} </p> {% endfor %} {% endfor %} which results in: player : James Harden performance : PlayerPerformance object (2) salary : PlayerSalary object (2) socialMedia : PlayerSocialMedia object (213) But that doesn't give me access to the values' internal elements. Like performance.points. I can also do this: {% for iter, values in plst.items %} {% for k, v in … -
'QuerySet' object has no attribute 'year' while using timesince
'QuerySet' object has no attribute 'year' Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 2.2.8 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'year' -
RuntimeError at / cannot cache function '__shear_dense': no locator available for file '/home/...site-packages/librosa/util/utils.py'
I am trying to host django application with apache2. But getting the following error. RuntimeError at / cannot cache function '__shear_dense': no locator available for file '/home/username/project/env/lib/python3.6/site-packages/librosa/util/utils.py' When running the Django server, no such error is encountered but in case of apache2 server, this error is thrown. Similar question can be found here : RuntimeError: cannot cache function '__jaccard': no locator available for file '/usr/local/lib/python3.7/site-packages/librosa/util/matching.py' The problem is a wsgi error and appears to be due to import of librosa and numba. I have been stuck on these days. Any pointers on how to approach this problem will be highly appreciated. -
How to get user profile data available for each template?
I work on a Django project when user is authenticated, I can get information of this user (queries on database) stored in five differents tables: user -- profile -- table1 -- table2 -- table3 I would like to have access to these data in each template I currently use context to pass data from views to template I also set session variables that I can use in views to set context but doing like that, I must pass these data in each views as session variables can be directly access in template but, is there a simpliest way of getting user data available in all template without having to pass context in each template? hope my question is clear enough... -
What does Django DEBUG do under the hood?
I have a bug that does not occur when DEBUG is True, whether in production on Apache or locally on the Django dev server. This leads me to ask: What is all the magic that Django DEBUG does behind the scenes? The documentation doesn't have very much information about this. Now for the bug. I understand that the following description is too bare-bones for anyone to reproduce, but I have IP to protect, and I don't have much hope of the error being reproduced anyway. Suppose I have a Django project with at least two apps, app alice with model A and app bob with model B. I am using UpdateWithInlinesView from django-extra-views. The error occurs when this view constructs a formset from instances of model A. In my email about the server error, I get a message like this: FieldError at /some/url/ Cannot resolve keyword 'field_of_A' into field. Choices are: field_of_B_1, field_of_B_2, field_of_B_3 I've gotten this type of error before. It normally happens when you tell a form "I'm using model C" and "I'm using a field called debbie" and model C doesn't have a field called debbie. That part makes sense. But this error makes it look like … -
Which is the best package in python django for creating reports .. I am looking for something like extent report
Which is the best package in python django for creating reports .. I am looking for something like extent report -
set custom django favicon
When I log into django admin page, my browser sends a request for favicon.ico. I've tried to override admin/base_site.html and now my browser sends 2 request: one to /static/favicon.ico (cause of my override) and still to /favicon.ico. Why does it still try to get /favicon.ico even though I've written an override? this is how it looks -
How to prevent 500 GET error when empty request happens on page load?
I have a form with a dependent drop-down that loads whenever the form is submitted so that the main choice that was selected before form submission is preloaded again after it submits. I noticed that I get a GET: 500 Internal Server Error whenever the page first loads without a parameter being passed, the error looks like this: Request URL: http://localhost:8000/operations/ajax/load-stations/?work_area= Request Method: GET Status Code: 500 Internal Server Error Because the work_area is empty (work_area = "") when the page first loads and no form has been submitted yet. How can I modify either the JS or the function so that this error does not occur? enter_exit.html {% block main %} <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate > {% csrf_token %} <div> <div> <label>Employee #</label> {{ form.employee_number }} </div> <div> <label>Work Area</label> {{ form.work_area }} </div> <div id="my-hidden-div"> <label>Station</label> {{ form.station_number }} </div> <!-- Rest of the form --> </div> </form> <script> function loadStations() { var url = $("#warehouseForm").attr("data-stations-url"); var workAreaId = $(this).val(); var $stationNumberField = $("#{{ form.station_number.id_for_label }}"); $.ajax({ url: url, data: { 'work_area': workAreaId }, success: function (data) { $("#my-hidden-div").show(); // show it $stationNumberField.html(data); // Check the length of the options child elements of … -
Django - Local instance keeps trying to connect to localhost for a MySQL database instead of remote in Visual Studio
I'm trying to connect to a remote MySQL database from Django, yet it keeps trying to connect to localhost for whatever reason. The error I'm getting: Traceback (most recent call last): File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\django\db\backends\mysql\base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\MySQLdb\connections.py", line 164, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'localhost' (10061)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\ptvsd_launcher.py", line 119, in <module> vspd.debug(filename, port_num, debug_id, debug_options, run_as) File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\debugger.py", line 39, in debug run() File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\__main__.py", line 316, in run_file runpy.run_path(target, run_name='__main__') File "C:\Users\Jesus\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "C:\Users\Jesus\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Users\Jesus\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "R:\dev\HTML\Jesuszilla's Lawn\jesuszillaslawn\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "R:\dev\HTML\Jesuszilla's Lawn\env2\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv … -
Why MyPage._meta.get_field("title").verbose_name changes all the titles' labe in Wagtail?
I have a few apps in my Wagtail project and one of them is "news" which contains News(Page). I want to overwrite the title's label "title" to "headline" in the admin. News._meta.get_field("title").verbose_name = "Headline" As a result, I get all the titles' label "Headline" in all apps and pages. Why I've got this strange effect? -
How can I redirect to the login page if the user is not logged in?
So I am developing an app in Django and I got two main templates and views. I got a login view with me url myApp2/login and an index page that is myApp2/ What I wanted to do is that if the user is not logged in and tries to go to myApp2/ it automatically redirects to myApp2/login. my views.py @login_required def index(request): actores = get_list_or_404(Actor.objects.order_by('nombre')) peliculas = get_list_or_404(Pelicula.objects.order_by('fecha_estreno')) context = {'peliculas': peliculas, 'actores': actores} return render(request, 'index.html', context) def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'registration/login.html', {'form': form}) my urls.py path('login/', views.login_view, name="login"), path('',views.index, name ='index'), Thank you in advance -
How to make a QuerySet with custom select in django
I'm working on a project in python I'm kind of a beginner. I searched a bit on the Queryset but didn't found out how to do a custom select query. Here's the raw SQL query : SELECT DATE_FORMAT(DATE_ADD(date_and_time, INTERVAL - WEEKDAY(date_and_time) DAY),'%Y-%m-%d') as Week,device_type as 'Type of device', COUNT(*) as Views FROM manage_history GROUP BY Week,device_type; How could I get the values but with a QuerySet ? Thanks a lot -
django 3 - import ipdb; ipdb.set_trace() - Runtime Error
Just installed django-3.0, I'm used to insert ipdb to stop runtime and inspect functions. With previous version it was working fine. Is there any way to get it work? > /home/tec1/workspace/static_site/stagen/hmi/views.py(11)dispatch() 10 def dispatch(self, request, *args, **kwargs): ---> 11 import ipdb; ipdb.set_trace() 12 127.0.0.1 - - [11/Dec/2019 15:52:07] "GET /pg/blog/g/ HTTP/1.1" 500 - Traceback (most recent call last): File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__ return self.application(environ, start_response) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/six.py", line 695, in reraise raise value.with_traceback(tb) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tec1/.local/share/virtualenvs/static_site-l8CYf1lN/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/tec1/workspace/static_site/stagen/hmi/views.py", line 11, in dispatch import ipdb; ipdb.set_trace() File "/usr/lib/python3.7/bdb.py", line 92, in trace_dispatch return self.dispatch_return(frame, arg) File "/usr/lib/python3.7/bdb.py", line 151, in dispatch_return self.user_return(frame, arg) File "/usr/lib/python3.7/pdb.py", … -
How to call the Django-Admin style of providing much with less code
I like the django admin very much. You only need to configure it. Making the admin site available for some models hardly "software development". I would call it "from coding to configuring". But that's not a term. How is the general term? I tried Scaffolding, but I think this is not the right term, since no code gets generated.