Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why accessing to cache from django code and shell are different
I`m trying to clear my cache in save function of model A. But when i try to delete it cant find any data cache.keys('*') returns []. So cache can`t be cleared. But when i do same operations in manage.py shell everyting works. So the question is, what is the difference between using cache in shell and in django codes -
Display number of wrong attempts of user
In my django app i want to show that the user has tried logging in with wrong password three time. I am using django-brutebuster I can see a table in my postgres on migrate named BruteBuster_failedattempt This captures: 1.id 2.username 3.IP 4.failures 5.timestamp **Setting.py:** Installed Apps: BruteBuster Middleware BruteBuster.middleware.RequestMiddleware', Block threshhold BB_MAX_FAILURES = 3 BB_BLOCK_INTERVAL = 3 I want to display the count of failed attempts on my django template. -
How could I send post on selected date without pressing any button
Hey I would like to send a date from selected date automatically, for instance when it is july 2019 and I will select August it will send post to the form and refresh page. I am using DatePickerInput(format="%m-%Y") so django create form in template for me. Do you have any ideas how could I do it ? I didn't find any solution. -
Upload any DateTime from CSV in Django
I am uploading CSVs in a django project but it shows error from laptop to laptop. Models.py time = models.DateTimeField(max_length=100, blank=True, default=datetime.date.today) views.py csv_file = request.FILES['file'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) uploaded_by = request.user for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = ItemBatch.objects.update_or_create(name=column[0], pid=column[1], quantity=column[2],date=column[8]) The problem is that it takes only this format : YYYY-MM-DD HH:MM I updated settings.py with this: DATE_INPUT_FORMATS = ['%d-%m-%Y','%Y-%m-%d','%d/%m/%Y','%m/%d/%Y' ] What changes do I need to make such that it accepts every datetime format? -
PATCH Method not allowed
I tried to add a Patch method to my API in Django and I'm always ending with a "Method not allowed". I added mixins.UpdateModelMixin as mention in the Django Rest Framework documentation, however, it still returns the same error. I look and don't find where I need to put authorization for Patch to be allowed. this is the code related to that view and path declaration in urls.py and views.py. urls.py ''' schema_view = get_schema_view( openapi.Info( title="WAF Management Portal API", default_version="v1", description="REST api for interaction between Frontend and Backend.", contact=openapi.Contact(email="soc-dev-automation@bell.ca"), ), public=True, permission_classes=(permissions.AllowAny,), ) path( 'action/dothis/', ActionApiView.as_view(), name="action_api_view" ), ''' views.py ''' class ActionApiView(mixins.UpdateModelMixin, ActionAPIView): """ post: add one or more settings to selected policy patch: modify or more settings to selected policy """ def get_queryset(self): return Policy.objects.allowed_to_user(self.request.user) def get_serializer(self, *args, **kwargs): return SettingsSerializer(*args, **kwargs) @swagger_auto_schema() def post(self, request): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(data=request.data) if serializer.is_valid(): selected_policies = serializer.get_selected_policies(queryset) .....do some data manipulation (included action_id variable)... response = { ....prepare response } return redirect("another_view", action_id=action_id) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @swagger_auto_schema() def patch(self, request): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(data=request.data) if serializer.is_valid(): selected_policies = serializer.get_selected_policies(queryset) .....do some data manipulation (included action_id variable)... response = { ....prepare response } return redirect("another_view", action_id=action_id) … -
How to pass arguments to a Python script from JavaScript
I'm need to run python script(s) based on user decisions in frontend. These scripts has to use these user decisions to "complete" the script before it runs. When the script has run it should return the ouput back to the frontend. I'm very new to JavaScript and only know Python basics. The script that is going to run are already created. I only need to edit some of the code so that it doesn't need to be configured from the code it self, but from a website instead. The scripts needs three arguments that should be provided from the frontend: a personal token a project name an array of test plan id's After the user has provided these three inputs, user can push a button which will be inserted into a python script in the correct place and the script should execute. When the output is ready, the script should return the ouput back to the frondend. Some of my HTML: <h4>Token</h4> <p>Insert token:</p> <form id="token_input_form"> <input type="text" name="token_input" size="52" required /> </form> Some of the script: personal_access_token = '<the token>' project = '<project name>' test_plans = [<one or more id(s) to test plan(s)>] -
DRF annotate nested serializer
I have a nested serializer initialized with many=True and would like to add a number of annotated fields to the output using SerializerMethodField(). How can I annotate the OrderLineSerializer queryset? class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ( 'id' 'lines' ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['lines'] = OrderLineSerializer( context=self.context, many=True, write_only=True, ) class OrderAPIViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer -
django: how to allow post request only from forms?
I have a simple form: {% block content %} <p> Upload invoices </p> <form method="post" action="{% url 'upload_thing ' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="invoice_thing"> <button type="submit">Upload</button> </form> I have a view @require_POST @transaction.atomic def upload_thing(request): .... How do I make sure that the no one can hit the post endpoint vs curl or postman? I want the end point to be accessible only by hitting the form button. How do I accomplish this? -
Model of a nested document in pymodm or mongoengine to work in Django
I have a specific kind of JSON which I need to code into a model for my Django problem. Problem is I have nested document in it or should I say object of objects and I don't know how to design the model in Pymodm or Mongoengine. Here is the JSON schema on which I am working. { "something": "something", "safasf": 5, "key": { "value1": ["dsd", "dd"], "value2": { "blah1": "blahvalue1", "blah2": "blahvalue2" } } } I have already looked into the documentation and API References of both these ODMs. I could not find anything useful. At best they have fields.EmbeddedDocumentListField which stores list of documents/objects. -
Is there a way to call a function when user enter the website/link?
So basically i'm working on a project that will allow users to download vCard when they enter the link. For example "https://www.google.com", when users open the link, a vCard will be downloaded. I already have the download method written in views.py. and i want it to be executed when users open the link. I tried to search on the internet, but I got no result. This is the method to open the link try: cardDetails = uservcfDetails.objects.all().filter(uuid=data) cardID = uservcfDetails.objects.get(uuid=data) userID = cardID.user_id_id checkBalance = userExchangeBalance.objects.get(user_id_id=userID) context = { 'details': cardDetails, } return render(request, 'webapp/VCFCard/shareContact.html', context) except Exception as error: return render(request, 'webapp/VCFCard/CardNotFound.html') I also have another method to download the file ... return My question is how to call the download method automatically? -
Django, Modelform not rendering
I created a basic Modelform in django but my form does not render. tasks.html <table class="..."> <tr> <th>Function</th> </tr> <tr> <td> <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Execute</button> </form> </td> </tr> </table> models.py class Tasks(models.Model): #Task module function_name = models.CharField(max_length=30, default='') script_location = models.CharField(max_length=300, default='') forms.py from django.forms import ModelForm from .models import Tasks class Tasks(ModelForm): class Meta: model = Tasks fields = ['function_name','script_location'] views.py class Tasks(View): def get(self, request): form = Tasks() return render(request, '.../tasks.html', {'form': form}) I except to see two text fields, but i only see the 'Execute' button -
Django ORM's contains vs SQL's LIKE
I'm working on Django 2.1.5 and MySQL version is 14.14. I'm trying to query using a wildcard search as below for single character replacement. 98765?321 - returns all the numbers in the database column with a single replacement for ? - at most 10 numbers will be returned. 98?65?321 - returns all the numbers with single replacement for both ?s - at most 100 numbers will be returned. 98?65?32? - returns all the numbers with single replacement for first ? and all the numbers ending with that for second ?- any number of numbers could be returned. 98?65?3?1 - returns all the numbers with single replacement for all three ?s - at most 1000 numbers will be returned. 987? should return all the numbers starting with 987 - could return any number of numbers. I was able to do this with Model.objects.filter(column_regex=regex). But as the DB contains 50 millions of rows, this is impacting performance. How do I do the same thing with column__contains or column__icontains etc. -
"BLOB/TEXT column used in key specification without a key length" error in Django
I have this model in my Django project: class Institution(models.Model): name = models.CharField(unique=True, max_length=100, blank=True) description = models.TextField(max_length=500, null=True, blank=True) def __str__(self): return self.name I run my project completely when I use SQLite ,but when I change my database engine to Mysql I got this error: MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'name' used in key specification without a key length") What I must to do? -
how to save data without html form into mysql database in django
I want to add data to mysql database in django without using any kind of form in post method. I want to hard code the data and store it in the database. I dont want to store it from phpmyadmin and want to code it I have alrady made my models.py file. this has created the table "offesnses" in the database. models.py from django.db import models from django.core.validators import int_list_validator # Create your models here. class offenses(models.Model): oid = models.IntegerField(primary_key=True) description = models.CharField(null=False, max_length=20) assigned_to = models.CharField(null=True, max_length=20) categories = models.TextField(null=True) category_count = models.IntegerField(null=True) policy_category_count = models.IntegerField(null=True) security_category_count = models.IntegerField(null=True) close_time = models.TimeField(null=True) closing_user = models.IntegerField(null=True) closing_reason_id = models.IntegerField(null=True) credibility = models.IntegerField(null=True) relevance = models.IntegerField(null=True) severity = models.IntegerField(null=True) magnitude = models.IntegerField(null=True) destination_networks = models.TextField(null=True) source_network = models.CharField(null=True, max_length=20) device_count = models.IntegerField(null=True) event_count = models.IntegerField(null=True) flow_count = models.IntegerField(null=True) inactive = models.BooleanField(null=True) last_updated_time = models.DateTimeField(null=True) local_destination_count = models.IntegerField(null=True) offense_source = models.IntegerField(null=True) offense_type = models.IntegerField(null=True) protected = models.BooleanField(null=True) follow_up = models.BooleanField(null=True) remote_destination_count = models.IntegerField(null=True) source_count = models.IntegerField(null=True) start_time = models.TimeField(null=True) status = models.CharField(null=True, max_length=20) username_count = models.IntegerField(null=True) source_address_ids = models.TextField(null=True) local_destination_address_ids = models.TextField(null=True) domain_id = models.IntegerField(null=True) class Meta: db_table = "offenses" I want to save response_body data into database.for e.g. id,description etc views.py … -
Add django .env settings to uwsgi server
I working with .env file for hide some settings values at my django projects. A part of settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('CVB_DB_NAME', ''), 'USER': os.environ.get('CVB_DB_USER', ''), 'PASSWORD': os.environ.get('CVB_DB_PASS', ''), 'HOST': os.environ.get('CVB_DB_HOST', ''), 'PORT': os.environ.get('CVB_DB_PORT', ''), } } .env CVB_DB_NAME=db CVB_DB_HOST=localhost CVB_DB_USER=owner CVB_DB_PASS=kwaD And I haven't any problem at locall mashine, but then push new setting to production server I got ImproperlyConfigured at / settings.DATABASES is improperly configured. Please supply the NAME value Im using Django2.2, uwsgi, nginx, python 3.7, pipenv Could anybody help me to solve this? -
Accessing the Value of a Django Queryset using a secondary list of column names
Im trying to avoid a hardcoding situation in my code if have a Customer queryset for example the columns are (name,phone,email….) so if I do customer = Customer.objects.get(name = 'bbc') # to get the values of each field I need to do customer.name customer.phone customer.email …… to avoid having to do this as I need to compare each field in an If statement to make a not of any changes from a form I made a list that contains the column name Example of the if statement if customer.name == some variable or customer.email == some vairiable ….. I made a list that contains the column name to avoid this issue list = ['name', 'phone' , 'email'] when I do this for loop if customer.list[i] == some variable I get an error customer doesn't contain attribute list how can I get around this issue thanks in advance -
SQLALCHEMY table joining related quesion
I have 3 tables. 2 needs to be joined all the time but the 3rd one only if some condition/flag is true. With the same, need to add group_by and order_by as well if true. Need help how to achieve it. In the sample code, it can be seen that I have written 2 separate queries, but I am looking for some way in which the same query can have all conditions checked. # When the flag is False childList = session.query( table1.-------).\ join(table2, and_(table1.id == table2.id)).\ group_by(table2.name)).\ order_by( table1.c.order).all() # When the flag is true childList = session.query( table1.-------).\ join(table2, and_(table1.id == table2.id)).\ join(table3, and_(table3.id == table2.id)).\ group_by(table2.name,table3.name)).\ order_by(table3.c.order).all() -
Django Queryset not returning the required column
I'm trying to get the values of a particular column and add it to my dropdown list in a forms.Form class. But the values in the dropdown isnt what its mean to be. Its returning the 'dept_name' of the table instead of the 'lead' column. I've tried series of stuff but it either not working or it throws the related_name error. Department.models.py dept_name = models.CharField(max_length = 200, unique = True) lead = models.CharField(max_length = 200) parent_dept = models.CharField(max_length = 200) added_by = models.CharField(max_length = 200, blank=True, null=True) number = models.IntegerField(blank=True, null=True) def __str__(self): return self.dept_name employee.models.py first_name = models.CharField(max_length = 200) last_name = models.CharField(max_length = 200) name = models.CharField(max_length = 200 , blank=True, null=True) employee_id = models.IntegerField(null=False, blank=False, unique=True) email = models.CharField(max_length = 200) address = models.CharField(max_length = 200) employment_type = models.CharField(max_length = 200) employment_status = models.CharField(max_length = 200) role = models.CharField(max_length = 200) marital_status = models.CharField(max_length = 200) gender = models.CharField(max_length = 200) join_date = models.DateField() end_date = models.DateField(blank=True, null=True) location = models.CharField(max_length = 200) hod = models.ForeignKey(Department, related_name="hod", on_delete = models.DO_NOTHING) phone_number = models.CharField(max_length = 200, null=False, blank=False) date_added = models.DateTimeField(default = datetime.now, blank=True) date_of_birth = models.DateField() department = models.ForeignKey(Department, related_name="departments", on_delete = models.DO_NOTHING) credentials = models.ImageField(upload_to = … -
How to convert base64 images string in python and save it local directory
How to convert a base64 string that contains an image into image format and save it local system This is my string data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QCSRXhpZgAASUkqAAgAAAAEAA4BAgAbAAAAPgAAADEBAgAHAAAAWQAAABICAwACAAAAAQABAGmHBAABAAAAYAAAAAAAAABwcm9mZXNzaW9uYWwgd29tYW4gcGljdHVyZQBHb29nbGUAAwAAkAcABAAAADAyMjACoAQAAQAAAIQDAAADoAQAAQAAAGQCAAAAAAAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8IAEQgCZAOEAwERAAIRAQMRAf/EAB0AAAEFAQEBAQAAAAAAAAAAAAEAAgMEBQYHCAn/x I need to convert this string in jpg/png/jpeg format and store as an image in a local system I already tried this question but not getting How to convert base64 string to image? -
Axios delete will result in a 401 unauthorized
I get a 401 error, when trying to delete an event via Axios. I have made all users within the app superusers and admins with permissions to delete events. I have made all users within the app superusers and admins with permissions to delete events. However, after rectifying this in the backend and having my staging server up-to-date I am still running into a 401 error. Eventdetails.js import React from 'react' import PropTypes from 'prop-types' import './index.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import moment from "moment"; import {Redirect} from "react-router-dom"; import swal from 'sweetalert'; import axios from "axios"; import {API_HOST} from "../../../constants"; class EventDetails extends React.Component { state = { redirect: false, }; setRedirect = () => { this.setState({ redirect: true }); }; renderRedirect = () => { if (this.state.redirect) { return <Redirect to='/Calendar/index'/> } }; deletePopUp = () => { swal({ title: "Diesen Termin wirklich löschen?", text: "Diesen Termin wird dauerhaft gelöscht. Diese Aktion kann nicht rückgängig gemacht werden.", buttons: { cancel: "Abbrechen", confirm: { text: "Ja, Termin löschen", className: "swal-button--confirm_red", visible: true, value: "confirm", }, }, }, ).then(async (value) => { switch (value) { case "confirm": const token = localStorage.getItem('accessToken'); await axios.delete(`${API_HOST}/events/${this.props.eventId}/`, { headers: { 'authorization': `Bearer … -
how can I enable django user to download portion of the db? or db entered by him?
I want to help user to save a copy of data entered by him in the cloud, is this feature available in django? or are there an alternatives? -
How run task asynchronously whith Celery in Django App?
My settings.py CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ALWAYS_EAGER = 'False' my celery.py from __future__ import absolute_import import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_try.settings') from django.conf import settings from celery import Celery app = Celery('celery_try', backend='amqp', broker='amqp://guest@localhost//') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) i have a view: def home(request): try: return render(request, 'app/home.html') finally: print '1' mytask.delay() and I have a script: from celery import shared_task @shared_task() def mytask(): time.sleep(10) print("Test 1234!") Actually it render home.html after 10 seconds and after print Test 1234! My goal is render home.html and AFTER 10 seconds run mytask() Any solution? -
How to redirect to homepage from navbar?
I'm very new to web-development. I created some pages such as products,create,delete. I have a navbar in base.html. The problem is that when i go to a page for example "product page" and then when clicked create on navbar it brought me to "http://127.0.0.1:8000/products/create/" and it doesn't exist I want to go to "http://127.0.0.1:8000/create/ from that, how do I do it? Thank you very much urlpatterns = [ path('admin/', admin.site.urls), path('', homepage, name ="home"), path('create/', create_product), path('products/', view_allproducts), path('products/<str:slug>/', retrive_product), path('products/<str:slug>/edit', update_product), path('products/<str:slug>/delete', delete_product), path("register/",register, name="register"), ------------------------------------------------------------- -
code examples of django-logpipe for kafka,thanks
I've seen documents on the official website, Document description is not detailed. as below: from django.db import models from rest_framework import serializers import uuid class Person(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class PersonSerializer(serializers.ModelSerializer): MESSAGE_TYPE = 'person' VERSION = 1 KEY_FIELD = 'uuid' class Meta: model = Person fields = ['uuid', 'first_name', 'last_name'] @classmethod def lookup_instance(cls, uuid, **kwargs): try: return Person.objects.get(uuid=uuid) except models.Person.DoesNotExist: pass -
Django rest framework Serializer: get source from POST request
I want to add data from a POST request to my serializer: class DeviceSerializer(ModelSerializerWithFields): class Meta: model = Device exclude = ("groups",) last_values = serializers.JSONField(source="get_graph_data", read_only=True) How can I get the resulting values from passing a specific request to get_graph_data? Ideally something like: last_values = serializers.JSONField(source="get_graph_data", read_only=True, payload="{'foo':1, 'bar':15}") but if not, at least a way to pass one value so I can edit the endpoint to take this specific case into account