Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker and webpack bundle generates locally but not in container
Can't get webpack to bundle react.js inside docker. My webpack configs and frontend bundle properly. The issue has to do with docker integration. When I run webpack before the docker container is up, or while the container is up, webpack generates bundles and they are copied into the container. This works and I could develop this way, but it feels sloppy. Instead, I want npm run build to run webpack in production mode inside the docker container. That way it generates bundles on its own if I just say docker-compose build and up. I already have a docker container with a django backend working. All I need is for webpack to use babel to transpile the react code in djangoproj/static/js and move it to djangoproj/static/bundles. Once the file is bundled to that folder the rest on the django side works and the page is rendered. It is worth noting that I don't get errors other than a 404 because the bundle isn't there. My output in the console shows that webpack uses babel to transpile and then bundles the code. However, after a docker ps and a docker exec on the django container, the bundles are not generated. Nor is … -
Django AWS S3 loads wrong url?
So I have AWS S3 setup to let users upload images and that works fine. However when loading the images the url that is loaded to the src is different to the one when accessing the image directly from the AWS console Loaded src: https://{bucket name}.s3.amazonaws.com/uploads/{file name}.png URL in AWS dashboard: https://{bucket name}.s3.us-east-2.amazonaws.com/uploads/{file name}.png Is the fact that the src doesn't include .us-east-2. the reason the image won't load? -
Using static I can load one css file but am having an issue loading another in the same directory
I have a 'base.html' file and a 'base.css' file, all other .html files extend 'base.html.' Using static to load the 'base.css' is working without a problem. It is when I try to have my 'index.html' extend 'base.html' and then also load the 'index.css' file that I am running into an issue. If I go to the js console and click 'sources' it will say 'Could not find the original style sheet.' in reference to 'index.css'. I am not sure why this is happening. Here is the directory for the app 'core': core/ templates/ core/ base.html index.html static/ core/ base.css index.css Base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Generic</title> <meta name="description" content="DESCRIPTION"> <link rel="stylesheet" href="{% static 'core/base.css' %}"> <!-- loading without issue --> {% block head %} {% endblock %} </head> <body> {% block body %} {% endblock %} </body> </html> index.html: {% extends "core/base.html" %} {% load static %} {% block head %} <link rel="stylesheet" href="{% static 'core/index.css' %}"> <!-- not loading --> {% endblock %} {% block body %} <!-- content --> {% endblock %} Thanks in advance for any help. -
How to exclude specific field types in a template form loop
I am using django_widget_tweaks to loop over form fields: {% for field in form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} This displays a happy Bootstrap4 compliant interface, except when displaying fields like radio when I need to use a custom-control class not the form-control class. How can I filter the form field loop to exclude radio inputs so I can write this code separately? -
Django, searching with custom QuerySet, erroneously returning empty object
forgive me if this has been answered before, I have searched Stackover flow and I haven't seen any questions/answers that my problem If you know one that matches please point me there I have a Django project set up (version 1.11) Along with Python 3.5.3 I have an app called Product and I wish to search its database its model.py looks like this: import random import os from django.db import models from django.db.models import Q from django.db.models.signals import pre_save from django.core.urlresolvers import reverse from .utils import unique_slug_generator def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): new_filename = random.randint(1, 1000000) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename ) class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(featured=True, active=True) def featured(self): return self.filter(featured=True) def search(self, query): lookups = (Q(title__icontains=query) | Q(description__icontains=query)| Q(price__icontains=query)) result = self.filter(lookups).distinct() print(result) return self.filter(lookups).distinct() class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self): return self.get_queryset() def featured(self): return self.get_queryset().featured() def get_by_id(self, id): qs = self.get_queryset().filter(id=id) # Product.object if qs.count() ==1: return qs.first() return None def search(self, query): return self.get_queryset().active().search(query) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99) image = models.ImageField(upload_to='products/', … -
Django effective way to use prefetch_related or select_related
I regularly use prefetch_related & select_related to process nested queries in one go. I would like you to know what we can do more to make it a little more faster. Foo.objects.prefetch_related('bar') There are some cases in my application where I just need only particular columns if Bar model. Does using custom queryset in prefetch_related method like below, boost the speed of the query? Foo.objects.prefetch_related(Prefetch('bar',queryset=Bar.objects.all().only('id)' -
How to Parse pdf from Django InMemoryUploadedFile?
I want to read files dynamically As i am giving pdf file from django the type of file it is having class 'django.core.files.uploadedfile.TemporaryUploadedFile' if i read the file it will have only bytes which is not understandable. Below is my code def file(request): pdf = request.FILES['file'] pdf1 = (pdf.read()) if i print the question i am getting bytes which is not understandable.so how to read pdfs from django dynamically and get text by using django -
Error During installing this library " pip install bcrypt" in django
I got an error while installing bcrypt in Django Command "python setup.py egg_info" failed with error code 1 in C:\Users\Hassan\AppData\Local\Temp\pip-install-w128k6kc\cffi\ ---------------------------------------- Command "C:\Users\Hassan\PycharmProjects\django_level_5\venv\Scripts\python.exe C:\Users\Hassan\PycharmProjects\django_level_5\venv\lib\site-packages\pip-19.0.3-py 3.8.egg\pip install --ignore-installed --no-user --prefix C:\Users\Hassan\AppData\Local\Temp\pip-build-env-ky7v9nxx\overlay --no-warn-script-location --no-binary : none: --only-binary :none: -i https://pypi.org/simple -- setuptools>=40.8.0 wheel "cffi>=1.1; python_implementation != 'PyPy'"" failed with error code 1 in None -
Application Architecture in Python, is this the right way?
I am developing a Client-Server Application along with the Mobile Application and want to use Python for the same. This is my idea of architecture What should I keep in mind if I want this model to be Scalable? My Application will require multiple schemas. Will this architecture be sustainable in the long run? -
403 error while attempting to get photo from MariaDB in Django project
Problem I am having troubles displaying images on my server. I am creating posts/images using the Django Admin page and they are being sent to my MariaDB and the media/images folder in my folder structure. I have verified that they are located on the server using mysql -u root -p and selecting from the db. When I load the page, I get the proper styling and the photo title and description are shown but the image is not. The networking tab shows a 403 error for the image. For my html, I am using <img src="{{ photo.img.url }/> This was working on my local host while using sqlite3, but I am trying to use MariaDB on my Linux server. I'm not sure if this is a permissions error or something else. I did have to change many permissions going from local to the server using sudo chmod -R 775 [folder_name]. Things I've Tried I tried using select @@datadir to find where the MariaDB was located and cd'ed into it. I then tried changing the group to www-data and changing the permissions but that did not work. I've tried googling this issue but I can't find anything this specific. The folders … -
querying a django model with foreign key relationship
In my models.py I have a model 'courses'. A course can have one name and one description but multiple links and instructors. I tried to stablish this using foreign key relationship. Now, lets say I want access the name of a particular course, I can do so by c.name where c would be an object obtained by using a filter query. But how would I access lets say the second instructor of that course? Also how would I add a new instructor to that course? class courses(models.Model): name=models.CharField(max_length=200) description=models.TextField() class links(models.Model): link=models.CharField(max_length=200) course=models.ForeignKey(courses,on_delete=models.CASCADE) class instructors(models.Model): inst=models.CharField(max_length=200) course=models.ForeignKey(courses,on_delete=models.CASCADE) -
Django 3 Nested conditionals in templates
I am running into a problem with nested templates in Django 3.0.1. Is is almost certainly a logic issue or wrong placement of the end tags. In the following view I have an issue with the POST bit. What I want to do is this First I try to see if the ticker entered is valid. It does an API call and if the result is an error it moved to another API call that searches for the ticker and displays the various possible stocks. The problem is that now when Error1 occurs the template still tries to execute the "else" block so it returns an error "TypeError at / type str doesn't define __round__ method" (this because the html inside the else block uses a custom template tag). Here is my view def home (request): if request.method == 'POST': ticker = request.POST['ticker'] api_response = requests.get("https://cloud.iexapis.com/stable/stock/"+ ticker + "/quote/?token="+token) try: api = json.loads(api_response.content) except Exception as e: api = "Error1" if api == "Error1": api_response = requests.get("https://cloud.iexapis.com/stable/search/"+ ticker + "/?token="+token) try: api = json.loads(api_response.content) print (api) except Exception as e: api = "Error" return render (request, 'home.html', {'api':api}) else: page = Page.objects.get(slug="home") return render (request, 'home.html', {'page': page}) and the … -
How can I write this django query?
I have the below models in django which represent articles and their sections. Articles have an order/index that represent the article's respective order in a section and sections have an order too so that they can also be sorted with other sections. class ArticleSection(models.Model): title = CharField(max_length=50) order = PositiveIntegerField() # the sections order with other sections def __str__(self): return self.title class Article(Model): section = models.ForeignKey( ArticleSection, on_delete=models.CASCADE) content = CharField(max_length=100) order = PositiveIntegerField() # the articles order in the section its in What I want to do is get a list of articles, sorted by their article order, group them by section and then finally sort by section order. So I essentially the result should look something like this: { section4: [article1, article2, article20], section8: [article1, article2, article3] ... } How can I do this? -
Django ModelForms - How to set default values for junction table
I'm using ModelForms to populate two tables with a Many-to-Many relationship. To simplify the problem description, I'll use the typical example, where there is a Pizza table and a Toppings table, and a pizza can have many toppings and a topping can be on many pizzas. The real application has more complicated tables, but I think it comes down to the relationships defined here: https://docs.djangoproject.com/en/3.0/topics/db/models/#many-to-many-relationships A junction table, where each record consists of pizza_id and a topping_id and a create_time, ties the two tables together. The application has a Modelform for the pizza and the toppings tables, but only a model (no ModelForm) for the junction table. The junction table records are created automatically by django because of the Many-to-Many relationship between the tables. The Pizza model has this "field" : toppings=models.ManyToManyField (Topping, through=PizzaToppingJunction) to define the ManyToMany relationship. In this example, the "create_time field is required to be not null. When the Pizza record is saved, django tries to create the junction table but fails because it has no value for the required field. I'm guessing I should use "through_defaults" but I have not been successful. I tried catching the m2m_changed signal and adding the relationships to pk_set: (pizza.toppings.add … -
Create file, serve for download, delete file on button click, Django template
I have some data that can be used to create a png image if needed. I am trying not to create the png file anywhere unless the user requests the download. I was able to get the downloading to work successfully with: <a href="{% static 'analyze/images/temp.png' %}" download="x_vs_y.png" style="padding: 5px;"> <input type="submit" value="Download Plot"> </a> However, this approach requires the file to already exist somewhere at the 'analyze/images/temp.png' path. I would like to call a separate Django view to do the following: create the necessary file in a temp folder Serve the file for download (similar to how the href download works) delete the temp folder return to original view, the user has the file now I am unsure how to do the 1-3 steps. I thought about calling the view, creating the file, and giving the path of the file. This can then be downloaded with something similar to the following javascript example: <script> function download(file, text) { //creating an invisible element var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8, ' + encodeURIComponent(text)); element.setAttribute('download', file); //the above code is equivalent to // <a href="path of file" download="file name"> document.body.appendChild(element); //onClick property element.click(); document.body.removeChild(element); } // Start file download. document.getElementById("btn").addEventListener("click", function() { … -
How to add datepicker and timepicker to Django forms.SplitDateTimeField using field_classes?
I have a form that splits the date and time from a datetime field in the model. class BooksForm(forms.ModelForm): class Meta: model = Books fields = '__all__' field_classes = {'datetime_created': forms.SplitDateTimeField } How can I add the classes datepicker and timepicker to the widget date_attrs and time_attrs? -
Changing a boolean value with a button in django
I have 2 buttons accept and decline in my requests.html when ever accept is clicked the request_status in my database should change to True and when decline is clicked it should change to False. My problem is that nothing happens when either of these two buttons are clicked.I am using query strings to retrieve the the wanted column from the database. views.py: def requests_leave_days(request, **kwargs): if request.method == 'POST': leaving_request = TimeOffRequest.objects.get(id=kwargs['request_id']) if 'accept_request' in request.POST: leaving_request.request_status = True leaving_request.save() count = {'accepted': 0, 'declined': 0, 'pending': 0} accepted = TimeOffRequest.objects.all().filter(request_status='True') refused = TimeOffRequest.objects.all().filter(request_status='False') pending = TimeOffRequest.objects.all().filter(request_status=None) #counting the number of refusals, acceptions and pending in the database for acceptions in accepted: count['accepted'] += 1 for refusal in refused: count['declined'] += 1 for pending in pending: count['pending'] += 1 return request.user.is_manager( render(request, 'managers/requests.html', { 'accepted' : accepted, 'declined' : refused, 'pending' : pending, 'employees': User.objects.all(), 'workingperiods' : WorkPeriod.objects.all(), 'count' : count}), redirect('news') ) requets.html: <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab"> <table class="table"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Naam</th> <th scope="col">E-mail</th> <th scope="col">Telefoonnummer</th> <th scope="col">Datum</th> </tr> </thead> <tbody> {% for requests in pending %} {% for employee in employees %} {% if requests.user_id == employee.id %} <tr> <th scope="row">{{ employee.id }}</th> … -
Operation Error no such column DJANGO pythonanywhere
So i have made change in my model. I added possibility to add picture. It works fine on my computer, but when i try to apply it on internet on pythonanywhere it does not work properly. There even in admin panel i can not add recipe. I have tried delete migrations and migrate again, but it did not help.. Now the website on the intrnet does not work, but on my local server everything is fine.. I do not know how fix it. My website: http://lui93.pythonanywhere.com/accounts/search/?q=sok OperationalError at /accounts/search/ no such column: drinks_recipe.recipe_image OperationalError at /accounts/search/ no such column: drinks_recipe.recipe_image Request Method: GET Request URL: http://lui93.pythonanywhere.com/accounts/search/?q=sok Django Version: 2.0.13 Exception Type: OperationalError Exception Value: no such column: drinks_recipe.recipe_image Exception Location: /home/Lui93/.virtualenvs/lui93.pythonanywhere.com/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py in execute, line 305 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.6 Python Path: ['/home/Lui93/lui93.pythonanywhere.com', Error during template rendering In template /home/Lui93/lui93.pythonanywhere.com/drinks/templates/drinks/search_results.html, error at line 14 no such column: drinks_recipe.recipe_image -
Is it possible to constantly long-poll from a Django server?
I have a Django server and I'd like to add a component to read from a Redis stream. This will work by putting a blocking read call in an infinite loop. When the thread unblocks, it will write some data to the database. Is there a recommended approach to doing this? Should this be done outside of the main server in a worker? Is it possible to maybe do this in another thread? -
Django Rest Framework creating profile for custom user error:'tuple' object has no attribute '_meta'
I made a custom user,with knox authentication and I want to create a profile for each user, here is what i have for profile model class Profile(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) GENDER = ( ('M','Male'), ('F','Female'), ) username = models.CharField(max_length=150,blank=True) gender = models.CharField(max_length=1, choices=GENDER,blank=True) def create(self,user,username): self.user=user self.username = username return self Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','email','phone_number') class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','email','phone_number','password') extra_kwargs = {'password':{'write_only':True}} def create(self, validated_data): user = User.objects.create_user( **validated_data ) username = validated_data['username'] profile = Profile.objects.create(user=user,username=username) user.set_password(validated_data['password']) return user,profile class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError('Incorrect Credentials') #serializer for profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['username','gender'] username = serializers.CharField(source='User.username') and this for views class UserApiView(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = UserSerializer def get_object(self): return self.request.user class RegisterApiView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self,request,*args,**kwargs): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception=True) user = serializer.save() profile = serializer.save() return Response({ 'user': UserSerializer(user,context=self.get_serializer_context()).data, 'token':AuthToken.objects.create(user)[1], 'profile':ProfileSerializer(profile,context=self.get_serializer_context()).data }) class LoginApiView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class ProfileApiView(generics.RetrieveAPIView): … -
I am using list of checkbox value to filter data in django
I am trying to filter the data in a tabular form using AJAX and JQUERY in django only the filter data by "ram" isn't working, although when an AJAX call is made the GET request is send to the server but the model filter query doesnt run; But when I run the following model filter query in shell it works allproduct = allproduct.filter(Memory__in=ram_list) django app name "graphicsCard" This is my views.py from django.shortcuts import render from .models import Products # Create your views here. # is the filter query correct # def is_valid_queryparam(param): # return param != '' and param is not None # the function that handles filters def productViews(request): allproduct = Products.objects.order_by('-Memory', '-Core_Speed', '-Boost_Clock') if request.method == 'POST' and 'Boost_Clock_min' in request.POST: Boost_Clock_minimum = request.POST.get('Boost_Clock_min') allproduct = allproduct.filter(Boost_Clock__gte=Boost_Clock_minimum) if request.method == 'POST' and 'Boost_Clock_max' in request.POST: Boost_Clock_maximum = request.POST.get('Boost_Clock_max') allproduct = allproduct.filter(Boost_Clock__lte=Boost_Clock_maximum) if request.method == 'POST' and 'Core_Clock_min' in request.POST: Core_Clock_minimum = request.POST.get('Core_Clock_min') allproduct = allproduct.filter(Core_Speed__gte=Core_Clock_minimum) if request.method == 'POST' and 'Core_Clock_max' in request.POST: Core_Clock_maximum = request.POST.get('Core_Clock_max') allproduct = allproduct.filter(Core_Speed__lte=Core_Clock_maximum) # print(request.GET.getlist('ram')) # ram_list = request.GET.getlist('ram') if request.method == 'GET' and 'ram[]' in request.GET: ram_list = request.GET.getlist('ram[]') print(ram_list) allproduct = allproduct.filter(Memory__in=ram_list) print(request.method == 'POST') print(request.POST) # print("####################################################") # … -
i want to pass data from axios to an object in the state
i tried this but it didn't work, i dont know how to get the array labels which is in the object chartData to pass the data to it state = { chartData: { labels:[], datasets:[{ label:'items', data:[] }] } } componentDidMount() { axios.get('http://127.0.0.1:8000/orders/chart/').then(result => { this.setState({ labels:result.data.label, data:result.data.quantity }); console.log(this.state.chartData) }); } and console.log gave me an empty arrays and here is the result Object labels: Array(0) length: 0 __proto__: Array(0) datasets: Array(1) 0: {label: "items", data: Array(0), _meta: {…}} length: 1 __proto__: Array(0) __proto__: Object -
TypeError: 'QueryDict' object is not callable
the error on the title showed to me in this django code views.py : from django.shortcuts import render from django.http import HttpResponseRedirect from .models import userdata def signinView(request) : all_users = userdata.objects.all() return render(request,'signin.html',{'all_items':all_users}) def adduser(request) : c = request.POST('username') d = request.POST('password') new_item = userdata(username=c, password=d) new_item.save() return HttpResponseRedirect('/signin/') urls.py : from django.contrib import admin from django.urls import path from signin.views import signinView, adduser urlpatterns = [ path('admin/', admin.site.urls), path('signin/',signinView), path('adduser/',adduser) ] what should i do to fix the error ? -
How can i deale wth static and media files in django without creating a virtual environnement?
Hello, i want to use pictures in my application, and in the video i am following he used a virtual environment that i don't know how to create. should i create a virtual environment ? if so , how to ? if not , how can i use pictures without creating a virtual environment ?, and what are the the settings i have to do in the settings.py and urls.py files? setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'd0cn(*@vl*liejsapzk2yhoo!$iorw9-hx-43)%mi0g_rf#m$l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'custom.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'custom.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password … -
Which tech stack is good for reporting Asp.net or Python-Django or others?
I am new to the web technologies. I am moving windows app to web app and planning to use python-Django. I have little knowledge on reporting in asp.net but no clue using other frameworks. Could you please provide info on how to generate reports using different web frameworks.