Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I customize admin add/edit page
I'm new to Django(working on 1.5), I've created a new model Ad and registered it in Django Admin, when I add a new Ad on the admin page, instead of manually filling out each field, how can I do the following scenario: Get json from an api endpoint(a list of Ads) and render them on the add/edit page as a select list, I'm using model form so I guess I need an extra custom field for it? Also where should I put the logic calling api ? when I select one of the Ad, it can fill out other fields of the Ad. my admin page: class AdAdminForm(forms.ModelForm): class Meta: model = Ad class AdAdmin(admin.ModelAdmin): form = AdAdminForm fieldsets = ( (None, { 'fields': ('name', 'price', 'contact') }), ) admin.site.register(Ad, AdAdmin) -
How do I convert seconds to hh:mm:ss in django template
So I have a dictionary called match. This has details of a match and one of the keys are game_time. If the game time is <= 10, the match is in draft. Else, I want to report the game time but the value its stored in is just in seconds. {% if match.game_time <= 10 %} drafting {% else %} {{match.game_time|date: "Z"}} {% endif %} Just gives me an error Could not parse the remainder: ': "Z"' from 'match.game_time|date: "Z"' any help appreciated -
infinite scrolling with jquery
I followed this tutorial:https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html It works fine except for the infinite part. Instead of loading more content upon scrolling, it just puts a "more" link at the bottom of the page which loads more content upon being clicked. Here is my code: views.py: def home(request): numbers_list = range(1, 1000) page = request.GET.get('page', 1) paginator = Paginator(numbers_list, 20) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) return render(request, 'blog/home.html', {'numbers': numbers}) home.html: <div class="infinite-container"> {% for number in numbers %} <div class="infinite-item">{{ number }}</div> {% endfor %} </div> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">More</a> {% endif %} <div class="loading" style="display: none;"> Loading... </div> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> I assume its because of the obvious hyperlink in home.html which is titles "more" but how can i change that so it add content automatically once i reach the bottom of the page instead of when i click the button? -
How to implement Django_moderation with django 2.2.3
I'm making a django project and want to add approval feature (edit or add) from a specific model.But i am getting confused with django_moderation doc. and is there any way to use it with django 2 I have read django_moderation got confused with their explanation. -
Ordering queryset by property of related model with another property equal to something
Let's say i have this model relationship: class Account(models.model): ... class Balance(models.Model): class Meta: verbose_name = u"Balance" verbose_name_plural = u"Balances" name = models.CharField(max_length=200, verbose_name=u"Currency", null=True, blank=True) count = models.FloatField(verbose_name=u"Count", null=True, blank=True) account = models.ForeignKey(Account, verbose_name='Account', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name I have the queryset of accounts, they all have the same amount of balances and balances have the same names but not the same counts. For example i have 3 accounts, and each account has only 2 related balances with names 'foo' and 'bar', but 'count' property in these balances may differ. How do i order account by 'count' property of its balance with name 'foo'? Also if possible would like to get solution for this problem but for filtering though i've made kludge for this already using for in so it's not that important. -
Django How to filter and sort queryset by related model
I have this model relationship: class Account: < ... fields ... > class Balance(models.Model): name = models.CharField(...) count = models.FloatField(...) account = models.ForeignKey(Account, related_name='balance') Let's say we have some number of accounts. I need to filter these accounts by balance__name and sort by balance__count. I need sorted accounts, not a list of balances. How do I do that? I don't even have any suggestions to find out a solution using iteration. -
What is causing SMTPAuthenticationError
I just deploy my application to an ubuntu server. I have ssl, so I made the respective modifications in my settings.py, it looks like this: EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_SSL = True I believe this is the Right configuration but when a email is sent I get something like: Traceback (most recent call last): File "/home/admin/Mefid/TransversalScripts/comunication.py", line 122, in send_email fail_silently=False, html_message=html_message) File "/home/admin/Mefid/venv2/lib/python3.7/site- packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/admin/Mefid/venv2/lib/python3.7/site- packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/admin/Mefid/venv2/lib/python3.7/site- packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/home/admin/Mefid/venv2/lib/python3.7/site-packages/django_smtp_ssl.py", line 14, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.7/smtplib.py", line 730, in login raise last_exception File "/usr/lib/python3.7/smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "/usr/lib/python3.7/smtplib.py", line 642, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbvc\n5.7.14 YlL_uB0GK_TLI557gRMyVYqHRr9iVrfj5mJ3jaEuyHjSmmevxT5-8ocIMMRh0BVOPqnrCR\n5.7.14 prX-jJCduiyPcF2RrYAWJkg4A5jUboKUMLzBEyz72VWQLPYiOKxFcZ5SBvrICb> Please\n5.7.14 log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 i11sm7651758oia.9 - gsmtp') ''' I followed a guide here https://github.com/bancek/django-smtp-ssl is there anything else I should be aware of? Thanks for your help. -
Callback with Boto3, Showing Upload Progress
I am in a situation with a document storage feature in a Django/Python application (using Boto3) where I also need to provide the user with information on the progress of an upload. The methods I have seen which use straight JS are not all universally 'usable' across browsers, what I want is to be able upload a file using Boto3 and then also show an upload progress bar in my Django template. Looking at the docs here: https://boto3.amazonaws.com/v1/documentation/api/latest/_modules/boto3/s3/transfer.html I am not understanding how it would be possible to show building progress of the upload calling ProgressPercentage() from within a template. How would I go about displaying the actual progress for my user in a template using Boto3? class ProgressPercentage(object): def __init__(self, filename): self._filename = filename self._size = float(os.path.getsize(filename)) self._seen_so_far = 0 self._lock = threading.Lock() def __call__(self, bytes_amount): # To simplify we'll assume this is hooked up # to a single filename. with self._lock: self._seen_so_far += bytes_amount percentage = (self._seen_so_far / self._size) * 100 sys.stdout.write( "\r%s %s / %s (%.2f%%)" % ( self._filename, self._seen_so_far, self._size, percentage)) sys.stdout.flush() transfer = S3Transfer(boto3.client('s3', 'us-west-2')) # Upload /tmp/myfile to s3://bucket/key and print upload progress. transfer.upload_file('/tmp/myfile', 'bucket', 'key', callback=ProgressPercentage('/tmp/myfile')) -
Best alternative to tkinter GUI in Django
I've created a very simple GUI in tkinter which is basically a bird's eye view of a warehouse, in which you could hover over particular areas to get some data from database or press into it to get some more details. What I didn't know while creating it is that I won't be able to call it with Django (and I guess any other framework). Do you have any suggestion what's the most optimal way to do above task? -
Why is my href tag directing to a different function?
I am working on getting a website up and running with Django 2.2. I am attempting to get a sidebar put together and I figured the first step is make sure I am linking to the right place and then go from there. On my html template I have links so that students can view assignment details and on the sidebar there should be links so students can go to course pages. Currently the href is using the views 'assignment_page' function instead of the 'course_page' function. I have researched into what I should be doing inside the anchor href tag and I feel like I am doing it right as the assignment links work. Looking below you can see the structure of the href tag for the assignment and the course links are the same but the course link doesn't point in the right place. Here is the html template: This the the course link I discussed {% for course in student_courses %} <div> <a href="{% url 'view_course' course.title %}"> {{ course.title }} </a> </div> {% endfor %} Here is the assignment link {% for assignment in course_assignments %} <div> <a href="{% url 'view_assignment' assignment.title %}"> {{ assignment.title }}</a> <p>Due … -
(1045, "Access denied for user)
I am trying to connect my Django app on Heroku to an external MySQL database server of another domain. I have already set up the config variable but the Heroku app doesn't seem to be using them. I get the error below. It seems the Heroku app is using an amazonaws host and not the one I have specified on the DATABASE_URL. Please help (1045, "Access denied for user 'dekacoke_dekate'@'ec2-3-85-219-69.compute-1.amazonaws.com' (using password: YES)") -
How to filter a model in django?
So i have a model called Partner. A business is a partner. I have a foreignkey field who takes self as a parameter to create choices. What i want to do is to go through all the created partners and filter out ones that are parent companies. I was thinking of having a boolean that says is_parent. How do i go about this can i search for the boolean in the database and create a choicefield or something with it so i can get a list of parent companies? I have tried to filter through my result but that did not work as expected. parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) -
'QuerySet' object has no attribute 'vulnerability_slug
i getting mentioned problem while declaring below statement series_urls[m] = part_one.vulnerability_slug this is my model class vulnerability(models.Model): vulnerabilty_date = models.DateTimeField('date published', default=datetime.now) vulnerability_doc = models.FileField(upload_to='documents/%Y/%m/%d/', default="") member_name = models.ForeignKey(TeamMember, default=1, verbose_name="team", on_delete=models.SET_DEFAULT) vulnerability_action = models.CharField(max_length=200, default="no action needed") vulnerability_slug = models.CharField(max_length=200, default=1) def __str__(self): return self.vulnerability_action works well till part but when i include part.vulnerability_slug i am getting error. -
How do I create a confirmation form prepopulated with data collected from an uploaded image in Django?
I'm using Tesseract to scrape text from an image the user uploads. The program currently stores the largest number found in the image and stores it in the database. I'm trying to redirect to a confirmation form after the user uploads an image. The confirmation form should be prepopulated with largest dimension for the user to edit. Should I create a new view for the confirmation form? #views.py def image_view(request): if request.method == 'POST': form = partForm(request.POST or None, request.FILES) if form.is_valid(): data = request.POST.copy() image_file = request.FILES.get('image') text_content = pytesseract.image_to_string(Image.open(image_file)) Serial_number = request.POST.get('Serial_number') x = Component(Serial_number = Serial_number,text=text_content, image=image_file,dimension1=max(new_list)) form.save() return redirect('confirmation_form') else: form = partForm() return render(request, 'home.html', {'form': form,}) #forms.py class editForm(forms.ModelForm): Serial_number = forms.CharField(max_length=20) class Meta: model = Component fields =['Serial_number','image','text','dimension1','Good_Candidate'] -
How to change models name in django from django admin interface?
using "verbose_name" we can change the models name, but here i want this process to be kind of dynamic, like from inside admin panel itself, it will be renamed, so that it will not have to be hard coded. can anybody suggest any solution? -
How can I return a template ( along with a needed argument ) with a custom template filter?
I want to use a custom template filter which will eventually return (redirect to) url of one of the pages that I have in the project along with the needed argument. Is there any way to do that ? (couldn't find anything) Thanks in advance def show(list) -> str: return {'%url 'app:list' list %'} <a href={{original_url|show}}}> -
View an Image Using Django CreateView Before Submitting
I have a Django CreateView that works as expected. I allow the user to attach a photo and then after they click Submit, the view captures the image as expected. However, I am trying to figure out if there is a way, using CreateView, to show the image that has been captured. As of right now, it shows the file name, but I am trying to get it to show the image instead. I tried a variation of this SO question, but it is not for CreateView and I can't figure out how to translate it. Render image without saving Here is my simple example, that works as expected. My Model... class NewAuthor(models.Model): image = models.ImageField(upload_to='images/',default='images/pic.jpg') My view.... class CreateNewAuthorView(CreateView,NeverCacheMixin): model = NewAuthor form_class = CreateNewAuthorForm template_name = 'create_new_author.html' My form... class CreateNewAuthorForm(forms.ModelForm): class Meta: model = NewAuthor fields = ['image',] My HTML... <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="picture"> {{ form.image }} </div> How can I incorporate code that will allow the image that was uploaded to actually be displayed before the user hits submit? Thanks in advance for any suggestions. -
How to access field values of an object from a ModelMultipleChoiceField, from within a template?
I have a database of television channels that I am displaying using a Django form with a ModelMultipleChoiceField and a CheckboxSelectMultiple widget. The template renders fine, but how do I access fields of the individual objects that are part of the ModelMultipleChoiceField field of the form? Channel model class Channel(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name This is the form class ChannelForm(forms.Form): channels_list = forms.ModelMultipleChoiceField(queryset=Channel.objects.all().order_by('name'), widget=forms.CheckboxSelectMultiple) This is how I was trying to access the 'name' field of each channel in the template by doing {{ channel.name}}. {% for channel in form.channels_list %} {{ channel }} accessing: {{ channel.name }}<br> {% endfor %} When it renders it simply says "accessing: " without the channel name -
How to run daphne in localhost with https and mkcert
I am trying to run a django-channels project locally using https (the app has a facebook login that requires https). I have followed the instructions for generating a key and certificate using mkcert ( https://github.com/FiloSottile/mkcert ) and have attempted to use the key and certificate by running daphne -e ssl:443:privateKey=localhost+1-key.pem:certKey=localhost+1.pem django_project.asgi:application -p 8000 -b 0.0.0.0 The server seems to be starting OK however when I try to visit https://0.0.0.0:8000 nothing happens and eventually I get a 'took too long to respond' message. No new output is added to the standard daphne output that appears when I start up the server: 2019-07-16 19:23:27,818 INFO HTTP/2 support enabled 2019-07-16 19:23:27,818 INFO Configuring endpoint ssl:8443:privateKey=../sec/localhost+1-key.pem:certKey=../sec/localhost+1.pem 2019-07-16 19:23:27,823 INFO Listening on TCP address 0.0.0.0:8443 2019-07-16 19:23:27,823 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0 2019-07-16 19:23:27,824 INFO Listening on TCP address 0.0.0.0:8000 Can anyone help with this? -
Why I cannot edit project started on another pc?
I have created a project on one pc and I want to work on it from second pc. I ziped the project from one pc and opened it from another. When I make changes for example in models and want to makemigrations it shows that no changes have been made. What I am doing wrong ? -
Getting error : 'admin' is not a registered namespace, on trying to access the password reset view
I created a password reset view following "https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html " this link. I used the urls for class based views since django uses CBVs in the version 2.1 and above. It seemed to work fine, but today I am getting the above stated error. I have commented the admin url,on uncommenting it the password_reset view works, but through the django registration and uses it's own template regardless of the templates I have created. Why am I getting this problem suddenly when it worked fine earlier? urls.py from django.conf.urls import url,include from django.contrib import admin from NewApp import views from django.conf import settings from django.conf.urls.static import serve from django.urls import path urlpatterns = [ url(r'^$', views.user_login , name='user_login'), url(r'^NewApp/', include('NewApp.urls', namespace="NewApp")), path('', include('django.contrib.auth.urls')), ] NewApp/urls.py from django.conf.urls import url,include from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views app_name = 'NewApp' urlpatterns =[path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Apart from these, I have only used templates which are just copied from the link I have mentioned. -
How to convert Django ORM query to SQL row query?
I have Django ORM query: month = InfraVltgDetail.objects.annotate( month=TruncMonth('create_dt')) .values('month').annotate( name_count=Count('id')) .values('month', 'name_count') I'm using month.query to convert sql row query. #print(by_month.query) output: SELECT django_datetime_trunc('month', "portal_infravltgdetail"."create_dt", 'UTC') AS "month", COUNT("portal_infravltgdetail"."id") AS "name_count" FROM "portal_infravltgdetail" GROUP BY django_datetime_trunc('month', "portal_infravltgdetail"."create_dt", 'UTC') When i'm using output sql row query to execute but getting error. How i'm running sql row query: import psycopg2 conn = psycopg2.connect(database="test", user = "postgres", password = "postgres", host = "localhost", port = "5432") cur = conn.cursor() cur.execute(output_query) cur.fetchall() Could you please help me to convert Django ORM to sql. Thanks in advance. -
Get record's age in second if older than 5 minutes in Django (with PostgreSQL database)
I'm retrieving all records, and I would like to display the record's age for those records that are older than 5 minutes. Here's my current code: Interfaces.objects.all() .annotate( age = (datetime.utcnow() - F('timestamp')), # 0:00:08.535704 age2 = Epoch(datetime.utcnow() - F('timestamp')), # 8.535704 # age3 = int(Epoch(datetime.utcnow() - F('timestamp'))/300), current_time=Value(str(datetime.utcnow()), output_field=null_char_field), ) .order_by('age','ip') age and age2 both work, but the problem is that I want the records that are older than 5 minutes sorted by age, and the rest by ip So I'm trying to set age to 0, if it's less than 5 minutes. Is there a way to do it? -
cant seem to figure out the error: get_queryset() takes 1 positional argument but 2 were given
I have a django rest framework project. I created a viewset and I am setting up the urls for the viewset. I am getting the following error: TypeError at /api/v2/preferences/ get_queryset() takes 1 positional argument but 2 were given I am working with the preferences urls... urlpatterns = [ path('', include(router.urls)), path('dashboards/<int:pk>', dashboard_detail, name='dashboard-detail'), path('dashboards/<str:guid>', dashboard_detail, name='dashboard-detail'), path('users/<int:pk>/stacks/', person_stack, name='user-stacks'), path('preferences/<str:namespace>/<str:path>/<int:pk>/', user_preference_stack, name='preferences-pk'), path('preferences/<str:namespace>/<str:path>/', user_preference_stack, name='preferences-path'), path('preferences/<str:namespace>/', user_preference_stack, name='preferences-namespace'), path('preferences/', user_preference_stack, name='preferences') ] I also wanted to know if it is possible to create 1 url with the namespace and path as optional and not required arguments rather than 4 urls with each variation of the url. here is the viewset: class PreferenceUserViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy' or self.action == 'list' or self.action == 'put': permission_classes = [IsAuthenticated] else: permission_classes = [IsAuthenticated] return [permission() for permission in permission_classes] def get_user(self): return self.request.user def get_queryset(self): namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: queryset = Preference.objects.all().filter(person=self.request.user.id) if namespace and path is None: queryset = Preference.objects.all().filter( person=self.request.user.id, namespace=namespace) if namespace and path: queryset = Preference.objects.all().filter( person=self.request.user.id, namespace=namespace, path=path) return queryset def create(self, … -
Django 1.8 unit tests OperationalError: no such column
I'm trying to upgrade a django1.6 project to 1.8. With this upgrade it seems like south stopped being used. Im trying to update my migrations. I followed the guide which made this seem simple. I deleted all of the old migration files and ran makemigrations to generate new ones. The migrations all run correctly if I run migrate. When I run the unit tests set up I get an error saying: self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x111eb4168> query = 'SELECT "common_basecacheconfig"."id", "common_baseconfig"."contact", "common_baseconfig"."slack_room", "com...config_ptr_id" = "common_baseconfig"."id" ) ORDER BY "app_appconfig"."uniqueentryconfig_ptr_id" ASC' params = () def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) > return Database.Cursor.execute(self, query, params) E django.db.utils.OperationalError: no such column: app_appconfig.name Django-1.8.3-py2.py3-none-any.whl/django/db/backends/sqlite3/base.py:318: OperationalError I edited some of the message to take out company specific stuff. But it's the same message. These are the relevant models I believe name_model = models.CharField(max_length=64, blank=False, db_index=True, validators=[validate_name]) stage_model = models.CharField(max_length=10, choices=STAGE_CHOICES, default=(TEST, TEST)) class UniqueEntryConfig(BaseCacheConfig): name = name_model stage = stage_model class Meta: unique_together = ('name', 'stage') class AppConfig(UniqueEntryConfig): _SERVER_PATH_TEMPLATE = '/service/%s/%s/%s_api' def trimmed_name(self): return self.name.replace('app_', '', 1) def cm_prefix(self): return self.name def delete(self): for config in self.capacity_configs.all(): config.delete() super(AppConfig, self).delete() def server_path(self): return self._SERVER_PATH_TEMPLATE % …