Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static css file not loading in Django admin
I'm trying to load my own css file to replace base.css in order to customize Django Admin {% extends "admin/base.html" %} {% load static %} {% block title %}VSPM{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block stylesheet %}{% static "admin/css/theme.min.css" %}{% endblock %} {% block nav-global %}{% endblock %} But the css file isn't loading in Django admin. What am I doing wrong? -
resolve pipenv install weasyprint error in Docker
I'm using Alpine linux for my Docker setup. Here is the Dockerfile. # pull official base image FROM python:3.7.4-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk --update --upgrade --no-cache add cairo-dev pango-dev gdk-pixbuf RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev jpeg-dev zlib-dev libffi-dev\ && apk add postgresql \ && apk add postgresql-dev \ && pip install psycopg2 \ && apk add jpeg-dev zlib-dev libjpeg \ && pip install Pillow \ && apk del build-deps # install dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /usr/src/app/Pipfile RUN pipenv install --skip-lock --system --dev # copy entrypoint.sh COPY ./entrypoint.sh /usr/src/app/entrypoint.sh # copy project COPY . /usr/src/app/ # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] which results in stalling on the installation of cairocffi and giving the error of unable to execute 'gcc': No such file or directory. -
Django Questionnaire application
I would like to create a questionnaire application. I would like to be able to create each question and their answer using the Django admin panel. I have designed such a model as below to store questions and answers. class Question(models.Model): question = models.TextField() class Answers(models.Model): question = models.ForeignKey(question, on_delete = models.PROTECT, related_name = 'answers') answer = models.TextField() I would be appreciated if you could help me to design a Model to store answers, View, and if required, Custom Form. Thank you, -
How to get objects like Bolean Field options? DJANGO
thanks for your time. By creating an object(product) i'd like to get the option to choose in a list of all my other objects (5 of them) to appear bellow the product. Like a recommended list. Although they don't have a field or category in common. I'd like to let the user of my software set the five of them manually to display for his client. is there something like: class Product (models.Model): name = models.CharField(max_length=100) related_products = models.CharField(choices=Product.objects.all()) or something like: def get_queryset (self): return Product.objects.all() class Product (models.Model): name = models.CharField(max_length=100) for p in queryset related_products = models.CharField(choices=Product.objects()) or like: class Product (models.Model): name = models.CharField(max_length=100) class Related_product (models.Model): product = models.ForeignKey(Product) -
Override Django admin's css
I want to replace Django admin's default base.css. I did something like this: {% extends "admin/base.html" %} {% block title %}VSPM{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block stylesheet %}{% static "admin/css/theme.min.css" %}{% endblock %} {% block nav-global %}{% endblock %} Theme.min.css is my css. But I get the following error: TemplateSyntaxError at /admin/accounts/institute/ Invalid block tag on line 9: 'static', expected 'endblock'. Did you forget to register or load this tag? What am I doing wrong? How do I override the css? -
Django serialize for specific id
I am using the serialize method to get a json of a Model object. However it does not work when I pass in a specific id. data = serialize('json', Sample.objects.get(id=1), use_natural_foreign_keys=True) print(data) It seems to only work when you get the entire model's content by all() i.e.: data = serialize('json', Sample.objects.all(), use_natural_foreign_keys=True) -
function should call after several hours with some parameters
I have a configuration like this Employee -> Manager Employee submits a transaction, it goes to the manager and the manager verifies it. I want to add a new configuration. Auto-action after some time(5-6 hours). If the manager is not taking action(verifying it) on Transaction, it will be auto-action according to my configuration. I can use SQS but it gives me only max 2hrs delay to process any function. Now I am thinking about using Redis, pushing an entry to Redis for some time according to config after it expires I will evaluate my function(auto-verify). Multiple employees can submit any number of Transactions for each Transaction I have to push a task to the queue and after each time it should call my function and dequeue from the queue. For Example: 1) Transaction1 is submitted on 6am and this employee has config of 4hrs then at 10am it should auto verify. -
Dropdown menu with django and Semantic UI does not work
there. I am stacking to make a dropdown menu with Django and Semantic UI. I'd like to adopt Semantic UI to the Django dropdown menu. How can I make it? My code form1_1.py EMPTY_CHOICES = ( ('', '-'*10), ) CHOICES = ( ('one', '1人'), ('multiple', '複数'), ) class Page1_1(forms.Form): defendant = forms.ChoiceField( label='複数ですか?', widget=forms.Select, choices=EMPTY_CHOICES + CHOICES, required=True, ) form1_1.html <form method="post" action="{% url 'page1_2'%}"> {% csrf_token %} <div> <lavel>{{ form.defendant.label }}</lavel> </div> <div class="ui selection dropdown"> <i class="dropdown icon"></i> {{ form.defendant }} </div> </form> What I have tried to... I have seen this code, but it does not work Versions Semantic UI 2.4 Python 3.7.5 django (3, 0, 2, 'final', 0) -
POST IS SEARCHED FOR USERS IN USER DATABASE AND TURNED INTO PROFILE LINK WITH ORIGINAL TEXT
Hey guys I'm new to Django and trying to get a certain thing to work so sorry if I have made previous posts but I'm making great progess. What I'm trying to do is when a user submits a post to the database it's scanned to see if a user is mentioned in it so that when it renders as html it turns that user mentioned in the post into a url link for that users profile along with the original text. So the post is the same just if a user is mentioned it's the users name as a link to his or her profile in the original text. This is what's rendering right now when a post is submitted. post that is submitted by user as you can see @devil is a user and it's username with link appears above it but not in the post data. How would I go about doing it so that the post is checked for a user in the database if it as the symbol "@" in front of it and returns the username as a link to it's profile. This is views.py code for the post submission as you can see … -
Form not displaying on Django site
I have just started learning Django and I have hit a little snag and was hoping someone could help. Problem: My form is not displaying in my main HTML template (ingredior.html) but the form will display in my test HTML template (test.html) which is just a boiler plate HTML file with the {{form1}} tag in the body. I am changing "return render(request, 'ingredior/ingredior.html', context)" in the views.py file manually to test the two different HTML templates. Question: Why is the form working in the test.html and not the ingredior.html file when changed? Please keep in mind that I am swapping this line of code "return render(request, 'ingredior/ingredior.html', context)" with "return render(request, 'ingredior/test.html', context)" to test between the two. CODE--------- Forms.py from django import forms class UserInput(forms.Form): base_search_ingredient = forms.ChoiceField(choices=[('vegan', 'Vegan'), ('vegatarian', 'Vegatarian')]) views.py from django.shortcuts import render import requests from .local_api_key import Key from .forms import UserInput def index (request): app_id = Key.app_id app_key = Key.app_key search_from = 0 search_to = 100 form1 = UserInput() test = [] if request.POST.get('search'): test2 = request.POST.get('search') intolerance = test2 url = requests.get(f"https://api.edamam.com/search?q={intolerance}&excluded=egg&excluded=beef&excluded=dairy&excluded=tomato&excluded=cherry%20tomatoes&excluded=rice&excluded=corn&excluded=soy&excluded=onion&from={search_from}&to={search_to}&health={intolerance}&app_id={app_id}&app_key={app_key}").json() recipe_length = (len(url['hits'])) else: intolerance = 'vegan' url = requests.get(f"https://api.edamam.com/search?q={intolerance}&excluded=egg&excluded=beef&excluded=dairy&excluded=tomato&excluded=cherry%20tomatoes&excluded=rice&excluded=corn&excluded=soy&excluded=onion&from={search_from}&to={search_to}&health={intolerance}&app_id={app_id}&app_key={app_key}").json() recipe_length = (len(url['hits'])) for urls in range(recipe_length): recipe_name = (url['hits'][urls]['recipe']['label']) recipe_url … -
Dynamic webpage using django and python
I am unable to connect my javascript file in with my html page in my django app. I have created a separate folder and placed the script.js. Inside html file; <html> <body> <script src="JS files/script.js"></script> </body> </html> -
Custom permission not passing to generic views django rest
I am writing custom permission and inheriting in the generic views but it is not working it returns TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User? instead of User required to perform this action my custom permission as follow class IsOwnedByUser(permissions.BasePermission): def has_object_permission(self, request, view, obj): message = {'detail': 'User required to perform this action'} return obj.user == request.user views.py class OrderAddressView(generics.ListCreateAPIView): queryset = OrderAddress.objects.all() serializer_class = OrderAddressSerializer permission_classes = (IsOwnedByUser,) def perform_create(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): return OrderAddress.objects.filter(user=self.request.user) BTW, it works fine with default rest framework permission class when I use like this permission_class = (permissions.IsAuthenticated,) but with my custom permission it is not working( Can anyone tell why it is that? Thanks in advance! -
I have a list of users id , i want to check every userid available or not, if not i want to get the follwing id which is not available
Here is the code that i have tryed staffids = [1,2,4,5,6,7] # up_obj = UserProfile.objects.filter(userId__in = staffids) #i will explain it below flag=0 unknown = [] for x in staffids: up_obj = UserProfile.objects.filter(userId=x) if up_obj.exists(): print(up_obj) else: flag=1 unknown.append({ "id": x }) if flag == 1: return Response({ STATUS:False, MESSAGE:"User not found", DATA:unknown }) This code returns only the available users up_obj = UserProfile.objects.filter(userId__in = staffids) suppose if the userid 3,4 not available , this code return the queryset with out 3,4. If all id are not present i want to return a message that the following ids are not available or somethis else..., i have tryed but im looking for a better way for doing this Is there any buildin method in django? -
i want to give permissions to superuser and staffuser to create post, in my case it's not working. any help would be appreciated
whenever i testing this code, it's showing that, "detail": "Authentication credentials were not provided." views.py from rest_framework import permissions import rest_framework class AdminAuthenticationPermission(permissions.BasePermission): ADMIN_ONLY_AUTH_CLASSES = [rest_framework.authentication.BasicAuthentication, rest_framework.authentication.SessionAuthentication] def has_permission(self, request, view): user = request.user if user and user.is_authenticated: return user.is_superuser or \ not any(isinstance(request._authenticator, x) for x in self.ADMIN_ONLY_AUTH_CLASSES) return False class ProductCreateAPIView(generics.ListCreateAPIView): model = Product queryset = Product.objects.all() serializer_class = DemoAppProductCreateSerializer permission_classes = [AdminAuthenticationPermission,] -
Unable to override admin templates in Django 3.0
Here is my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' And here is my template base_site.html in templates/admin/accounts/ (accounts is my app name): {% extends "admin/base.html" %} {% block title %}School name{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} But this template is not overriding existing templates -
How to create a downloadable URL for a zip file in Django?
I am trying to create a webpage that has a table where one of the columns in that table downloads a particular file that resides in my computer. The file that is supposed to be download is based on the ID number of that row.(ID is a column in my table) Ex. If the user clicks on the URL that is in the 3rd row then the file named '3.zip' in my local files should get downloaded. I have tried the <a href="<path>" download> in my HTML template file but I realized in Django the method is different. Then I used the HTTPResponse as an attachment method. This is my Views.py code for download. def download_file(request): fl_path = '/home/harish/Desktop/cvision/users_output_files/5/5.zip' filename = '5.zip' with open(fl_path, 'r') as zip_file: response = HttpResponse(zip_file, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"'%filename return response Urls.py urlpatterns = [ path('',views.homepage), path('add',views.datapage), path('newdata',views.newdata), path('newuser',views.newuser), path('download_file/',views.download_file) ] So, When I go to path http://127.0.0.1:8000/download_file the file is supposed to get downloaded. But instead I get an error. 'utf-8' codec can't decode byte 0xeb in position 10: invalid continuation byte If we ignore the Encoding error how can I solve the problem of downloading a particular file from local folders based … -
Django: UserCreationForm not getting Custom User Class
I'm new to django and I;m running into an odd issue. Using django 2.2.5 I've created a custom User class, sub-classed from AbstractBaseUser. Other than extending AbstractBaseUser the only major change I made was deleting the username field and adding my own (won't get into why here). I've added the USERNAME_FIELD = "my new username" to the model as well. This all appeared to work well and I was able to create users. I then installed django-registration, to use that functionality and when I tried to makemigrations I ran into this error: 'django.core.exceptions.FieldError: Unknown field(s) ("My new username") specified for User` Now this didn't make any sense to me since the model clearly has a"My new username" field and I'd specified django should use my User model in setting via AUTH_USER_MODEL. I knew that was working because calling get_user_model() in a shell returned my custom model. Now here's where it gets weird, I was able to trace the issue to django-registrations, RegistrationForm. This is a from that subclasses django's UserCreationForm. When RgistrationForm was loading or whatever during makemigrations it was producing the error because the model reference for the form was django.User not my custom user model. RegistrationForm does not … -
Reverse for with arguments '('', '', '', '')' not found. 1 pattern tried error
I am adding a URL in my page to download CSV. Below is the URL. I am getting below error. Reverse for 'kitty_download' with arguments '('', '', '', '')' not found. 1 pattern(s) tried: ['kitty_download/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)$'] CSV Download Path is Below. path('kitty_download///', views.kitty_download, name='kitty_download') View def kitty_download(request,codep,slotp,customerp): url_name = request.resolver_match.url_name print(url_name) print(codep) print(slotp) print(customerp) kitty_members = kitty_member.objects.all().order_by('cretime') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] ='attachment; filename="kitty_member.csv"' writer = csv.writer(response, delimiter = ',') writer.writerow(['kitty Member Details']) writer.writerow([]) writer.writerow(['Code','Slot','Customer','Status']) for i in kitty_members: writer.writerow([i.code,i.slot,i.customer,i.status]) return response -
how to call a value list with variables in for range | django
I have difficulty in printing the list in sequence, I've done my best still :( tool/views.py class aswq(FormView): form_class = AswqForm template_name = "tool/aswq.html" context_object_name = "result" def post(self,request): if request.method == "POST" or "post": self.query = request.POST['query'] self.context = { 'anime_title':[], 'thumbnail':[], } self.results = AnimeSearchWithQuery.keyword(self.query) self.var = 0 for self.result in range(0,len(self.results['title'])): self.context['anime_title'].append(self.results['title'][self.var]) self.createdAt = self.results['createdAt'][self.var] self.updatedAt = self.results['updatedAt'][self.var] self.startDate = self.results['startDate'][self.var] self.endDate = self.results['endDate'][self.var] self.nextRelease = self.results['nextRelease'][self.var] self.status = self.results['status'][self.var] self.subtype = self.results['subtype'][self.var] self.popularityR = self.results['popularityRank'][self.var] self.ratingR = self.results['ratingRank'][self.var] self.favoritesC = self.results['favoritesCount'][self.var] self.synopsis = self.results['synopsis'][self.var] self.context['thumbnail'].append(self.results['thumbnail'][self.var]) self.var += 1 return render(request,'tool/result.html',{ 'results':self.context, "range":range(0,len(self.context['anime_title'])) }) template, tool/result.html {% extends "base.html" %} {% block title %} {% endblock title %} {% block content %} {% for i in range %} {{results.anime_title.i}} {% endfor %} {% endblock content %} if it's in python it's like this list = {'sub':['en','id'],'genre': ['horror','games'],} for i in range(0,len(list['sub'])): print('subtitle: {}'.format(list['sub'][i])) print('genre : {}'.format(list['genre'][i])) can django do such a structure?, thanks if i can't explain / bad english -
Getting errors while trying to integrate django-private-chat in my application?
I am working on an application where I want to implement the django-private-chat in for one to one messaging feature after I did everything which is said in the documentation I ran the server and got to the link http://127.0.0.1:8000/dialogs/ I am getting the blank page and when I see in console I am seeing this javascript error please help me out I have included the error traceback also My dialogs.html: {% extends "django_private_chat/base.html" %} {% load static %} {% load i18n %} {% block css %} <link href="{% static "django_private_chat/css/django_private_chat.css" %}" rel="stylesheet" type="text/css" media="all"> {% endblock css %} {% block content %} <input id="owner_username" type="hidden" value="{{ request.user.username }}"> <div class="container"> <div class="col-md-3"> <div class="user-list-div"> <ul> {% for dialog in object_list %} <li> {% if dialog.owner == request.user %} {% with dialog.opponent.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a> {% endwith %} {% else %} {% with dialog.owner.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a> {% endwith %} {% endif %} </li> {% endfor %} </ul> </div> </div> <div class="col-md-9"> <div class="row"> … -
disadvantages to using ACCOUNT_CONFIRM_EMAIL_ON_GET
using Django rest-auth and allauth, using a rest api. I have ACCOUNT_CONFIRM_EMAIL_ON_GET=True. in the documentation it gave a warning about this. Are there any major disadvantages to this? this method seems to be perfect for me and i would like to know what trouble this could cause in the long run. -
How can I return to back page after create django?
After Create moneylog, I want to got back to moneybook_detail, so I made a moneylog/View.py: class moneylog_create(FormView): form_class = forms.CreateMoneylogForm template_name = "moneylogs/create.html" def form_valid(self, form): moneylog = form.save() moneybook = moneybook_models.Moneybook.objects.get( pk=self.kwargs["pk"]) form.instance.moneybook = moneybook moneylog.save() form.save_m2m() return redirect(reverse("moneybook:detail", kwargs={'pk': self.kwargs["pk"]})) and this is Moneybook/urls.py app_name = "moneybooks" urlpatterns = [ path("create/", views.moneybook_create.as_view(), name="create"), path("update/<int:pk>/", views.moneybook_update.as_view(), name="update"), path("<int:pk>/", views.moneybook_detail, name="detail") ] How can I return to moneybook_detail after create moneylog? -
Getting Javascript error while integrating django-postman into django project?
I am working on an application where I want to implement the django-private-chat in for one to one messaging feature after I did everything which is said in the documentation I ran the server and got to the link http://127.0.0.1:8000/dialogs/ I am getting the blank page and when I see in console I am seeing this javascript error please help me out I have included the error traceback also My dialogs.html: % extends "base.html" % {% load static %} {% load i18n %} {% block css %} {{ block.super }} <link href="{% static "django_private_chat/css/django_private_chat.css" %}" rel="stylesheet" type="text/css" media="all"> {% endblock css %} {% block content %} <input id="owner_username" type="hidden" value="{{ request.user.username }}"> <div class="container"> <div class="col-md-3"> <div class="user-list-div"> <ul> {% for dialog in object_list %} <li> {% if dialog.owner == request.user %} {% with dialog.opponent.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a> {% endwith %} {% else %} {% with dialog.owner.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a> {% endwith %} {% endif %} </li> {% endfor %} </ul> </div> </div> <div … -
Django + Apache + Mobile Initiating Download Instead of Serving Page
I have a webapp that uses the following tech stack : Apache running on Amazon EC2 Instance Django, serving via WSGI Javascript compiled via webpack / babel Things are working great on a desktop environment, but on mobile, it is completely non-functional. When I navigate to the home page, mobile browsers try to initiate a download rather than serving the page. I've been beating my head against the wall for a few days trying to figure out what is going on, but I don't have any leads. Here is my webpack.config.js, since I think that's the most likely place for a problem : const path = require('path'); const webpack = require('webpack'); const autoprefixer = require('autoprefixer'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const BundleTracker = require('webpack-bundle-tracker'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const SentryCliPlugin = require('@sentry/webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const devMode = process.env.NODE_ENV !== 'production'; const hotReload = process.env.HOT_RELOAD === '1'; const styleRule = { test: /\.(sa|sc|c)ss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { plugins: () => [autoprefixer({ overrideBrowserslist: [ 'last 2 Chrome versions', 'not Chrome < 60', … -
Docker mariadb and django
I have up and running docker image for MariaDB10.4.11. when i connect with django project it gives me following error: django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'172.18.0.4' (using password: YES)") I can login into MariaDB with same credential, which I am using in setting.py file. This is my docker-compose file configuration. db: image: mariadb:10.4.11 environment: MYSQL_DATABASE: bookstore MYSQL_USER: bs MYSQL_PASSWORD: xxxxx MYSQL_ROOT_PASSWORD: xxxx restart: on-failure volumes: - mariadb_data:/var/lib/mysql volumes: mariadb_data: Any help will highly appreciate. Thanks