Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing a image in Django file-system (without using a database)
index.html <form method="POST" action="."> {% csrf_token %} {{ image_form.as_p }} <input type="submit" name="submit" value="Search via URL"> </form> forms.py class UploadImageForm(forms.Form): image_field = forms.ImageField(required=False) views.py if request.method == 'POST': if request.POST.get('submit') == 'Search via Image': print(request.POST) print(request.FILES) So I want to take the image uploaded by the user and save it in my storage, perform a few operations on it, display it on the webpage and delete it. But I am not being able to go this. In request.POST I'm getting a dict containing the file name, but that's plain text. And while using request.FILES I'm getting, <MultiValueDict: {}> How should I go about this? Thanks, in advance. -
unable to import models: for comment
i'm trying to import comment models but i'm getting error while migrate my code from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image from django.urls import reverse class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=300) image = models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) class Comments(models.Model): Post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') user_id = models.ForeignKey(User,on_delete=models.CASCADE,default=True) comment = models.TextField() commented = models.DateTimeField(default=timezone.now) the error is :- django.db.utils.IntegrityError: The row in table 'userpost_comment' with primary key '1' has an invalid foreign key: userpost_comment.author_id contains a value 'sd' that does not have a co rresponding value in auth_user.id. -
How can we export dict containg list as value in csv file
Suppose this is input format... {'ID':[1,2,3,4,5,6,7,8,9,10], 'Name':['A','B','C','D','E','F','G'], Flag:['True'], City:'', } and i want to export this data as follow in csv file in python ID Name Flag City 1 A True '' 2 B '' 3 c 4 D 5 E and so on...How can we do it ..? Thankx in advance PF:Im getting input formate from django models -
How to implement Django Session Wizard with multiple templates
Im trying to implement a multi step form in django using the form wizard that comes with django-formtools and so far it steps through all the forms till the last one then instead of calling the done method, the page goes back to the first form. Some of my code is shown below: Urls.py from django.urls import path from minereg import views urlpatterns = [ path('',views.ContactWizard.as_view(views.FORMS),name="registration"), ] Views.py from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import RegForm1,RegForm2 FORMS = [("home",RegForm1),("bank",RegForm2)] TEMPLATES = {"home":"home.html", "bank":"bank.html"} class ContactWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self,form_list, **kwargs): #Required form_data = [form.cleaned_data for form in form_list] print(form_data) return render(self.request,template_name = "thanks.html") The print(form_data) in the done method doesn't happen, showing the code never gets to that point. home.html {% extends "base.html" %} {% load widget_tweaks %} {% load i18n %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="{%url 'registration' %}" method='post'> {% csrf_token %} {{wizard.management_form}} <div class="container col-md-9"> <h1>PERSONAL DETAILS</h1> <p>Please fill in this form to create an account.</p> <hr> <!-- Name --> <div class="row"> <div class="form-group col-md-4"> {{ wizard.form.name.label_tag }} {{ wizard.form.name|add_class:"form-control form-control-lg" }} </div> <div class="form-group col-md-4"> {{ wizard.form.middle_name.label_tag }} {{ wizard.form.middle_name|add_class:"form-control form-control-lg" }} … -
Visual studio code doesn't read db.sqlite3 in django framework
I saw a tutorial of django on youtube. That tutorial explain that I must open and write the db.sqlite3 file. Unfortunately Visual Studio Code doesn't read that file. Can anyone help me? -
How Do I Create A Socail Media App With Python?
Hello Guys I Wanted To Create An Social Media App Which Does Not Mine With User's Data. I Want To Build The App Purely With Python. I Know Kivy, Postgreql, Sockets And Finally Python. Is There Anything Else I Need To Learn To Create An Social Media App? Thanks In Advance. -
MultipleObjectsReturned at /checkout/ get() returned more than one Order -- it returned 2
Hi I'm trying to develop an e-commerce website using Django. I have two models and views on separate folders, one is an order model and view, another is the checkout model and view. The order view creates a new order everytime an item is added to the cart. And the checkout view creates a new billing address. I want to associate the billing address that is created to the order when the checkout form is submitted. But for some reason, it's not happening. It throws an error: MultipleObjectsReturned at /checkout/ get() returned more than one Order -- it returned 2! What is the problem? My orders.models.py: from django.db import models from shopping_cart.models import Cart from django.contrib.auth import get_user_model from accounts2.models import BillingAddress STATUS_CHOICES = ( ("Started", "Started"), ("Abandoned", "Abandoned"), ("Finished", "Finished"), ) User = get_user_model() class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) order_id = models.CharField(max_length=120, default='ABC', unique=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Started") sub_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) tax_total = models.DecimalField(default=0.00, max_digits=1000, decimal_places=2) final_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) billing_address = models.ForeignKey(BillingAddress, on_delete=models.SET_NULL, blank= True, null=True) My orders.views.py: @login_required def order(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return … -
Best approach to multiple user types in django
I have the need for multiple user types in my application, each with different type specific information, and potentially different FK associations to other entities. In my research on the topic I've seen the recommended approach in the documentation is to create a OneToOne related user profile model to the user here. I've also seen this approach suggested in this example and this question. Let's say for the sake of an example: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_number = models.CharField() class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) department = models.ForeignKey(Department) class Course(models.Model): convenor = models.ForeignKey(Teacher) students = models.ManyToManyField(Student) Contrary to the above examples, I've found only one example recommending the use of subclassing of the User model, here. For the above context this would instead be class User(AbstractUser): pass class Student(User): student_number = models.CharField() class Teacher(User): department = models.ForeignKey(Department) This seems to me to be the much more intuitive and less verbose implementation of the same thing. Is a subclass of a model not just a OneToOne association to the parent model? However in the above stack overflow selected answer this approach is specifically advised against, saying it will lead to problems later. How? I … -
Is it a problem to have two or more exactly same class name at different files?
For my django application, I created class based views and each of them is defined at different file: # foo.py from django.views import View ... class MyView(View): def get(...): foo() # bar.py from django.views import View ... class MyView(View): def get(...): bar() Actually, it is not necessary to have same class names because the views (the web pages) does not have the same content. They have different content created by foo() and bar(). What I want to ask is that is having the same class names at different files is contrary to Object-Oriented Programming (OOP) concepts? Any explanation is appreciated. -
.core problem. just want to do simple login app?
using VSCode i am trying to create a basic signin login app. I change to my Python 3.9 env the "no module named" **.core problem seems to be solved but its really because "couldn't import django" problem. I tried my python 3.7 venv but then "couldn't import django". -
Cloud ndb middleware for django Notimplemented error. How can I solve it?
I using django==2.2 and python==3.7. I install latest google-cloud-ndb library using pip. I added the middleware 'google.cloud.ndb.django_middleware.NdbDjangoMiddleware' in the middleware list inside settings.py file. When I try to run runserver command it gives me following error File "S:\Python\Python37\lib\site-packages\google\cloud\ndb\django_middleware.py", line 23, in __init__ raise NotImplementedError NotImplementedError -
Find current static tag in Django
I'm trying to get current active hash for my static files and I'm using CachedStaticFilesStorage <script type="text/javascript" src="https://example.com/static/js/main.787c27db2d80.js"></script> In the template invocation is like below {% javascript 'jquery' %} {% render_bundle 'main' 'js' %} How do I find programmatically (or somewhere in the database/cache) current hash 787c27db2d80 that is used and at which point this value is going to be regenerated. Django 1.11 + django-webpack-loader + django-pipeline -
django , react , redux authentication token is null
im new to react and redux , i have been trying to utilize django as my backend , react as my frontend and redux as my local storage to store authentication states. However i have encountered an error and im not too sure how to debug this. There is no error messages , just that i am unable to pass the token into my components. index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { createStore, compose, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import reducer from './store/reducers/auth'; const composeEnhances = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore(reducer, composeEnhances( applyMiddleware(thunk) )); const app = ( <Provider store={store}> <App /> </Provider> ) ReactDOM.render(app, document.getElementById('root')); registerServiceWorker(); App.js import React, { Component } from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import { connect } from 'react-redux'; import BaseRouter from './routes'; import 'antd/dist/antd.css'; import * as actions from './store/actions/auth'; import CustomLayout from './containers/Layout'; class App extends Component { componentDidMount() { this.props.onTryAutoSignup(); } render() { return ( <div> <Router> <CustomLayout {...this.props}> <BaseRouter /> </CustomLayout> </Router> </div> ); } } const mapStateToProps = state => { return … -
Do I really need to use {% load static %} in Django Templates?
I am using Django 3, the latest version. I have defined the static files directories properly as required. Currently to display an image, both the following source codes work fine. Code 1: <img src="static/img/logo.png"></img> Code 2: {% load static %} <img src="{% static 'img/logo.png' %}"> </img> Since both the code snippets are working and running fine without any problems, I am wondering why not to simply use the way of Code 1 above and refrain from the extra lines of Code 2. Which one would be beneficial and why? Please guide. -
django.urls.exceptions.NoReverseMatch on second level context
I believe my situation is different to other questions and I've tried multiple other answers to no avail. I have a config with a uuid pk. On my list of configs, one can add, edit, delete a config, if you click a config name, it doesn't take you into a detail of the config itself but rather a view of data in other models that references the config as a foreign key (i.e. data "in" that configuration). Within that configuration, one can CRUD each model. I have just started adding the "Add" buttons but get a NoReverseMatch exception. I think this is something to do with my URLs but can't work it out. I know I need to somehow pass the pk from the config to the next view. In addition, when creating an entry for each model, the pk from the config needs to automatically save as a foreign key of the new item (in the background). URLS.PY # My configuration list, and CRUD (this works) path('configurations/', ConfigurationsListView.as_view(), name='configurations'), path('configurations/create/', views.ConfigurationCreate.as_view(), name='configuration_create'), path('configurations/<uuid:pk>/update/', views.ConfigurationUpdate.as_view(), name='configuration_update'), path('configurations/<uuid:pk>/delete/', views.ConfigurationDelete.as_view(), name='configuration_delete'), # My configuration detail view (actually a view of data with the config as a foreign key) path('configurations/configuration/<config_id>', views.ConfigurationDetailView.as_view(), name='configuration_detail'), # … -
How to run a cronjob in a Django app running on nginx uwsgi
I have a django app running on a webserber with nginx and uwsgi. On my local server the crons are working. i add it with python3 manage.py crontab add command. I guess it doesnt work this way on the weberserver as it's not working when i try. I can't find / figure out how to configure it properly. Maybe someone can enlight me ? Thanks -
Django: not able to run application using uwsgi
I ma trying to run django application using uwsgi but it throws continuously one error : not able to import site module the issue is was previously running it under python2.7 env but then i switched to virtual env with python3.6 and after that i am not able to run this project under python3.6 env it always runs in 2.7 I have tried all the tutorials but i'm not able to get the result this is my uwsgi.ini file : [uwsgi] # telling user to execute file # telling group to execute file #gid = webapps # name of project you during "django-admin startproject <name>" project_name = xyz_dev # building base path to where project directory is present [In my case this dir is also where my virtual env is] base_dir = /home/ubuntu/croydoner/%(project_name) # set PYTHONHOME/virtualenv or setting where my virtual enviroment is # WSGIPythonPath = /usr/local/lib/python2.7/dist-packages/ virtualenv = /home/ubuntu/croydoner/venv/ # plugins-dir = /usr/local/uwsgi-2.0.18/plugins/python # plugins = python3.6 # unprivileged-binary-patch = /home/ubuntu/croydoner/venv/bin/uwsgi # changig current directory to project directory where manage.py is present chdir = %(base_dir) # loading wsgi module wsgi-file = %(base_dir)/demo/wsgi.py http = :8090 # enabling master process with n numer of child process master = true processes … -
DRF explicit ordering direction
Im looking for a solution for DRF where I would get query like this: ..../?sort=foo&order=asc/desc I was able to change order param to "sort" but I dont know how to add explicitly "&order=asc" except current solution which uses "-" before column. thank you in advance. -
convert mp3 file to wave and send via request django
so i want to send auido file of mp3 type to my backend which is a Django and i want to convert it to wav file in the django backend and return it to the front end my problem is how to do it directly without saving it in my current folder because i want to deploy it later in heroku ijust started learnig Django the problem i am facing is in converting and return it as a request HTTP i tried sound=pydub.AudioSegment.from_mp3(mp3_file) sound=sound.set_frame_rate(8000) sound.export(wav, format="wav") but the problem that sound.export save it in my current folder and i have to send it back to my frontend as a HTTP request and i have to do it a lot so its not ok to save it each time in my folder -
Set default tags in Django/Wagtail
I want to be able to set a list of default tags using Taggable Manager. city_region_tags = TaggableManager(through=CityRegionSnippetTag, blank=True) The CityRegionTableSnippetTag is - class CityRegionSnippetTag(TaggedItemBase): content_object = models.ForeignKey( 'CityRegionSnippet', on_delete=models.CASCADE, related_name='tagged_city_region' ) Ideally I would pass a list of default tags e.g. tag_list = ['Spatial Patterns', 'Functional dynamics', 'Social-eco dynamics', 'Global-local dynamics'] and so on. Is there a way to do this? I had a look at custom tagging here and doesn't appear to be what I want to do - (https://django-taggit.readthedocs.io/en/latest/custom_tagging.html#) Documentation on tags in forms shows what the tags would look like in a list but that is after user input. I want to be able to put these tags in before the user gets there from the tag_list - (https://django-taggit.readthedocs.io/en/latest/forms.html#tags-in-forms) -
Django - best way to update a summary stats table based on incoming API data
Background: I've got a Django project which uses the restful api to send in user data. This data comes from a few different devices, and consists of the player's name and a score. A version of the models is shown below. class User(models.Model): full_name = models.TextField(null=True, blank=True) device = models.TextField(null=True, blank=True) class Score(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="scores") score = models.CharField(max_length=64, blank=True, null=True) timestamp = models.DateTimeField(null=True) I now want the site to calculate some user summary statistics based on the scores, and store them in another table that I can reference elsewhere on the site. This will be called something like UserStats, and contains data that can't just be aggregated by querying the scores. Things like number of games, that will require processing through the scores. class UserStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stats") number_of_games = models.IntegerField(default=0) Question: My question is, what is the best way of processing the incoming Scores on the server? Essentially once a new score appears I want to process it and update the fields in the UserStats model. Methods I'm aware of: Add the code to the score api view. So when a score is submitted, it checks the UserStats model and creates or updates it. … -
Django Rest Framework ,logic of Like button for blog posts
I have a Django Rest Framework project, users can post,comment any post and like any post. I can't figure it out the logic in models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=100) post_author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='posts') def __str__(self): return self.title class Comment(models.Model): body=models.CharField(max_length=100) commet_post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.body class Like(models.Model): like_post = models.ForeignKey(Post,on_delete=models.CASCADE) like_author=models.ForeignKey(User,on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) -
How to save the data we get from GET request to models in Django?
I am using APIView of Django restframework for my API. my serializer file: class HelloSerializer2(serializers.Serializer): '''Searlizes id field for viewing details ''' id = serializers.CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) I want to save the response i am getting in database. How do i do that?? the response is like this { "json": { "ver": "1.0", "version": "1.0", "name": "xxxxx", "attr_names": [ "xxxxx" ], "main_id": "xxxxxxx", "seqNo": 1234 } } model.py : class Table(models.Model): """Database model for saving """ #id = models.IntegerField() main_id = models.TextField() name = models.TextField() version = models.TextField() attributes = models.TextField() seq_num = models.IntegerField() def __str__(self): return self.main_id -
I'm trying to complete the Django website tutorial, following the youtube tutorial - and at the beginning I have this "error"
The tutorial writes in "source env/bin/activate" When I write it in this is what comes out: (venv) C:\Users\user\PycharmProjects\FirstProject>source env/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. He uses a mac and I use Windows 10, do I need a different line of code? -
Uncaught ReferenceError: function is not defined - when calling function from outside jQuery ajaxSetup
I am including the below code (found here Django CSRF check failing with an Ajax POST request) to get my AJAX requests to send back the CSRF token in he custom X_CSRFTOKEN header - it was working fine for me so far: $.ajaxSetup({ beforeSend: function(xhr, settings) { 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 = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); But now, when calling the getCookie() function below, I get the error Uncaught ReferenceError: getCookie is not defined at previous_selection: var preselection = localStorage.getItem("preselection"); function previous_selection () { if (localStorage.getItem("preselection") != null) { const data = new FormData(); data.append("preselection", preselection); const request = new XMLHttpRequest(); request.open('POST', '/prebasket'); request.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); request.send(data); return false; } } previous_selection(); Is it a scope problem? If so, why did the exact same ajaxSetup-code work in a previous getCookie() call I had out of a different script? For completion's sake: I am trying to use/access …