Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OpenStack cloud-config won't run my scripts in windows when I use APIs
My problem is a bit strange, here is the scenario: I want to make a random password ( for ssh ) for every new instance. So I will pass this script in my user_data to OpenStack server. ( I'm using OpenStack APIs ) #cloud-config\npassword: P@ssword\nchpasswd: {{expire: True}}\nssh_pwauth: True It will work properly for my Linux machines ( i.e. ubuntu ) But when I use this command for my windows machines: #ps1\nnet user administrator P@ssword The username and password won't work. I thought maybe my scripts are wrong, so I used the Horizon dashboard and put exactly the same scripts in the user_data text box ( in configuration tab ), and after creating the machine, it worked OK. To sum up, my scripts are working properly on the horizon dashboard. The Linux scripts work Ok in my client ( using APIs ) but the windows command is not working in my client. I've checked the horizon source code and didn't see any difference in passing user_data on windows machines or Linux machines. Thanks a lot. -
How do i make self.request.user.account refer to the new inherited Account?
I am using a ready module "account" and I want to supplement it with the help of inheritance with another attribute "photo". In models.py I create class Account, that inherits from Account from "account" module. extended_account/models.py from django.db import models from account.models import Account class Account(Account): photo = models.URLField(blank=True, default="default") But in views.py I have no idea how to chains my own Account model with PhotoView. self.request.user.account still refers to the Account from "account" model and has no "photo" attribute. How do i make self.request.user.account refer to the new Account in extended_account/models.py? extended_account/views.py from django.views.generic.edit import FormView from account.mixins import LoginRequiredMixin from extended_account.forms import PhotoForm class PhotoView(LoginRequiredMixin, FormView): template_name = "account/new_photo.html" form_class = PhotoForm def get_initial(self): initial = super(PhotoView, self).get_initial() initial["photo"] = self.request.user.account.photo return initial def update_account(self, form): fields = {} if "photo" in form.cleaned_data: fields["photo"] = form.cleaned_data["photo"] if fields: account = self.request.user.account for k, v in fields.items(): setattr(account, k, v) account.save() extended_account/forms.py class PhotoForm(forms.Form): photo = forms.URLField(required=False) -
Django+React: Uploading images to Django media inserted in a Rich Text editor via React
I have a project that solely utilizes Django as web API server and React as its frontend. And I am using Django Rest Framework (DRF) for RESTful API implementation. In this project, I am working on an article module where an author can insert one or more images in between text contents in a rich text editor. Do you have any idea as to the process of communicating React with Django in order to upload those inserted images to my media folder? For sure, the entire article content will be saved as a code snippet (as generated by the rich text editor) that will contain img tags of the inserted images. This code snippet will be saved in my model's content field (TextField). Here is my Article model's struct: class Article(models.Model): title = models.CharField(max_length=250, default="", unique=True) category = models.ForeignKey( ArticleCategory, on_delete=models.DO_NOTHING, related_name="article_category") slug = models.SlugField(max_length=300, unique=True) author = models.ForeignKey( User, on_delete=models.DO_NOTHING, related_name="article_author") content = models.TextField() feature_image = models.FileField( upload_to='article_images/'+str(current_date.year) + "/" + current_date.strftime('%B')) feature_image_caption = models.CharField(max_length=50, default="") publish_date = models.DateTimeField() unpublish_date = models.DateTimeField(blank=True, null=True) published = models.BooleanField(default=False) preapproved = models.BooleanField(default=False) preapproved_by = models.ForeignKey( User, on_delete=models.DO_NOTHING, related_name="article_preapproved_by", blank=True, null=True) approved = models.BooleanField(default=False) approved_by = models.ForeignKey( User, on_delete=models.DO_NOTHING, related_name="article_approved_by", blank=True, null=True) updated_by … -
Django: How to remove a coupon from an order without deleting coupon from database?
Hey guys I have this coupon model, I need to give it a remove functionality (not delete from database), to remove coupon from the order if the customer wishes to. How can I have that functionality? If I use delete(), it will delete the coupon from database, and using remove() shows an attribute error. views def remove_coupon(request, id): coupon = Coupon.objects.get(id=id) order = Order.objects.get(user=request.user, complete=False) order.coupon.remove() if coupon.used !=0: coupon.used =- 1 return redirect('store:checkout') model: class Coupon(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) code = models.CharField(max_length=20) amount = models.FloatField(max_length=4) valid_from = models.DateTimeField(null=True) valid_to = models.DateTimeField(null=True) max_value = models.IntegerField(validators=[MaxValueValidator(100)], verbose_name='Coupon Quantity', null=True) used = models.IntegerField(default=0) Thanks -
How to use multiple language snippets in one file in vs code?
I want to write a django-template in vs code, But I can't use both django-snippet and html-snippet at same time. If I set language to 'html' vs code won't support django-snippet, and also if I set the language to 'django html' vs code won't support html-snippet. What should I do?? -
Django rest fram work i want the Json to be displayed by clubbing the risk tag key with in rest api code
Below is the Json response from Django Rest api i want a customized output like risktag: common as one group and risktag: "Supply chain" as one group' at present when i hit the url http://127.0.0.1:8000/inidcator/?name=app&year=2019 below is the json response [ { "id": 1, "year": "2019-09-28", "name": "Mango", "risk": "Global markets for....", "risktag": "Common" }, { "id": 2, "year": "2019-09-28", "name": "Banana", "risk": "Global markets for the ....", "risktag": "Supply chain" }, { "id": 3, "year": "2019-09-28", "name": "Banana", "risk": "Global markets for the ....", "risktag": "Supply chain", "Common","Market" }, . . . . . so on... ] code: models.py: '''class indicator(models.Model): year= models.DateField(db_column='FiscalYearEnd') name= models.CharField() risk= models.CharField() risktag= models.CharField() serializers.py: class IndicatorSerializer(serializers.ModelSerializer): class Meta: model = indicator fields = ['year','name','risk', 'risktag'] views.py filters: from django_filters import rest_framework as filters class indicatorDataBaseListView1Filter(filters.FilterSet): year = filters.NumberFilter(lookup_expr='year') name= filters.CharFilter(lookup_expr= 'icontains') risk= filters.CharFilter(lookup_expr= 'icontains') risktag= filters.CharFilter(lookup_expr= 'icontains') view class indicatorView1(generics.ListAPIView): serializer_class = KeyperformanceindicatorSerializer queryset = Indicator.objects.all() #vice versa for get_queryset method filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter) filterset_class = indicatorDataBaseListView1Filter -
Why my request session lose data view to another view in auth azure AD?
I'm trying to integrate my django platform with azure ad authentication, so I followed the following document https://docs.microsoft.com/pt-br/graph/tutorials/python. In my project, I can only login to my platform user when the AD login is complete and working, so I'm trying to pass the user through the session to the callback view (which is called as soon as the AD login is complete) , at times it worked but most of the time the session comes completely empty def sign_in_ad(request, pk): request.session.flush() # Get the sign-in URL user = User.objects.filter(id=pk).first() company_azure = CompanyAzureAd.objects.filter(company=user.employee.firm).first() sign_in_url, state = get_sign_in_url(company_azure) # Save the expected state so we can validate in the callback request.session.update({'user_id': pk}) request.session.update({'auth_state': state}) request.session.modified = True # Redirect to the Azure sign-in page return HttpResponseRedirect(sign_in_url) def callback(request): user_id = request.session['user_id'] #Error key not exist user_platform = User.objects.filter(id=int(user_id)).first() company_azure = CompanyAzureAd.objects.filter(company=user_platform.employee.firm).first() # Get the state saved in session expected_state = '' # Make the token request url = request.build_absolute_uri(request.get_full_path()) if "http:" in url: url = "https:" + url[5:] token = get_token_from_code(url, expected_state, company_azure) # Get the user's profile user = get_user(token) # Save token and user store_token(request, token) store_user(request, user) login(request, user_platform, backend='django.contrib.auth.backends.ModelBackend') return HttpResponseRedirect(reverse('dashboard')) I do not understand why the session … -
Django not retaining session through views
I'm developing an application for Bitrix24 and I'm having a problem with sessions. @method_decorator(csrf_exempt, name='dispatch') class IndexView(View): r'''Index View.''' def get(self, request): r'''Manages Bitrix24 authentication redirect.''' return render(request, 'frontend/index.html') # POST working as GET because Bitrix24 does not GET the homepage. def post(self, request): r'''Renders the home page and stores Bitrix24 domain in session.''' request.session['bitrix24_domain'] = request.GET.get('DOMAIN') return render(request, 'frontend/index.html') As soon as the user goes to another view, the session is gone, completely. It also happens locally, if I set a key in session and try to retrieve it from another page, all data is lost too. I'm currently using default settings to Django and using rest-framework. Can anyone help? -
Django access/manipulate CreateView uploads
I have an CreateView as follows: class SpaceCreateView(CreateView): model = Space fields = ['title', 'space_image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I would like to pass the space_image to an 3rd party API and get back the response from there. How should I go about this since I have this set up inside an CreateView? -
pass queryset data to javascript as a variable template
I am trying to pass queryset data to the template as a javascript variable. I know I am doing something silly that is not working. views.py from django.http import HttpResponse from django.template import Context,Template,RequestContext from django.shortcuts import render_to_response, render from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.template.context_processors import csrf from io import TextIOWrapper from django.core.mail import send_mail from django.utils.safestring import mark_safe from django.db import connection import os import json import xlrd from django import forms from django.forms import ModelForm from django.db import models from .models import Deliveries # Create your views here. def historicals(request): context = {} historicals= Deliveries.objects.all()[1:100] print (historicals) context['historicals']=historicals context['abc']=123 return render(request,'customer.html',context) then the customer.html {% extends "base.html" %} {% load static %} <script type="text/javascript"> //{% autoescape off %}{{ historicals }}{% endautoescape %}; <--tried this too var actuals = {{ historicals | safe }}; var abc = {{ abc | safe }} ; </script> <script src="{% static 'js/custom.js' %}"></script> {% block content %} {% for i in actuals %} {{ i.Date }} {% endfor %} <h1> {{ abc }} </h1> {% endblock content %} Heres the confusion. When I print the historicals, the queryset shows in the console. It tells me … -
Django REST RelatedObjectDoesNotExist: User has no userprofile
I'm having problems with setting custom fields of the user model, in Django REST with rest-auth. When I go to http://localhost:8000/api/accounts/1/ (which is my path to the userviewset) to access user 1, custom_field is there but I can't edit it. When I edit it, I'll get the error above, namely "Django REST RelatedObjectDoesNotExist: User has no userprofile". I'm still relatively new to Django and it seems like there are a lot of ways to create custom user models, so I'm struggling to see where I went wrong. Any idea? user_profile/models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) customField = models.CharField(max_length=255, blank=True, null=True) user_profile/serializers.py class UserSerializer(UserDetailsSerializer): custom_field = serializers.CharField(source="userprofile.custom_field", allow_blank=True, required=False) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('custom_field') user_profile/views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer project/urls.py router = routers.DefaultRouter() router.register('accounts', UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), # This is used for user reset password path('', include('django.contrib.auth.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('account/', include('allauth.urls')), path('api/', include(router.urls)), -
how to calculate sum of @property function in django model?
I want to calculate the sum of total_amount property. Here is my models.py class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_item = models.ForeignKey('Product', models.DO_NOTHING, db_column='order_item', blank=True, null=True, related_name='ordered_item') order_status = models.CharField(max_length=100, blank=True, null=True) delivery_address = models.TextField(blank=True, null=True) customer = models.ForeignKey('User', models.DO_NOTHING, db_column='customer', blank=True, null=True) quantity = models.IntegerField() date_time = models.DateTimeField() @property def total_amount(self): rate = Product.objects.get(pk=self.order_item.product_id) total_amount = rate.price * self.quantity return total_amount @property def unit_rate(self): rate = Product.objects.get(pk=self.order_item.product_id) return rate.price -
Returning multiple times in Django views and proceed code execution
How can I return something and still proceed? In this case, Hello World should be printed in the console def filter_pending_documents(request): return pass #code should not stop here print('Hello World') return HttpResponse('') -
How can I call already made API to feed other API specific variable?
I made one API in Django which helps me to give the list of all Hospitals and I also assign some namespace for this url url(r'hospital_list$', HospitalList.as_view(), namespace="hospital-list"), class HospitalList(APIView): permission_classes = (AllowAny,) def get(self, request): return Response(HospitalSerializer(instance=Hospitals.objects.all(), many=True).data) Response of this API: [ { "id": 2, "name": "Apollo Bangalore Cradle Ltd." }, { "id": 3, "name": "Apollo Bangalore Cradle Ltd." }, { "id": 4, "name": "Apollo Hospitals" }, .. .. .. ] I am making another API where I want to feed data of one variable(hospital_list) which will come from the first API. path('profile/', AgentProfile.as_view()), class AgentProfile(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) def get(self, request): usr = request.user lead_objs = Leads.objects.filter(agent__id=usr.id) hospital_list = request.get()------> here I am getting confusion how I will use namespace return Response({"hospital_list":hospital_list, "total_lead": lead_objs.count()}) How can I call the namespace URL and save the response in a variable? -
Is there anyway to develop blockchain from django models [closed]
I would like to develop blockchain for my project. Currently the project is developed with django, with multiple apps, each with multiple models. -
Make modal image be that of the active image
I'm using django with wagtail to get an image carousel. Currrently I have code that will only display the first image that is in the carusel and not the one that is active. How do i alter my code or how do i add javascript to allow the active image to come onto the modal view. <div class="carousel-inner"> {% for item in page.products_images.all %} {% image item.image fill-10000x10000 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" data-aos="fade-down" alt="{{ img.alt }}" onclick="document.getElementById('modal01').style.display='block'"> <div class="imageCounter"> <img src="/media/original_images/camera.png" id="display"> {{ forloop.counter }} of {{ page.products_images.all.count }} </div> </div> <!-- The Modal --> <div id="modal01" class="w3-modal" onclick="this.style.display='none'"> <span class="w3-button w3-hover-red w3-xlarge w3-display-topright">&times;</span> <div class="w3-modal-content w3-animate-zoom"> <img src="{{ img.url }}" style="width:100%"> </div> </div> {% endfor %} </div> -
Launching django and uwsgi with nginx and docker
I'm trying to launch django and uwsgi with docker locally, but I've been unsuccessful so far. I have a slight variation of this setup working in production, so I don't want to mess with it too much, but I do want to have django running locally for some bug fixing. The setup is quite complex, at this point, so I'd rather avoid setting up manually and use runserver. This is my docker-compose: version: '3' services: website: build: context: website env_file: website/config/production.env volumes: - ./src/staticfiles:/usr/website/staticfiles expose: - "80" nginx: image: nginx:1.13 volumes: - ./nginx/config:/etc/nginx/ - ./src/staticfiles:/usr/website/staticfiles depends_on: - website ports: - "80:80" - "443:443" - "8000:8000" expose: - "80" - "443" - "8000" My dockerfile: FROM python:2.7 COPY src /usr/website COPY config/start.sh /usr/start.sh COPY config/django-uwsgi.ini /etc/uwsgi/django-uwsgi.ini WORKDIR /usr/website RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y build-essential RUN apt-get install -y python-dev RUN apt-get install -y nodejs RUN pip install uwsgi RUN curl https://www.npmjs.com/install.sh | sh RUN npm install RUN npm install node-sass RUN npm audit fix RUN npm update caniuse-lite browserslist RUN ./node_modules/.bin/webpack --config webpack.config.js RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN pip install mysqlclient RUN npm install webpack webpack-cli --save-dev RUN adduser … -
Add a date or a number at the end of a slug
i'm trying to add a number or publish date at the end of a slug, off the page mode, if the slug already exist. I found a possible solution with RoutablePageMixin but not quite sure how to approach it as it changes the URL not the slug itself. Here is what i got so far but it seams that is not working... class BlogPage(HeadlessPreviewMixin, Page): #... def full_clean(self, *args, **kwargs): # first call the built-in cleanups (including default slug generation) super(BlogPage, self).full_clean(*args, **kwargs) # now make your additional modifications if not self.slug.startswith('awesome'): self.slug = "awesome-%s" % self.slug -
How to deploy djanjo-angular-postgresql web app using google kubernates engine?
I have a djanjo, angular, postgresql web app that I want to deploy. I never deployed a web app before, so, this is my fist time. I decided to use google cloud platform. They offered app engine which seems to be easy to use and deploy but it's very expensive, though. So, I decided to go for kubernates engine, since it's much cheaper. I went through the documentation for kubernates but I don't really seem to understand anything at all. Can someone guide me through how to deploy the previously mentioned app ? -
Docker with pipenv and django shows an unusual bug
FROM python:3.8-slim-buster # Setting environment variables ENV PIPENV_IGNORE_VIRTUALENVS=1 \ PIPENV_VENV_IN_PROJECT=1 \ PYTHONBUFFERED=1 # Installing dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY Pipfile* ./ RUN pipenv sync # Copying all the files files over to the workdir COPY . ./ # Running the container when asked with pipenv to load .env files ENTRYPOINT ["pipenv"] CMD ["run", "start"] Above is my dockerfile, when I run docker built -t djhml:latest ., it builds the image nicely without any errors, but when I run docker run djhml it does not bring up the website unless if I run it through the command docker run --network=host djhml and I have seen people not using this. How can I just run docker run djhml and it hosts the website on my local machine? Also, it does not print certain things when the server boots up. For example, if I make a request to the site url, it prints it out but it does not print the first part when I run the container, it prints it when I press ^C This is what I meant: You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for … -
End block error for translate with seemingly perfect syntax
I'm new to django & I'm trying to write my own django template and when I execute the following code <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> &rsaquo; <a href="{% url opts|admin_urlname:'changelist' %}">{{ module_name }}</a> &rsaquo; <a href="{% url opts|admin_urlname:'change' object.pk|admin_urlquote %}">{{ object|truncatewords:"18" }}</a> &rsaquo; {% translate 'History' %} </div> I get the error 'translate', expected 'endblock'. Did you forget to register or load this tag? The tags as you can see are properly closed and I'm absolutely clueless as to why this is happening. This is admin history template (admin/object_history.html") & this exact code works absolutely fine there for all the history forms. Any help or sense of direction is appreciated. -
How to add more images in multiple input tag html?
Suppose I have a input tag like this <input type="file" name="Posts" id="FilesForUpload" multiple> When I Click on this it takes a file (or multiple files) for Example i chose - A.jepg, B.jepg Now after i selected these two images now I want to add a third Image say C.jpg. So when I click on the input tag again then it replaces A.jpg and B.jpg. I know its obvious that it will replace those two, But is there any way so that it not replaces previous files. I am using Django Framework to build my Project and I am stuck on this. -
How to push a json data from angular to django views?
var myApp = angular.module('myApp',[]); ... other js functions implemented for push notification ... function postSubscribeObj(statusType, subscription) { console.log("inside post subscribe"); var subscription = subscription.toJSON(); // API call to store the endpoint in the database myApp.controller('mainController', ['$scope','$http', function($http) { $http.post('/api/fetch_browser_subscription_url', subscription, function(response){ console.log("Awaiting response from server") if(response === 'success'){ console.log("API call successful"); } else { console.log('ERROR occurred while making API call.'); } }); }]); } I am trying to use the above code to push the JSON data (browser subscription message I received to implement the push notification) to a Django view. Is it the right way to use it? or should it be used outside a function? When I tried using $.post method of jQuery it shows an error that the url not found but using this the error is gone but not sure that whether it has actually found that error or it is not entering this controller itself. PS: I am a beginner in web development -
want to create Django model for below data: How can I create array for activity_periods and members?
{ "ok": true, "members": [{ "id": "W012A3CDE", "real_name": "Egon Spengler", "tz": "America/Los_Angeles", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] }, { "id": "W07QCRPA4", "real_name": "Glinda Southgood", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] This is the model I have come up with. What should the code for activity_periods be? from django.db import models from timezone_field import TimeZoneField class Member(models.Model): id = models.CharField() real_name = models.CherField() tz = TimeZoneField(default='Europe/London') activity_period = Period() class Period(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() -
Django cannot load static files once in production
I currently have a Django project and the static files will not load into the templates. I have spent over a week on this trying every solution online with no luck. I use {% load static %} at the top of the file and {% static 'css/style.css' %} It still will not load the static files. Any help would be much appreciated. Thank you """ Django settings for example project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ 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 = 'somekey' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [''] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.static', 'django.contrib.humanize', 'example', 'example.templatetags', 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' 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', ] #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'example', # } #} …