Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django settings.MEDIA_ROOT as string file path?
Modules being used: OpenCV and Django Task: I am trying to process a video during upload by reading the video file and saving the first frame of the video to use as thumbnail on an HTML page. Problem: The function cv2.imwrite, which saves an image, is where the code stops working. I have added a bunch of print() statements to show exactly what is going on. I would like to note that if I use a file path in the string form such as: cv2.imwrite('/media/test2_thumbnail.jpg', frame) the process works. OpenCV Code: def save_video_thumbnail(video, video_name): cap = cv2.VideoCapture(video) ret, frame = cap.read() if ret: print(f'It is {ret} that it is reading the frame') print('Saving file to:', settings.MEDIA_URL + video_name + "_thumbnail.jpg") thumbnail = cv2.imwrite(settings.MEDIA_URL + video_name + "_thumbnail.jpg", frame) return thumbnail Django Code: def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) form.instance.sender = self.request.user if form.is_valid(): form.save() video_name = form.instance.name video_file_path = str(settings.MEDIA_ROOT) + "/" + str(form.instance.video_file) print(f'start with file: {video_file_path}') thumbnail = save_video_thumbnail(video_file_path, video_name) print(f'It is {thumbnail} that it is saving the thumbnail.') Output: start with file: /home/david/PycharmProjects/clearpath/media/videos/IMG_0088_PwgOcpW.MOV It is True that it is reading the frame Saving file to: /media/test2_thumbnail.jpg It is False that it is saving the … -
How to link rows from one table to rows of another table in Django?
I have to four tables: class Instrument(models.Model): name = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ManyToManyField(Instrumentation, verbose_name=_('instrumentation'), related_name='instrument', blank=True) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) Entries to the table are: row 1: name = violin, instrumentation = piano trio row 2: name = piano, instrumentation = piano trio row 3: name = cello, instrumentation = piano trio Here are the other two tables: class Ensemble(models.Model): name = models.CharField(max_length=200, null=True, blank=True) class EnsembleMember(models.Model): ensemble = models.ForeignKey(Ensemble, verbose_name=_('ensemble'), related_name='ensemble_member', on_delete=models.PROTECT) member = models.ForeignKey(Person, verbose_name=_('member'), null=True, blank=True, on_delete=models.PROTECT) row 1: name = person 1 (violin), ensemble = Beau Arts Trio row 2: name = person 2 (pianist), ensemble = Beau Arts Trio row 3: name = person 3 (cellist), ensemble = Beau Arts Trio How do I link Instrument with EnsembleMember? ForeignKey or ManyToManyField? An Instrument to map to many different Ensemble Member. row 1 in Instrument to row 1 in Ensemble Member row 2 in Instrument to row 2 in Ensemble Member row 3 in Instrument to row 3 in Ensemble Member And have drop down options in admin.py -
Heroku (DjangoRF/React App) react router works but urls don't work while refreshing or writing manually
I've got APP working on Heroku. It has DRF API backend and ReactJS frontend. React routing works properly but when I refresh page or write URL manually it throws django 404 URL not found error. During the development I didn't have that problem. It has became a problem after pushing App to Heroku. -
how to get amp template in django
i've been trying to get my site with django in back-end and AMP on the front-end (without a html), i've created some sites with fully amp but now i'm problems with the 'base.amp.html' and another issues. i've tried to use the app 'django-amp-tools' and get some errors in the app, tried to create without it and getting erros on the validation just to bring the extends 'base.amp.html'. base.amp.html: {% load staticfiles %} {% load static %} {% get_media_prefix as MEDIA_PREFIX %} <!doctype html> <html amp lang="en"> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <title>{% block title %}dealership{% endblock %}</title> <link rel="canonical" href="https://amp.dev/pt_br/documentation/guides-and-tutorials/start/create/basic_markup/"> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "NewsArticle", "headline": "Open-source framework for publishing content", "datePublished": "2015-10-07T12:02:41Z", "image": [ "logo.jpg" ] } </script> <style amp-boilerplate> body { -webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both; -moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both; -ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both; animation: -amp-start 8s steps(1, end) 0s 1 normal both } @-webkit-keyframes -amp-start { from { visibility: hidden } to { visibility: visible } } @-moz-keyframes -amp-start { from { visibility: hidden } to { visibility: visible } } @-ms-keyframes -amp-start { from { visibility: … -
can i use jQuery in Django framework
i'm writing a Django Full website and trying to change the element using jQuery OR JavaScript but i couldn't i want to change the total ''' <tr> <td>{{i.itemname}}</td> <td>{{i.description}}</td> <td id="quantity">{{i.quantity}}</td> <td id="price">{{i.price}}</td> <td id="total"></td> </tr> ''' ''' var quantity = document.getElementById('#quantity') var price = document.getElementById('#price') q=Number(quantity) p=Number(price) total = q*p document.getElementById("#total").innerHTML = total; ''' -
Is there a way to restrict outbound traffic on a Django function?
I have a function in my Django app and I'd like to ensure there is no outbound network traffic from it while still being able to return a response. For example, blocking the POST request to an external site in this function: def secureFunction(val): request.POST('www.example.com', data={'val':val}) return val * 2 Currently, I break my app into APIs and use AWS security groups to accomplish this. Is there a way I can put a wrapper on Django functions to block outbound traffic, but still return a response? For example something like: @block_traffic def secureFunction(val): request.POST('www.example.com', data={'val':val}) # blocked return val * 2 I want to be able to apply outbound traffic blocking to specific functions. -
Filtering data in real time in django forms
I have two problems strictly. The first is the problem with the field type in forms.py. Because I'm trying to use a foreign key as a value in the check box and I have the error that the "int () must be a string, a byte-like object or a number, not" ModelChoiceField "and I don't know what to do with it. The second main problem is data filtering in the interface in real time. What I mean? I have a user model like: # user/models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) country= models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) year = models.IntegerField(choices=YEARS, default=1) image = models.ImageField(default='default.jpg', upload_to='profile_pics') And in forms I want to see only those cities that are in the selected country. For example, we have record like: London, United Kingdom; York, United Kingdom; Berlin, Germany; and if the user chooses Germany, he should only see Berlin in the area with the cities. I hope you know what I want to achieve and someone will be able to help me. # forms.py: class ProfileUpdateForm(forms.ModelForm): country =forms.ModelChoiceField(queryset=Country.objects.all()) city = forms.ModelChoiceField(queryset=City.objects.filter(country=country)) class Meta: model = Profile fields = ['website','country', 'city', 'year', 'image'] # city/models.py class Country(models.Model): name = models.CharField(max_length=100) … -
Geocoding with GeoPy and ImportExport in Django
I am bringing a data set from a .CSV file of addresses into a model in Django through the ImportExport plugin, and at the point of saving this the model runs a geocoding process with GeoPy. 90% of the time it works but there are a few entries that are coming up with the following error: ... in save _, latlon = geocoder.geocode(address) TypeError: cannot unpack non-iterable NoneType object I am guessing that the geocoding is not finding an address but I'm not sure why it doesn't just leave the field empty. Apologies if this question is a a simple misunderstanding, I am a very new starter to this level of programming, I've looked up relevant sections in Django Docs, GeoPy docs and google maps geocoding docs but don't seem to find any hint as to how to fix it. below is the a more full trace back error output: Traceback (most recent call last): File "C:\Users\henry\webvenv\aavenv\lib\site-packages\import_export\resources.py", line 522, in import_row self.save_instance(instance, using_transactions, dry_run) File "C:\Users\henry\webvenv\aavenv\lib\site-packages\import_export\resources.py", line 315, in save_instance instance.save() File "C:\Users\henry\webvenv\project\architects\models.py", line 51, in save _, latlon = geocoder.geocode(address) TypeError: cannot unpack non-iterable NoneType object Below is the app/model.py which is being populated by the .CSV file and … -
Filter images by foreign key
I have an Image model and a Category model. I want to display only images of the corresponding category in my category_detail view. models.py class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title class Image(models.Model): category = models.ForeignKey(Category, on_delete="CASCADE") image = models.ImageField() caption = models.CharField(max_length=250) class Meta: verbose_name_plural = "Images" def __str__(self): return str(self.image) views.py def category_detail_view(request, slug): category = get_object_or_404(Category, slug=slug) context = { "gallery": Image.objects.filter(Category), } return render(request, 'main/category_detail.html', context) category_detail.html {% for image in gallery %} <div class="col-md-4"> <a href="{{ image.url }}"> <img src="{{ image.url }}" class="img-responsive img-thumbnail" width="304" height="236"/> </a> </div> {% endfor %} -
The most reliable way to grab an IP-address?
I noticed that it is fairly tricky to grab an IP-address with Django, It almost seem that JavaScript can grab an IP more reliably than Django but the problem with JS is that it can be disabled easily by the user. What is your take on the situation? I can't decide which tech to use. Thanks. -
TypeError: Cannot read property 'length' of undefined in Django and ReactJs
TypeError: Cannot read property 'length' of undefined thats whats says compiller when i run my Django and ReactJs ecommerce app .What i need to do with this ? error place is shown as in cart.js 53 | text={${cart !== null ? cart.order_items.length : 0}} ^ 54 | pointing error place is shown as in Layout.js 33 | dispatch(cartSuccess(res.data)); ^ 34 | }) In action/ cart.js export const fetchCart = () => { return dispatch => { dispatch(cartStart()); authAxios .get(orderSummaryURL) .then(res => { dispatch(cartSuccess(res.data)); }) .catch(err => { dispatch(cartFail(err)); }); }; }; In Layout.js <Menu.Menu inverted position="right"> <Dropdown icon="filter" loading={loading} text={`${cart !== null ? cart.order_items.length : 0}`} pointing className="link item" > <Dropdown.Menu> <Dropdown.Item>List Item</Dropdown.Item> <Dropdown.Item>List Item</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Header>Header Item</Dropdown.Header> <Dropdown.Item> <i className="dropdown icon" /> <span className="text">Submenu</span> <Dropdown.Menu> <Dropdown.Item>List Item</Dropdown.Item> <Dropdown.Item>List Item</Dropdown.Item> </Dropdown.Menu> </Dropdown.Item> <Dropdown.Item>List Item</Dropdown.Item> </Dropdown.Menu> </Dropdown> </Menu.Menu> -
Context Error while using Django-tables2 in my Project
I am attempting to implement Django-tables2 into my project. I am able to render the object_list, but when I alter the template to render_table table, it fails. I am seeing this error upon rending my template: Exception Type: AttributeError Exception Value: context Here are my following files Views.py class DeviceTable_New(SingleTableView): table_class = DeviceTable template_name = "device_app/device_list.html" paginator_class = LazyPaginator filterset_class = DeviceFilter Tables.py class DeviceTable(tables.Table): class Meta: model = Device template_name = "device_app/device_list.html" fields = ("id", "type", "processed","donated_to_recipient") urls.py path('device_list/',views.DeviceTable_New.as_view(),name='device_list'), Template (Not the full page. There is proprietary information on this page.) <div class='col-md-8'> <div class="jumbotron"> <h1>Devices</h1> <hr> <p><a class='button' href="{% url 'device_app:device_create'%}">Create Device</a</p> {% render_table table %} </div> </div> -
Request req_5BdKqxhl1rXEbe: No such customer: cus_FLh58K7EslblSw django
when i try to add stripe to this project https://github.com/justdjango/django-ecommerce i have got this error Request req_5BdKqxhl1rXEbe: No such customer: cus_FLh58K7EslblSw even I added secret key and public key to the project same issue -
Getting the next Item in a queryset
Here's a snippet from Voting web project, and i'm trying to get the next category after voting @login_required def Nominees(request, category_id): categories = Category.objects.get(id=category_id) next_category = categories.id +1 college_id = categories.College.id if lastday < today: messages.info(request, "Window closed") context = {'categories':categories, 'college_id':college_id, 'lastday':lastday, 'today':today,'next_category':next_category} return render(request, 'nomination/contestants.html', context ) def Voting(request): if request.method == "POST": vote_user = request.POST.get('vote_user') vote_contestant = request.POST.get('vote_contestant') vote_category = request.POST.get('vote_category') next_category = request.POST.get('next_cat') vote_college = request.POST.get('vote_college') college = College.objects.get(pk=int(vote_college)) college_id = college.id nex = int(next_category)-1 try: Vote.objects.filter(user_id=request.user.id, category_id=vote_category)[0] messages.error(request, "You've already voted") return HttpResponseRedirect(reverse('nomination:nominees', args=(vote_category,))) except(IndexError, Vote.DoesNotExist): if lastday < today: messages.error(request, "Too late") return HttpResponseRedirect(reverse('nomination:nominees', args=(vote_category,))) else: new_vote = Vote(contestant_id=vote_contestant, category_id=vote_category, college_id=vote_college, user_id=vote_user) new_vote.save() messages.success(request, "Successfully voted!!") try: categories = college.category_set.filter(id=next_category, College_id=college_id)[nex] category_id=categories.id return HttpResponseRedirect(reverse('nomination:nominees', args=(category_id,))) except (IndexError, Category.DoesNotExist): categories = college.category_set.first() category_id = categories.id return HttpResponseRedirect(reverse('nomination:categories', args=(college_id,))) I would also appreciate it if i could get a better way of doing this like maybe using the nect function which ive tried but still it;s giving me issues, thank you so much -
How to add an attribute to request like the 'user' variable
I want to create a new variable which is always available like how the 'user' variable works. Here is my myapp/context_processors.py def patient_selected(request): print(hasattr(request, 'patient_selected_id')) print( 'patient_selected_id' in locals()) print( 'patient_selected_id' in globals()) if not hasattr(request, 'patient_selected_id'): request.patient_selected_id = 0 return {"patient_selected_id": 0} The problem is, it always prints 'false'. It seems like I cannot add an attribute to the request, nor create a variable constantly available. BTW, I have added this context_processors.py to settings. Here is my setting: 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', 'hrs.context_processors.patient_selected', ], }, }, ] -
Django server inaccessible
I have a Django 2.2.5 server running on a Windows 7 machine. I'd like to access it from my Android phone to make sure that the website being served by the Django server works well on the Android device. However, the website fails to load on the Android device. I've look around and found some things to try, but nothing has worked. Here'a list of things I've tried, all of which have failed: Debug = False ALLOWED_HOSTS = ['*'] Allowing any traffic through port 8000 through firewall Turning firewall off Accessing from raspberry pi I've also tried some testing on the Windows 7 machine: When ALLOWED_HOSTS = [], I can access the site with localhost:8000/my_site and 127.0.0.1:8000/my_site, but not my_ip_address:8000/my_site. This may be expected behavior, and I am okay with that. When ALLOWED_HOSTS = ['localhost', my_ip_address], if I'm not mistaken, localhost:8000/my_site should work, 127.0.0.1:8000/my_site should not work, and my_ip_address:8000/my_site should work. As expected, localhost:8000/my_site works and 127.0.0.1:8000/my_site does not work. my_ip_address:8000/my_site, however, does not work. Can anybody explain this to me and help me access my Django server from my Android phone? -
AJAX success not render properly since second request
I use ajax to render output to below HTML element. <p class="result-box" id="result-box">The result is : <br><strong id="result"></strong></p> When I update my input, the console changes and prints desired data but the webpage including the text does not change. I get Cannot read property 'setAttribute' of null at canvas_and_ploton the 2nd+ time refresh below, If I remove setAttribute, I get Cannot read property 'getAttribute' of null at canvas_and_plot. $(document).on('submit','#cat_select',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat_select', data:{ l2:$('#l2').val(), l3:$('#l3').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function server_response(response) { const r = JSON.parse(response); console.log(r); //refreshed var cat_result = r.cat_result; console.log(cat_result[0]) //refreshed, below rendering to HTML does not refresh var text=$('<i></i>'); $.each(cat_result, function(idx, value) { text.append('<id="result'+idx+'">' + cat_result[idx][0]+ '<br>'); text.append('<canvas id="canv_'+idx+'" width="200" height="200"></canvas><br>'); }); $('#result').replaceWith(text); $.each(cat_result, function(idx, value) { canvas_and_plot(idx,cat_result[idx][9],cat_result[idx][10],cat_result[idx][11])}); } function canvas_and_plot(idx,a,b,c) { var canv = document.getElementById('canv_'+idx); canv.setAttribute('id', 'canv_'+idx); var C = document.getElementById(canv.getAttribute('id')); //plot... } I tried adding cache: false and adding random number to the url but neither of them works. Why only error after the first request? How can I fix this? Thanks -
Error occurring when setting up postgresql with Django
I am creating a project in Django which aims to use postgresql as the database. I have gone into the settings file added all the required properties to setup the postgresql database. When I attempt the run the server, a prompt to install psycopg2-binary occurs. This is expected, as I have encountered this issue in my other projects. When I install in my other projects, It successfully gets installed and I can apply migrations and run the server. However for this project, when I type in pipenv install psycopg2-binary, an error occurs which I haven't encountered before. Error: `exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /var/folders/wq/c85_j_cd4n7by1kyz4z2_yq40000gn/T/tmpthm8df6cbuild/psycopg2-binary/` Note that I am using the latest version of python(3.8), and the latest version of pip. Anyone know how to fix this and successfully complete the install of psycopg2-binary? Thank you. -
How to login with e-mail in Django?
I am trying to change the way the user do log in by changing from username to email. I put in settings.py: AUTHENTICATION_BACKENDS = ['apps.myapp.ModelBackend'] In myapp I created the file backends.py with the code: from django.contrib.auth import backends, get_user_model from django.db.models import Q UserModel = get_user_model() class ModelBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: # user = UserModel._default_manager.get_by_natural_key(username) # You can customise what the given username is checked against, here I compare to both username and email fields of the User model user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) And on myapp in models.py I did: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): USERNAME_FIELD = 'email' email = models.EmailField(unique=True, name='email address') REQUIRED_FIELDS = [] But when I run makemigrations I get the following error: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for … -
How to add a new pip package to a deployed application with heroku
I have deployed a django rest api with heroku. And I have some updates regarding the code, For updating the source code is easy just updating the source code and commit changes with git. But I have trouble adding a new pip package. Is there a solution for this problem or do I need to re-deploy the application? -
Encrypting communication between between Microservices
I am dealing with communication between microservices. Microservice A - Angular6/django Microservice B - NodeJS My Microservice A is in company network and Microservice B is in AWS. we need to find a way to communicate between them securely like using VPN or other encryption. what is the best way to architecture this communication? -
Django and JQuery - Find and Replace Text
I want to transfer data from one tag to the other. This is how far I got: <a id="oldartist"> {{ object.user }}</a> <a id="newartist"></a> function newArt() { var artistname = document.getElementById("oldartist"); $('#newartist').text(artistname); }; But I get https:// mywebsite.com/johndoe instead of johndoe Why is this happening and how can I fix it? Thank you for any help -
Getting token of user
I am new to django/python. I currently use api-token-auth to generate user auth token successfully. But i will like to write an api function to get and validate the token before executing. ie my app need validated user to access certain resources. How can i write the get the valid auth token and pass it to the rest of the process? I am using the below code but get errors Thank you -
DRF - combine django_filter and ordering
I use drf alongside with django-filters. The problem is I can't make work django-filters with ordering. from django_filters import rest_framework from rest_framework import viewsets from feeds_core.imports.models import SourceFeedFetch from feeds_core.imports.serializers import SourceFeedFetchSerializer from products.filters import ProductFilter from products.models import Product from products.serializers import ProductSerializer class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer filter_backends = (rest_framework.DjangoFilterBackend,) filter_class = ProductFilter def get_queryset(self): return Product.objects.all() class ProductFilter(FilterSet): ordering = OrderingFilter( fields=( ('name', 'name'), ), ) class Meta: model = Product fields = {'name': ['icontains']} When I go to http://127.0.0.1:8000/api/products/ it raises: TemplateDoesNotExist at /api/products/ django_filters/rest_framework/form.html Do you know what is wrong with that? -
ImportError: cannot import name 'OrderDetailView' from 'core.api.views' in Django and ReactJs
after i Build OrderDetailView Class, i run python manage.py migrate in backend it show error as from .views import ( ImportError: cannot import name 'OrderDetailView' from 'core.api.views' (C:\Users\Dell\project7\core\api\views.py) In frontend, it show an error as Network Error "message":"Network Error","name":"Error","stack":"Error: Network Error\n at >createError (http://localhost:3000/static/js/0.chunk.js:1970:15)\n at XMLHttpRequest.handleError api > urls.py from django.urls import path from .views import ( ItemListView, AddToCartView, OrderDetailView ) urlpatterns = [ path('product-list/', ItemListView.as_view(), name='product-list'), path('add-to-cart/', AddToCartView.as_view(), name='add-to-cart'), path('order-summary/', OrderDetailView.as_view(), name='order-summary') ] api> views.py from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.utils import timezone from rest_framework.generics import ListAPIView, RetrieveAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from core.models import Item, OrderItem, Order from .serializers import ItemSerializer, OrderSerializer class ItemListView(ListAPIView): permission_classes = (AllowAny,) serializer_class = ItemSerializer queryset = Item.objects.all() class OrderDetailView(RetrieveAPIView): serializer_class = OrderSerializer permission_classes = (IsAuthenticated,) def get_object(self): try: order = Order.objects.get( user=self.request.user, ordered=False) except ObjectDoesNotExist: return Response({"message": "You do not have an active order"}, status=HTTP_400_BAD_REQUEST) constants.js const localhost = "http://127.0.0.1:8000"; const apiURL = "/api"; export const endpoint = `${localhost}${apiURL}`; export const productListURL = `${endpoint}/product-list/`; export const addToCartURL = `${endpoint}/add-to-cart/`; export const orderSummaryURL = `${endpoint}/order-summary/`;