Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Vision API for django based website
I've developed a website for uploading and downloading images using Django. I've also written a python code using the Google Vision API and executed the file successfully on the command line. Now, where should I place that python code in my Django project, so that my images pass through the API? -
Trouble configuring Django with AWS/ElasticIP
I am trying to attach my domain to my Django app on AWS. The first thing I did was get the app working and accessible from the IPv4 Public IP supplied by AWS. This, of course, involved updating my NGINX and DJANGO configurations. No problems there. I followed directions from 2 websites about attaching my domain. Both said to set up an elasticIP. This seems to work fine till I use the NEW public IP address to access my site. Then I start getting BAD REQUEST 400. I tried updating my NGINX and DJANGO configurations to both the NEW public IP and the private IP that is now available, neither works. How should I configure the NGINX and DJANGO configurations after setting up an elastic IP so that I can test it by calling AN IP ADDRESS? Should I be using something different than the NEW public IP or private IP supplied? -
how to make docker build run python manage.py migrate
I'm very new to docker, am trying to use it with Django, here is my DockerFile : FROM python:3.6 RUN mkdir /app WORKDIR /app ADD . /app/ ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV DEBIAN_FRONTEND=noninteractive ENV PORT=8000 RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN pip3 install --upgrade pip RUN pip3 install pipenv RUN pip install -r requirements.txt && python manage.py migrate EXPOSE 8888 CMD gunicorn g_attend.wsgi:application --bind 0.0.0.0:$PORT it works normally but it never does the migrations, any help? Note Pardon me if the question is a beginner question, it is my 1st time with docker and can't find clear documentation for Docker/Django -
How to submit django model forms via ajax, preventing reload/refresh on submit
Problem: every time I click the login button, the page reloads and then goes to some funny URL appending 'undefined' in the URL - http://127.0.0.1:8000/accounts/userLogin/undefined. I would like if the form has errors, then the form errors are shown with the form again for the user to correct and if there are no errors, then log in the user. PS: I am relatively new to this Django/javascript world. Here is my code: View @method_decorator(csrf_protect, name='post') class UserLogin(LoginView): """docstring for UserLogin""" template_name = 'accounts/login.html' def get(self, request): '''a func to work on the request.POST''' print("getting the form for you ") form = LoginForm() return render(request,self.template_name,{'form':form}) def post(self, request): form = LoginForm(request.POST) print("go the data for you") if request.is_ajax(): print("entered form") if form.is_valid(): print("form valid") email = form.cleaned_data['email'] try: user = User.objects.get(email=email) print("user obj", user) if user.check_password(form.cleaned_data['password']): # 0-super admin, 1-dept admin,2-dept staff, 3-end user print("correct password") if user.account_type == 4: if user.last_login == None or user.last_login == '': to = "verify" else: to = "user" else: if user.account_type == 2: to = 'dept_admin' elif user.account_type == 3: to = 'dept_staff' elif user.account_type == 1: to = 'super_user' else: to = None res = {'status':'ok', 'error':False, 'acc_type':to, 'data':user.email} else: print("incorrect password") res … -
Multiple slugs in href
I'm trying to href to my model instances that take a 'model_slug' and 'category_slug' argument. It's giving me NoReverseMatch html {% for model in models %} <a class="btn btn-outline" href="{% url 'main:model_detail_view' model.category_slug model.model_slug %}">View Model</a> {% endfor %} views.py def model_detail_view(request, category_slug, model_slug): model = Model.objects.get(category__category_slug=category_slug, model_slug=model_slug) context = { "models": model, } return render(request=request, template_name='main/model_detail.html', context=context) urls.py path("products/<str:category_slug>/<str:model_slug>/", views.model_detail_view, name="model_detail_view"), -
Can you help me solve Django dynamic formset problem?
I want to use multiple formsets in my django app and each formset and users can add rows to these formsets. I found a js code to add rows and it works when there is only one formset. But when there are more than one formset it keeps adding rows to just the last formset, but delete button is working correctly. I am not a js expert so I don't understand the codes I apply, I'd appreciate if you tell me what should I change in my codes -
How to send Expiration date email in Gmail using django?
Is there any library of feature available in Django to send expiration email using Gmail SMTP server? -
Django multiple media fields not being uploaded to S3
I have multiple media fields in my model I just added media_thumbnail to a model, I basically need to get the first frame out of the video and then store it. I have used Django 's built-in S3 uploading mechanism which by default sends to the bucket which is defined in settings.py such as AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_STORAGE_BUCKET_NAME and etc. It works only when I do not create a field for thumbnail in my model instance. I am using django as my backend as you might have guessed and I have dockerized the whole process models.py media_path = models.FileField(blank=True, null=True) media_thumbnail = models.ImageField(blank=True, null=True) views.py media = Media( media_path=file, media_thumbnail=thumbnail, media_type=request.data.get('med_type', None)) This is the function I am using to generate thumbnail out of a video. def generate_thumbnail(video): path = video.temporary_file_path() thumbnail = video.name.split('.')[0] thumbnail += "_thumbnail.jpg" filepath = os.path.join(os.getcwd(), thumbnail) try: ( ffmpeg .input(path, ss="00:00:00.000") .filter('scale', 640, -1) .output(thumbnail, vframes=1) .run(capture_stdout=True, capture_stderr=True,overwrite_output=True) ) except Exception as e: raise CustomException("someting went wrong", e) finally: with open(filepath) as f: myfile = ImageFile(f) os.remove(filepath) return myfile I am returning an object type <class 'django.core.files.images.ImageFile'> which should be uploaded to S3. but after I try to send a request to a specific endpoint which is supposed … -
I want to create a form in django using model that has foreign key
I have this in my model.py class Proj(models.Model): name = models.CharField(max_length=100) due_date_proj = models.DateTimeField(blank=True,null=True) class Subproj(models.Model): name = models.CharField(max_length=100) due_date_subproj = models.DateTimeField(blank=True,null=True) proj = models.ForeignKey(Proj, on_delete=models.CASCADE) I now want to create a template that allows user to create a new project and then add how many ever subprojects he/she wants under their project. How do i create such a template . Can someone pls provide me the code for forms.py , views.py and for my template . I know I'll have to use formset and javascript , It'll be very usefull if you could give me the entire code as i have been working on this and just can't seem to connect the dots . -
I can't upload the stylesheet image to Django
I have my template ready, but I am blogging with python, there are many images in my CSS and the path is url (... / folder / file.jpg) I can not make the image appear, I tried with the {% static ''%} but still the image does not appear. -
Heroku DataClip fails to retrieve data for some tables
I've a DB hosted in Heroku. Using DataClips I want to make a simple query to my table Order, but gives me an error: SELECT * FROM Order; Dataclip Error ERROR: syntax error at or near "Order" LINE 1: SELECT * FROM Order; ^ However, I can apply the same query to other tables and it works, the difference is in the name of the table: SELECT * FROM shop_product; The DB was created by Django ORM. -
How to do Delete confirmation for a table data with bootstrap Modal in Django?
I'm having a table to show a list of actions in my app. I can delete any action in that table. So, I have added a delete button in every row. This delete button will trigger a 'delete confirmation' bootstrap modal. <table class="table table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col" class="th-lg">Name</th> </tr> </thead> {% for action in actions_list %} <tbody> <tr class="test"> <th scope="row" class="align-middle">{{ forloop.counter }}</th> <td class="align-middle"> {{action.action_name}} </td> <td class="align-middle"> {{action.id}} </td> <td> <div class="row justify-content-end"> <button id="edit" type="button" class="btn btn-sm btn-dark col col-lg-2" style="color: rgb(255,0,0,0)" > <i class="lni-pencil"></i> </button> <button id="trash" type="button" class="btn btn-sm btn-dark col col-lg-2" style="color: rgb(255,0,0,0)" data-toggle="modal" data-target="#modalConfirmDelete" > <i class="lni-trash"></i> </button> </div> </td> </tr> </tbody> {% endfor %} </table> Below is the code for 'Delete Confirmation' bootstrap modal. It will have 'Yes' and 'No' buttons. If I click 'Yes', then that particular action id will be passed to URL and that particular action id will be deleted. {% block modalcontent %} <!--Modal: modalConfirmDelete--> <div class="modal fade" id="modalConfirmDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog modal-sm modal-notify modal-danger" role="document"> <!--Content--> <div class="modal-content text-center"> <!--Header--> <div class="modal-header d-flex justify-content-center"> <p class="heading">Are you sure?</p> </div> <!--Body--> <div class="modal-body"> <i class="fas fa-times fa-4x animated rotateIn"></i> </div> … -
How to filter a ManyToMany query in a class based view?
I have the following models: class List(models.Model): participants = models.ManyToManyField(Participant, through='ParticipantThroughModel', blank=True) class ParticipantThroughModel(models.Model): participantlist = models.ForeignKey(List, null=True, on_delete=models.PROTECT) participants = models.ForeignKey(Participant, null=True, on_delete=models.PROTECT) is_responsible_person = models.BooleanField() class Participant(models.Model): username = models.CharField(max_length=255) And I have the following view: class ListDetail(DetailView): model = List template_name = 'participantlists/participantlist_detail.html' context_object_name = 'participantlist In my template, I can display all the Participant via: {% for obj in participantlist.participantthroughmodel_set.all %} {{ obj.participants }} {% endfor %} However, if I want to filter this to display only participants with is_responsible_person = True how can I do this? -
Can't uninstall Python 2.7.16 on Mac
I am gonna newly install Python 3.8 after uninstalling the previous version - python 2.7.16 So I used these commands on terminal sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7 sudo rm -rf "/Applications/Python 2.7" ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' cd /usr/local/bin/ ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm But when I type "python --version" after finishing these commands, I can still see "Python 2.7.16". Can anyone solve this problem? -
Form code trying to run during MAKEMIGRATONS
I am attempting to setup my new website that works fine locally. However, when I deploy, there is some code in one of my forms that is causing an issue: class ProfileForm(forms.ModelForm): first_name = forms.CharField(max_length=60) last_name = forms.CharField(max_length=100) address1 = forms.CharField(max_length=200) address2 = forms.CharField(max_length=200) city = forms.CharField(max_length=100) state = forms.CharField(max_length=100) zip_code = forms.CharField(max_length=25) CHOICES = tuple((o.pk, o.name) for o in Allergen.objects.all()) allergens = forms.MultipleChoiceField(choices=CHOICES, required=False) The problem is the last 2 lines. When I attempt to MAKEMIGRATIONS, I get this error that the Allergens model is missing. However, if I remove these 2 lines, there is no issue. I suppose, I can just comment out the lines, then add them back. But there must be a better way. How can I do makemigrations without it trying to run these lines? -
Django Template Not Displaying Variables Correclty
I have a django page which is making an API call then displaying the results through a template. This has been working well but I must have changed something and now half the variables are not displaying correctly. Usually when there is an error calling a variable the template would just display a blank field. However, in my situation the webpage is displaying the code which is calling the variable. Here is what I have: My HTML Code Looks like this: <h6>Page</h6> <ul class="list-inline mx-auto row"> <li class="list-group-item col-md-12">ASN: {{ context.upload.urlscan.page.asn }}</li> </ul> <ul class="list-inline mx-auto row"> <li class="list-group-item col-md-12">ASN Name: {{ context.upload.urlscan.page.asnname }}</li> </ul> <ul class="list-inline mx-auto row"> <li class="list-group-item col-md-12">IP: {{ context.upload.urlscan.page.ip }}</li> </ul> From this code ONLY the first and third line are displaying correctly - These lines are displaying the variables that they are assigned to. The middle value Labeled 'ASN Name' is displaying the code back. On the webpage it looks like this: {{ context.upload.urlscan.page.asnname }} I have verified that the data is coming in correctly and this is happening in several places in my code. Not sure why some variables are working and some are not. I am using Django 2.1 and Python 3.6 … -
CSS in django doesn't update
The problem that I have is not I fail to load css file, is that I can't update them. The first few times I edit after I have just created my css files, the changes were working. But after a while, when I try to change for example: the color, it is not changing. The colour on the web is not changing and I click to see the source file, it is using the unchanged version. I have also tried to use python manage.py collectstatic but still can't update the file. # in settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") # in main urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Like button and I keep getting : Reverse for 'like' with no arguments not found. 1 pattern(s) tried: ['products/(?P<slug>[-a-zA-Z0-9_]+)$']
i'm making a like button in Django with a JSON code but i keep getting " NoReverseMatch ".In the urls.py and models.py I'm showing all the code, in views.py only the method of the like button and the imports, and in detail.html only the HTML tag's for the like button and the JSON script. This is what I'm getting in the browser: Reverse for 'like' with no arguments not found. 1 pattern(s) tried: ['products/(?P<slug>[-a-zA-Z0-9_]+)$'] Request Method: GET Request URL: http://localhost:8000/products/7/ Django Version: 2.2.9 Exception Type: NoReverseMatch Exception Value: Reverse for 'like' with no arguments not found. 1 pattern(s) tried: ['products/(?P<slug>[-a-zA-Z0-9_]+)$'] Python Version: 3.7.4 The models.py in the app "products": from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from django.urls import reverse class Product(models.Model): title = models.CharField(max_length = 80) pub_date = models.DateTimeField() body = models.TextField() url = models.TextField() image = models.ImageField(upload_to = 'images/') icon = models.ImageField(upload_to = 'icon/') votes_total = models.IntegerField(default=1) slug = models.SlugField(null=False, unique=True) likes = models.ManyToManyField(User, blank=True, related_name='likes') hunter = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] + "..." def pub_date_pretty(self): return self.pub_date.strftime("%b %e %Y") def save(self, *args, **kwargs): #if not self.slug: #self.slug = slugify(self.title) if not self.slug: slug = … -
TemplateDoesNotExist at /users/login/ registration/login.html
I got the following error while doing an exercise from Python Crash Course Book. screenshot of error Code in files: login.html: <p> <a href="{% url 'blogs:index' %}">Blogging Site</a> - {% if user.is_autenticated %} Hello, {{ user.username }} {% else %} <a href="{% url 'users:login' %}">Log in</a> {% endif %} </p> {% block content %}{% endblock content %} urls.py of users app: from django.urls import path, include app_name = 'users' urlpatterns = [ path('', include('django.contrib.auth.urls')), ] -
Is it possible to select no table fields receiving only values calculated based on real columns?
So the question is "is it possible to make the following query using Django ORM without raw statements?" SELECT my_table.column_a + my_table.column_b FROM my_table The example for which it would be suitable from my point of view: We have a model: class MyOperations(models.Model): operation_start_time = models.DateTimeField() At some point we create a record and set the field value to Now (or we update some existing record. it doesn't matter): MyOperations.objects.create(operation_start_time=functions.Now()) Now we want to know how much time has already passed. I would expect that Django ORM produces the following SQL statement to request data from the database (let's assume that we use MySQL backend): SELECT TIMESTAMPDIFF(MICROSECOND, `myapp_myoperations`.`operation_start_time`, CURRENT_TIMESTAMP) AS `time_spent` FROM `myapp_myoperations` WHERE ... So is it a way to achieve this without raw statements? For now I settled on the following solution: MyOperations.objects.values('operation_start_time').annotate( diff=ExpressionWrapper(functions.Now() - F('operation_start_time'), output_field=DurationField() )).filter(...) It produces the following SQL statement: SELECT `myapp_myoperations`.`operation_start_time`, TIMESTAMPDIFF(MICROSECOND, `myapp_myoperations`.`operation_start_time`, CURRENT_TIMESTAMP) AS `time_spent` FROM `myapp_myoperations` WHERE ... Or in the Python response object representation: {'operation_start_time': datetime(...), 'diff': timedelta(...)} Is it a way to get the response dict with only diff since this is the only field I am interested in? Django ORM produced the query which requests operation_start_time just as … -
How to lookup a reverse foreignkey in Django template
I have a the following models: class Issuer(models.Model): issuer_name = models.CharField(max_length=255) issuer_administrators = models.ManyToManyField(CustomUser, blank=True, through='AdministratorsThroughModel') class AdministratorsThroughModel(models.Model): issuers = models.ForeignKey(Issuer, null=True, on_delete=models.PROTECT) users = models.ForeignKey(CustomUser, null=True, on_delete=models.PROTECT) class CustomUser(models.Model): username = models.CharField(max_length=255) class List(models.Model): summary_issuer = models.ForeignKey(Issuer, on_delete=models.PROTECT) I then have a simple class based view for List: class ListDetail(DetailView): model = List context_object_name = 'list_obj' What is the correct syntax in the view to look up all CustomUsers who can administer the List? The pseudo logic is: Each List has an Issuer Each Issuer can have a number of CustomUsers I want to display the CustomUsers associated with the list_obj in the DetailView E.g. {{ list_obj.issuer_set.customuser }} -
How to Populating Django Dropdown list from mysql database?
This is my models.py class School(models.Model): school_name = models.CharField(max_length=50) school_at = models.ForeignKey(District,on_delete=models.CASCADE) def __str__(self): return self.school_name i want to show the values in drop down!, Tanks in advance -
Broken Images on Django
I am getting broken images on django. Below are the relevant information with code, I guess. I am new to django and any information would be greatly appreciated. name of project/site=imagesite name of app=gallery in models.py, class Photo(models.Model): pub_date = timezone.now() image = models.ImageField(upload_to='images') in views.py, def view_gallery(request): photo_list = Photo.objects.all() return render(request, 'gallery/view_gallery.html', {'photo_list' : photo_list}) in view_gallery.html, <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Gallery</title> </head> <body> {% csrf_token %} {% for photo in photo_list.all %} <img src="{{ photo.image.url }}" width="240"> <h2> {{ photo.pub_date }} </h2> <br> {% endfor %} </body> </html> in settings.py, MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite/media') in imagesite/urls.py, urlpatterns = [ path('imagesite/', include('gallery.urls')), path('admin/', admin.site.urls), ] in gallery/urls.py, urlpatterns = [ path('', views.view_gallery, name='view_gallery'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Getting an error when deploying a Django app to Heroku
I am trying to deploy a django app but I am getting a push rejected error(Traceback attached). I am using whitenoise to handle the static files and done the correct configuration in settings.py file. This error has really been bugging me . -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/app/.heroku/python/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 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'whitenoise' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed -
Django Login System with DynamoDB Backend
I am trying to build a login system using django framework and dynamodb backend. Getting the data isn't the issue I am facing, I just have no idea how to build the login system using the dynamodb backend. Has anyone built something using django and dynamo that can point me in the right direction to get this done? Any advice/documentation on the topic would help greatly.