Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF Token is not getting set
So i am using VueJS and Django. Axios to make a get request. When i try to retrieve the CSRF token and log it, it shows me it is null. here is my serializer: class VehicleSerializer(serializers.ModelSerializer): seller = serializers.SerializerMethodField() class Meta: model = Vehicle fields = ('vehicle_id', 'color', 'model', 'year', 'category', 'manufacturer', 'seller') def get_seller(self, instance): return instance.seller.customer.username My Viewset: class VehicleListCreateAPIView(ListCreateAPIView): serializer_class = VehicleSerializer permission_classes = [IsAuthenticated] queryset = Vehicle.objects.all() def perform_create(self, serializer): request_user = self.request.user try: seller = Seller.objects.get(customer = request_user) except Seller.DoesNotExist: seller = Seller.objects.create(customer = request_user) serializer.save(seller = seller) My urlpattern: path('vehicles/', VehicleListCreateAPIView.as_view()), The code from django documentation to retrieve a token: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); export { csrftoken }; -
Django admin page and CSS
I'm very new to django. I just did the very basic step for creating a project which has one application. I started the server using python manage.py runserver which ended up giving me my home page. but when I opened the admin page it was not with proper CSS as it is supposed to be. I went through some solutions like adding the following code so that my static files are added correctly. STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' But this doesn't reflect anything after running python manage.py collectstatic. Do I need something else to done further? This is the settings.py file 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 = '(9szxe#x0q67)^wc6us01*i$=1)!&f7)530%73=pvzzhwp23gp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { … -
attempt to write a readonly database - Django app deployed on App Engine (SQLite3 DB)
I have hosted Django app using App Engine standard environment. When I try to login, it gives me 'attempt to write a readonly database' error . I have added URL to ALLOWED HOSTS and added in admin credentials in DATABASE in settings.py. Everything else works as intended. app.yaml # [START django_app] runtime: python37 service: hellotest1 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # [END django_app] settings.py - DATABASES and ALLOWED_HOSTS ALLOWED_HOSTS = ['url'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'admin', 'PASSWORD': 'admin', } } -
Django IIS Active Directory Single Sign On (SSO)
I have application written in Django, hosted with IIS on my intranet with Active Directory. Following this stackoverflow topic https://stackoverflow.com/a/26987622/4992056 I managed to create basic domain authentication. Unfortunately this solution reqiures login with domain account credentials everytime I rerun browser what is not ideal user experience and brings security issues (browser prompts user to save their domain account credentials). I would like to have true single sign-on feature that means: when user is signing in with his domain account, he/she should also be signed in to the web app without prompting for password. Thanks in advice for your answers. Best regards, Wojtek -
IntegrityError in database stored vlaues in django?
''' My problem is database values can't stored properly In below I uploded views functions file,model file as an images. so in model there are three fields but database stored only image stored and other vlaues strored by default get null values so can you help to solving my problem.. ''' userproblem.html <form method="POST" action="/uploadoc/" enctype="multipart/form-data" data-toggle="validator"> {% csrf_token %} <div id="progressbarwizard"> <ul class="nav nav-pills bg-light nav-justified form-wizard-header mb-3"> <li class="nav-item"> <a href="#account-2" data-toggle="tab" class="nav-link rounded-0 pt-2 pb-2"> <i class="mdi mdi-account-circle mr-1"></i> <span class="d-none d-sm-inline">Query Form</span> </a> </li> </ul> <div class="tab-content b-0 mb-0"> <div class="tab-pane" id="account-2"> <div class="row"> <div class="col-md-5"> <label class="col-md-12 col-form-label">Query Types: <span class="text-danger">*</span></label> <div class="col-md-8"> <input type="text" class="form-control" data-validate="true" name="queryn" placeholder="Enter Query Types"> </div> </div> <div class="col-md-5"> <label class="col-md-12 col-form-label">Description of Query: <span class="text-danger">*</span></label> <div class="col-md-12"> <textarea type="text" class="form-control" data-validate="true" name="querydec" placeholder="Description of Query"></textarea> </div> </div> </div><!-- /.First row end --><br> <div class="row"> <div class="col-md-5"> <label for="Emailadrress" class="col-md-12 col-form-label">Upload Your File: <span class="text-danger"></span></label> <div class="col-md-12"> <div class="input-group-append"> <input type="file" id="img" name="img" accept="image/*"> </div> </div> </div> <div class="col-md-6"> <label for="Emailadrress" class="col-md-12 col-form-label">Solutions: <span class="text-danger"></span></label> <div class="col-md-12"> <div class="input-group-append"> <textarea type="text" name="querysol" placeholder="Solutions of Query"></textarea> </div> </div> </div> </div> <!-- /.second row end --> </div><br> <div class="row"> <div class="col-12"> … -
How to run a function witth (request) every hour?
i have function: def coins_costs_load(request): response = requests.get( 'https://explorer-api.minter.network/api/v1/coins').json()['data'] for coin in response: coin_crr = coin['crr'] coin_id = coin['symbol'] obj = CoinCosts.objects.create( crr=coin_crr, coin_id_id=coin_id) obj.save() It works great and everything is fine. But how to automatically run a function every hour? I tried all the methods, and the shedule plugin, and the built-in tools. They do not work with the request argument. Gives an error message. And if you remove the argument, also an error... Please help! Thanks! -
Django ModelForm save to another database
I have a set up with multiple databases: let's call them db1, db2 and db3. db1 is default. I now have a ModelForm that is meant to save an object Customer to db2. class CustomerCreateForm(ModelForm): class Meta: model = Customer fields = ["name", "type"] My view: if "create" in request.POST: f = CustomerCreateForm(data=request.POST) customer = f.save(commit=False) # Error -> no table 'customer' on database 'db1' customer.date_joined = datetime.now() customer.save(using='db2') It appears that the save() method does not have a using argument. How can I save an instance of Customer to db2? -
saving to django models using ajax
I am trying to save a users data into the database. Iam trying to get one input from the user that is the answer, then I want to get the question that has been assigned to the user that is the First_question variable. I tried to track if the selected_answer and assigned_question has been parsed to the view and it did. but then I get an error: NOT NULL constraint failed: study_answer.question_id [246, None, None, 30.0, '2020-04-09 13:53:36.008824', '2020-04-09 13:53:36.008849'] self sql ('INSERT INTO "study_answer" ("participant_id", "question_id", "answer", ' '"completion_time", "created_at", "updated_at") VALUES (%s, %s, %s, %s, %s, ' '%s)') from my understanding it seems that both question_id and answer_id are not being able to be parsed. although when I printed them I got the answer as in text and the question id. views.py participant = get_object_or_404(Participant, user=request.user) selected_choice = request.POST.get('selected_choice') assigned_question = request.POST.get('assigned_question') completion_time = 30 answer = Answer(participant=participant, question=assigned_question, answer=selected_choice, completion_time=completion_time) answer.save() template.html <p name="question" id="{{First_question.id}}"> {{First_question}} </p> {% for i in all_choices %} <input type="radio" id="{{ i.id }}" name="choice" value="{{ i.choice_text }}"> <label for="{{ i.id }}">{{ i.choice_text }}</label> {% endfor %} <button type="button" id="Submitbutton" class="btn btn-primary" onclick=Nextquestion() >Next</button> </div> <script> function Nextquestion(){ selected_choice = $("input[type='radio'][name='choice']:checked").val(); assigned_question = … -
how to Convert ruby on rails code to Django?
i want convent this code from ruby on rails to django just example class HomeController < ApplicationController include BusinessPlans include CreditRepairPlan include FinancePlan skip_before_action :verify_authenticity_token, only: [:get_plan,:get_credit_repair_plan, :get_finance_plan] before_action :authenticate_user! def index end def upgrade end -
Matching database columns in the filtering in Django
I'd like to match database columns in the query. How is this possible? For example select * from docs where mlal_id_no=8 AND column1= column2 qs = docs.objects.filter(mlal_id_no=8,column1=column2) -
Can't use django 2.2 with django-oscar-wagtail for wagtail cms
I am using: django 2.2 django-oscar 2.0.4 I can't use wagtail<2.6 since I am using django 2.2( django2.2 support is with wagtail 2.6 ). And django-oscar-wagtail require wagtail <2.4. Can you give me some ideas to use wagtail with django-oscar? -
Django get user like from friend list
I'm a Django beginner, I have a friend field in Profile Model which list all my friend users. And also these friends liked my post. How do I get the names of only those users in my friends list to display in the post they liked. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) friends = models.ManyToManyField('Profile',related_name='my_friends') class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL) likes = models.ManyToManyField(User, related_name='image_likes') def home(request): #...... -
custom context processor not working for displaying cart items
This is my custom context code for displaying cart def cart(request): return {'cart': Cart(request)} and added this line to the context_processors in settings 'appname.context_processor.cart', but not getting out put on base.html templates template code {% with total_items=cart|length %} {% if cart|length > 0 %} Your cart: <a href="{% url 'cart_detail' %}"> {{ total_items }} item{{ total_items|pluralize }}, ${{ cart.get_total_price }} </a> {% else %} Your cart is empty. {% endif %} {% endwith %} -
Django channels page stuck on loading
I created a simple Django Channels consumer that connects to a Redis channel and receives some data from this channel, i want to send this data to the frontend. The consumer is able to connect to the consumer and receives the data; the problem is that if i try to load the page when the consumer is running, the page will be stuck on loading. I'm sure this happens because the connection to the Redis channel is a blocking operation, or it could be a problem with threads. I'm new to this concepts, so i decided to make a question for it. Here is my consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): self.send({ 'type': 'websocket.accept' }) self.receive(event) def receive(self, event): channel = 'TEST' params = urllib.parse.parse_qs(self.scope.get('query_string', b'').decode('utf-8')) pubsub = connection.pubsub(ignore_subscribe_messages=True) pubsub.subscribe(channel) for message in pubsub.listen(): # self.send({ # 'type': 'websocket.send', # 'text': message['data'], # }) print(message['data']) async def websocket_disconnect(self, event): redis_url = 'redis://localhost:6379/0' connection = redis.StrictRedis.from_url(redis_url, decode_responses=True) channel = 'TEST' pubsub = connection.pubsub(ignore_subscribe_messages=True) pubsub.unsubscribe(channel) print('DISCONNECTED!') So what happens is that i can see the data being printed to my console, but if i try to leave that page and reach a different part of my site, the page will get … -
Django is searching the URL in the wrong application
My application is currently using a external app supplied URLs . I decided to override some of their views , this however resulted in the issue whereby django is searching for the URL in the wrong directory. Heres some of my code to explain the problem : url.py(not the root config , however its in my main app) urlpatterns = [ path('pipeline/<process_pk>/documents/<task_pk>/assign/', #<---- this is the URL and view that i overrode OverrideTaskView.as_view(), {'flow_class': Pipeline, 'flow_task': Pipeline.documents}, name="pipeline:{}__assign".format(Pipeline.documents.name)), path('pipeline/', include((pipeline_urls,'pipeline'))), #<--- this is the app-supplied URLs views.py class OverrideTaskView(CoreAssignTaskView,FormView): #<--- im inheritting the view from the third party app form_class=AssignForm action_name = 'assign' def post(self, request, *args, **kwargs): if '_assign' or '_continue' in request.POST: self.activation.assign(self.request.user) return HttpResponseRedirect(self.get_success_url()) #<---- this is where it calls the faulty code else: return self.get(request, *args, **kwargs) def get_success_url(self): #<--- in this get success url the self.request.resolver is returning the wrong value """Continue on task or redirect back to task list.""" url = self.activation.flow_task.get_task_url( self.activation.task, url_type='guess', user=self.request.user, namespace=self.request.resolver_match.namespace + ':' + 'pipeline') back = self.request.GET.get('back', None) if back and not is_safe_url(url=back, allowed_hosts={self.request.get_host()}): back = '/' if '_continue' in self.request.POST and back: url = "{}?back={}".format(url, urlquote(back)) elif back: url = back return url The piece of code … -
Помогите пожалуйста , не могу понять Django rest_framework
После удаления объекта User , выводится только id , как вывести все филды данного обяекта id = serializers.PrimaryKeyRelatedField(queryset=CommunicationObject.objects.all(), many=True) def delete_many(self): for i in self.validated_data['id']: i.delete() -
Django view as API with Get method save twice records from Firefox
I made a simple view for searching one product in my ecommerce website.. The view (an API) wait a GET parameter (as http://example.com/search/12345) after I would like to save the searched parameter (with a create queryset) in a specific model for obtain search history. But if I call the view/api from last Firefox version, I get two records in database, from Edge only one. Deepening the topic the problem is the idempotency expected from HTTP RFC on Get method. Some browsers can do more than one request... I need to preserve GET method for search api but I need saving the searched string. What I can use GET parameter for searching and SAVE it in database only one? without CSRF/Cookie/User-Agent? P.S. I don't post code because it is needless. -
Password reset confirm not work in Rest-Auth
I use rest-auth for backend with django rest framework. In urls: path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls'))-at when I access to http://localhost:8000/rest-auth/password/reset/ I get an email field. After providing email, I get NoReverseMatch at /rest-auth/password/reset/. Mainly, Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. How can I fix this?? I tried in urls: from rest_auth.views import PasswordResetConfirmView url(r'^rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm') Now I get an email and when I go to the link I get four field (New password1, New password2, Uid, Token) but (Uid and Token field are empty). How can I get this 2 field (Uid and Token) filled with url's Uid and Token?? -
Django Not letting save Time in Hour:Minute formate
I am trying to save time in this formate '13:21' . but django not letting me to do so and giving this exception ["'13 : 53' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."] my field is duration = models.TimeField(null=True , blank=True) my setting.py is TIME_INPUT_FORMATS = ('%H:%M',) -
best way to integrate Vue.js to Django application in production
i have a Django application in production hosted using digital ocean, the project is huge and has been live for 4 months now, i need to a add a few frond end features to one of the site pages using Vue.js but i am still wondering on which way is better to integrate vue.js and vuetify, which is the best method, using the cdn link or a webpack installation? -
How do i upload a image from user side to media folder from views and models in django? [closed]
my views.py file from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from mcatagory.models import sub_catagory, product from PIL import Image # Create your views here. def addproduct(request): scat = sub_catagory.objects.all() # scat = sub_catagory.objects.raw( # 'SELECT id FROM mcatagory_sub_catagory WHERE catagory_id_id=%s',[sub_catagory]) added = False if request.method == 'POST': p_name = request.POST.get("p_name") p_price = request.POST.get("p_price") p_desc = request.POST.get("p_desc") img = request.POST.get("image") s_cat = request.POST.get("s_cat_id") status = 0 data = product(p_name=p_name,p_price=p_price, p_desc=p_desc, image=img, sub_catagory_id=s_cat, status=status) data.save() added = True print("Thai Gayu !!!") return render(request, 'customer/rentproduct.html', {'sub_catagory': scat, 'added': added}) else: return render(request, 'customer/rentproduct.html', {'sub_catagory': scat}) -
Django admin Form with dynamic field addition
I study in Django and I have a task. There is data with a list of periods. These periods can be either five or twenty. And I need to create a form in to add this data. Periods will be added using the two fields start_period and end_period. The task is that when adding data, the user in the admin panel could add periods as much as necessary, when changing data accordingly, too. I see this as a form with the ability to dynamically add the required number of fields start_period and end_period, then saving data with periods in either json or in a separate table, the problem is that I don’t know how to implement dynamic adding of a field. Unfortunately, I could not find an adequate solution to this problem. I found something close to this through Formsets, but this is not what we are looking for. Who can tell how to implement this? python 3.7, Django 3.0.4 -
Database connection Error while hosting site on heroku
So I was trying to host my first Django app on heroku. Took help form some Youtube channels. I used postgresql as my database. Now when I tried hosting my app on heroku the following error is showing up: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?``` **This is the error showing** -
How to pass a dictionary in DestroyAPI SUccess MEssage
class ExampleDestroyView(DestroyAPIView): serializer_class = PetSerializer def perform_destroy(self, instance): self.data = {} self.data['status'] = True /// Some Code /// self.data['msg'] = "It removed" return self.data def get_queryset(self, *args, **kwargs): self.data Here is my Sample Class ..... In this I need to Delete an objet.... It's deleting But I am unable to pass the following Dict As an OutPut How can I pass the status and a message in a dictionary -
Updating value of a model
I am newbie of Django. And I don't understand how Django model works. First, I am trying to create a model of user score in users/models.py, so each user has a score variable to store their own score, and score can be updated. Then, in my morse_logs/game1.html, i will ask a question as simple as 1+1 to user, then i retrieve the answer and compare it in morse_logs/views.py to see if it is correct, if it is correct, I will add 5 score to that user; if incorrect, no score is added. So now I am struggling to define a correct model for setting a field for user to have their own score, and I wonder how can I update and retrieve the score of the user in view.py. users/models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) description = models.CharField(max_length=100, default='') #score = models.CharField(User, max_length=10, default=0) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class UserScore(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.CharField(max_length=1000, default=0) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Returns a string representation of the model""" return …