Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Query for abstract model class in Django
I have a abstract class I want like this: def detail(request,slug): game=get_object_or_404(Game,slug=slug) if game.type='1' lol=get_object_or_404(LeagueOfLegendsGame,....) elif game.type='2' warcraft=get_object_or_404(WarcraftGame,...) (i know abstract class cannot create object. What should you suggest) model.py class Game(models.Model): slug=models.SlugField(unique=True)... type=models.CharField(max_length=10,null=True,blank=True) class Meta: abstract = True class LeagueOfLegendsGame(Game): fields.... class WarcraftGame(Game): fields.... -
Django csv output with react
I am working on a task that needs to write to csv and download in the frontend. In views I have done: ...omitted details data = data.values(*values_fields) response = HttpResponse(content_type='text/csv') writer = csv.DictWriter(response, fieldnames=values_fields) writer.writeheader() writer.writerows(data) return response And, in the frontend: let a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; const blob = new Blob(res, {type: "text/csv"}); const url = window.URL.createObjectURL(blob); a.href = url; a.download = 'data.csv'; a.click(); window.URL.revokeObjectURL(url); a.remove() First of all, when I inspect res, I have only seen arrays of integers instead of dictionaries. How can I download my data? -
Where to put extra logic in django web API, in the view, or in the serializer?
I have a DRF view which extends CreateModelMixin and GenericViewSet. In the body of the post request, I want to accept an extra field, which does not belong to the related model. Then, I want to pop that extra field, use it for other purposes. I do not want to put that extra field back to the http response because it is a big and complex object. To explain it better here is a sample json input and the response that I want to return to the user: Request: # request { "name": "Why Nations Fail", "extra_field": { "my_keys": ["I'm", "a", "very", "big", "JSON-array", "object.", "..."] } } Response: # response { "id": 120 "name": "Why Nations Fail" } My problem is, I can't decide where to do this pop this extra_field; in the view or in the serializer (which extends ModelSerializer). Currently, I managed to do that by extending the create method handler of my view. But according the books and tutorials I've read: We should keep our views thin and our serializers thick. Keeping this in mind, I have tried to pop the field in the serializer but I couldn't manage to do that, I think because I'm … -
Cant use JsonResponse in Django
I have a bunch of values which I would like to send from views.py function to my template in Django. I saw some topics that the best way is by json format. So I did so. But because my values are not ascii I'm using a upgraded version which worked in normal Http response but don't work in JSON response. HERE is my code base = {weather_main_key : weather_main_values, wind_speed_key : wind_speed_value + "m", wind_deg_key : wind_deg_value, base_temp_key : base_temp_value + " ℃", base_press_key : base_press_value + " mbar", base_hum_key : base_hum_value + " % " } base = json.dumps(base, ensure_ascii=False).encode('utf8') return JsonResponse(json.dumps(base)) So I had an error msg In order to allow non-dict objects to be serialized set the safe parameter to False. So I did as it told me JsonResponse(json.dumps(base, safe=False, ensure_ascii=False).encode('utf8')) And now the error is __init__() got an unexpected keyword argument 'safe' And I can't move... -
Django - objects.all() shows nothing
I'm trying to get a list of objects in Django from a model. I just want to get the list of 'dht node' from the request user, but it shows nothing in the html file (as if the list was empty). The user that I'm using has 2 'dht nodes' and they're shown in the django admin. I don't know what is wrong, because if I use the instruction "member.dht.create(...)" in the views function and a create a new 'dht node' like this, this is shown. Only 'dht nodes' that I enter by form do not show. Can be the form? Thanks a lot, Here's my code: Models.py class Node(models.Model): name = models.CharField(primary_key=True, null=False, max_length= 50) description= models.CharField(default=None, null=False, max_length= 250) topic=models.CharField(default=None, null=False, max_length= 50, unique=True) def __unicode__(self): return self.name class dht(Node): temp = models.IntegerField(default=None, null=True) hum = models.IntegerField(default=None, null=True) class UserProfile(User): uid = models.CharField(default=None, null=False, max_length= 250) dht = models.ManyToManyField(dht, blank=True) def __unicode__(self): return self.user.username Views.py -dht list- @login_required(login_url = '/web/login') def listDhtSensor(request): member = request.user.userprofile list = member.dht.all() return render(request, 'web/listDhtSensor.html', {'list':list}) Html -listDhtSensor.html- {% block content %} {% for dht in list %} {{ dht.name }} {{ dht.topic }} {% endfor %} {% endblock %} Forms.py class … -
Python library can be found in PyPi but can't be installed by 'pip install'
I got django project code and tried to install all the requirements by 'pip install -r requiremets.txt' but somehow it doesn't work. occurred error is below Could not find a version that satisfies the requirement mkl-fft==1.0.9 (from -r requirements.txt (line 14)) (from versions: 1.0.0.17, 1.0.2, 1.0.6) No matching distribution found for mkl-fft==1.0.9 (from -r requirements.txt (line 14)) I tried to upgrade pip but it didnt work. -
How to show login form error in login page?
I'm trying to create a login page. I have used the default auth_view templates. I want to print the username and password field error in my login page. But cannot show them. I have tried using {{ form.username.errors }} but it is not working. But when is say {{ form.error }} it shows like below: __all__ Please enter a correct username and password. Note that both fields may be case-sensitive. urls.py path('login/', auth_views.LoginView.as_view(template_name='profiles/login.html'), name="login"), form template <div class="login-clean"> <form method="post"> <h2 class="sr-only">Login Form</h2> <div class="illustration"><i class="icon ion-code" style="color: rgb(71,151,244);"></i></div> {% csrf_token %} {{form.errors}} <div class="form-group"><input class="form-control" id="{{ form.username.id_for_label }}" type="text" name="{{ form.username.html_name }}" placeholder="username"></div> <div class="form-group"><input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name }}" placeholder="username"></div> <div class="form-group"><button class="btn btn-primary btn-block" type="submit" style="background-color: rgb(71,151,244);">Log In</button></div><a class="forgot" href="#">Forgot your email or password?</a> </form> I want to see error results also If I want to style it, How to do it? -
Django with Apache and mod_wsgi: Timeout error
I'm trying to deploy Django application on a CentOS 7 server with Apache and mod_wsgi. The application is using plotly library to create graphs and plotly is using orca application to export created graph to image. I tested the application using the integrated django web server - everything works perfectly. So I set up Apache and mod_wsgi according official documentation. When I connect to Apache the application works, but it is not possible to export graphs. Browser ends up with Gateway Timeout Error. I inserted logger messages to the code which creates and exports graphs. The code runs until this line: static_image_bytes = plotly.io.to_image(figure, format='png', width=800, height=450) This line should run local Orca application and translate figure object to PNG image bytes. Orca requires X11 display server and CentOS is installed without GUI. I'm using Xvfb to emulate X11 (according to Orca's github page). Orca application is an AppImage downloaded from github. /bin/orca #!/bin/bash echo "`date` - ORCA STARTING with $@" >> /tmp/orca.log xvfb-run /usr/u/s/orca-1.2.1-x86_64.AppImage "$@" echo "`date` - ORCA FINISHED" >> /tmp/orca.log Also, I have tried to link /bin/orca directly to AppImage using: ln -s /usr/u/s/orca-1.2.1-x86_64.AppImage /bin/orca and adding this line to my code: plotly.io.orca.config.use_xvfb = True Apache error_log: …