Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save() prohibited to prevent data loss due to unsaved related object 'user'
i am trying to save data in a table when a user click the checkout button of add to cart but it is showing me the above mention error i am unable to understand and one more thing is happening when i logout my the cart which i saved also got erased is it shomehow related to that i don't know here is my views.py for checkout button class Checkout(View): def post (self, request,): user = request.session.get('user') ids = (list(request.session.get('cart').keys())) sections = Section.get_sections_by_id(ids) for section in sections: order = Order(user = User(id=user), section = section, price = section.price, ) order.save() my views.py for cart.html class Cart(View): def get (self, request): ids = (list(request.session.get('cart').keys())) sections = Section.get_sections_by_id(ids) print(sections) return render(request, 'cart.html', {'sections': sections}) my urls.py urlpatterns = [ path('cart/', Cart.as_view(),name='cart'), path('Check-Out/', Checkout.as_view(),name='checkout'), ] my cart.html {% extends 'base.html' %} {% load static %} {% load cart %} {% load custom %} {% block head %} <link rel="stylesheet" href="{% static 'css/cart.css' %}"> {% endblock %} {% block content %} <div class="container jumbotron"> <section> <h1>My cart</h1> <table class="table"> <thead> <tr> <th scope="col">S.no</th> <th scope="col">Subject</th> <th scope="col">Section</th> <th scope="col">Teacher</th> <th scope="col">Duration</th> <th scope="col">Price</th> </tr> </thead> {% for section in sections%} <tbody style="margin-bottom: 20px;"> <tr> … -
Django Storages for saving media to S3 - it is duplicating uploaded images locally
I am using django-storages to upload media files to S3. This works all fine, the issue is that its also making a copy in local folders, which is causing the server for the app fill up pretty fast. Django v3 Django-storages v1.11.1 custom-storages.py. This was based on web based tutorial. I can see (and assume its because of this) the cached storage, but i cannot see how or where it actually uses it to adjust it. from django.conf import settings from django.core.files.storage import get_storage_class from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION file_overwrite = False class CachedS3Boto3Storage(S3Boto3Storage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super(CachedS3Boto3Storage, self).__init__(*args, **kwargs) self.local_storage = get_storage_class( "compressor.storage.CompressorFileStorage")() def save(self, name, content): self.local_storage._save(name, content) super(CachedS3Boto3Storage, self).save(name, self.local_storage._open(name)) return name settings.py AWS_S3 = True if AWS_S3: AWS_DEFAULT_ACL = 'public-read' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_ACCESS_KEY_ID = ... AWS_SECRET_ACCESS_KEY = ... AWS_STORAGE_BUCKET_NAME = ... AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_HOST = 's3-eu-west-2.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_PRELOAD_METADATA = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'connect.custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' MEDIA_URL = … -
manage.py migrate not working properly it is migrating exisiting table
I am working in djongo and i created a new model and apply the migrations using. python manage.py makemigrations This gave me description related to the new model i have created but when i am doing python manage.py migrate It is giving me the error djongo.sql2mongo.SQLDecodeError: FAILED SQL: CREATE TABLE shareactivity Although that table has been migrated succesfully in my last migration.My latest migration file is 23 and inside it, It has dependenices on file 22 and in file 22 i have that shareactivity table migration -
How I can use Checkbox list widget in admin panel?
I want to use checkbox list in admin panel in django. How can i do that without using from django import forms? -
Why do I get 404 error when trying to GET image from heroku?
So I have deployed my Django project via heroku. I'm testing my api calls, but getting error when fetching images. On request, I was able to get this data : { "id": 1, "source": 2, "category": [ 1, 4 ], "key_line": "blabla", "footnote": "", "created_at": "2021-07-19", "image": "https://bookcake.herokuapp.com/api/cake/media/None/rlvdmseoghk.jpg", } Now the problem is the image field. All other data show up fine in the front-end, but the image doesn't. As well, nothing shows up when I click on that link. What could be the problem? Here's my settings.py file for your information, but I don't see any problem with it. ... MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
view images uploaded from admin on html in django
I am learning to write a Django app which will fetch all images from os.path.join(BASE_DIR, 'media_root', 'uploads') and show it on html page. But its not working like so. admin.py from .models import Experience # Register your models here. admin.site.register(Experience) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') MEDIA_URL = '/media/' models.py class Experience(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='uploads/', default='newbalance.jpg', height_field=None, width_field=None) studio_name = models.CharField(max_length=255) designation = models.CharField(max_length=255) duration = models.CharField(max_length=255) description_short = models.TextField() description_long = models.TextField() keywords = models.CharField(max_length=255) date = models.DateTimeField('DateAdded', auto_now=True, auto_now_add=False) class Meta: db_table = "experience" def __str__(self): return self.studio_name + ' ' + self.duration views.py class ExperienceList(generic.ListView): model = Experience template_name = 'resumesection.html' queryset = Experience.objects.all() urls.py urlpatterns = [ path('modelview/', views.ExperienceList.as_view(), name='experience_list'), ] In error log, 2021-07-19 04:15:40,528: Not Found: /resume_site/modelview/uploads/atomic_arts.png 2021-07-19 04:15:41,239: Not Found: /resume_site/modelview/uploads/futureworks.jpg I presume django should read image from 'MEDIA_ROOT/uploads' folder but it reads from '/resume_site/modelview/uploads/'. Which is not there. I come close to the answer in this post Django admin view uploaded photo, But cannot connect the dots between 'MEDIA_ROOT/uploads' and '/resume_site/modelview/uploads/' How does viewing image, uploaded from admin, work in django. ? -
python-docx and Django - identical method doesn't work in django
I started a Django project weeks ago. It fits into the keyword "customer relation management (CRM)". One of the tools is using a docx-template replacing keywords in a docx-template with python-docx and save it as a new document. All of it works like a charm in jupyter notebook. After developing my code, I transferred it into my Django project which I am developing with pycharm. Everything worked smoothly, but ... The created docx-file cannot be opened. "Pages could not read the file." And furthermore, in the destination directory, there is a mysterious file "~$[part-of-the-filename].docx", which also can not be opened. Can anyone help me with this? Could not find anything about it on the web. And I think it is not about writing permissions, since the file is created. Thanks in advance! Here is my code: def main(gutachtenid): # get data from db con = psycopg2.connect(database="postgres", user="user", password="password", host="127.0.0.1", port="5432") cur = con.cursor() cur.execute('SELECT COLUMNS from table;') last_case = cur.fetchall()[gutachtenid-1] template_file_path = '/template/MTXXXXX-file.docx' output_file_path1 = f'/template/MT{gutachtenid}//MT{gutachtenid}-file.docx' if os.path.exists(output_file_path1): variables = { "${keyword1}": last_case[3], "${keyword2}": last_case[1], "${keyword3}": last_case[2], } template_document = Document(template_file_path) for variable_key, variable_value in variables.items(): for paragraph in template_document.paragraphs: replace_text_in_paragraph(paragraph, variable_key, variable_value) for table in template_document.tables: for col in … -
How to get stock data and add it to a django model?
Hay, I am building a finance website where there is a stock model. I want the price to update automatically in a intfield when the website is running. -
Django-Rest-Framework: How to build Async Directory/Folder upload and Bulk File upload
So My team mates and I have been having a hard time with the efficiency of the synchronous file upload CRUD endpoints we've built and now we need to implement a bulk file upload(Directory upload) with either celery or asyncio(any other methods are kindly welcome). what I have working currently My Model: class CompanyFileUpload(SoftDeletionModel): name = models.CharField( max_length=100, null=True, unique=False, blank=True, default="file name" ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='company_file_uploads' ) timestamp = models.DateTimeField( auto_now_add=True ) data_file = models.FileField( upload_to=Utils.create_company_file_upload_path, blank=True, null=True, validators=[validate_file] ) comment = models.CharField( max_length=400, null=True, unique=False ) file_size = models.CharField( max_length=100, null=True, unique=False, blank=True, default="null" ) def save(self, *args, **kwargs): size = self.data_file.size power = 2**10 n = 0 power_labels = {0: '', 1: 'Kilo', 2: 'Mega', 3: 'Giga', 4: 'Tera'} while size > power: size /= power n += 1 self.file_size = f"{size:.2f} {power_labels[n]}bytes" self.name = self.data_file.name super(CompanyFileUpload, self).save(*args, **kwargs) def __str__(self): return f'{self.data_file}, {self.user}' @receiver(post_save, sender=CompanyFileUpload) def email_report_details_handler(sender, instance, **kwargs): ctx = { "firstname": instance.user.firstname, "timestamp": instance.timestamp, "fullname_and_email": f"{instance.user.firstname} {instance.user.othernames}", "subject": "File Upload", "recepient": instance.user.email, "email": instance.user.email, "url": instance.data_file.url, "comment": instance.comment } Utils.send_report_email(ctx) My serializer: class CompanyFileUploadSerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField( format="%d-%m-%Y %H:%M:%S", read_only=True) class Meta: model = CompanyFileUpload fields = ["id", "name", "user", "data_file", … -
Problem with redirecting in django html file
Hey so I am building a personal website and i am getting an error whenever I click on the the redirect link and i am quite puzzled how to proceed, I am also sending my url.py, views.py and navbar.html (html file where redirect code is) code views.py def product(request): return render(request = request, template_name = "main/categories.html", context ={"categories": ItemCategory.objects.all}) def homepage(request): return render(request = request, template_name = "main/categories.html", context ={"categories": ItemCategory.objects.all}) def about(request): return render(request = request, template_name = "main/about.html", context ={"categories": ItemCategory.objects.all}) def contact(request): return render(request = request, template_name = "main/contact.html", context ={"categories": ItemCategory.objects.all}) url.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = "main" urlpatterns = [ path("", views.homepage, name="homepage"), path("product/", views.product, name="product"), path("about/", views.about, name="about"), path("contact/", views.contact, name="contact"), path("register/", views.register, name = "register"), path("logout/", views.logout_request, name = "logout"), path("login/", views.login_request, name = "login"), path("<single_slug>", views.single_slug, name="single_slug"), ] urlpatterns += staticfiles_urlpatterns() navbar.html <nav> <div id="nav-wrapper"> <div> <ul class="center hide-on-med-and-down"> <li> <a href="{% url 'homepage' %}">Home</a> </li> <li> <a href="about/">About Us</a> </li> <li> <a href="product/">Products</a> </li> <li> <a href="services/">Services</a> </li> <li> <a href="contact/">Contact</a> </li> <li> <a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a> </li> </ul> </div> </div> </nav> … -
How to all Django Template in a new window from Vue.js?
I am using DRF for backend and Vue for frontend, and have encountered the following problem by calling Django templates in Vue. In Vue there is a button "Call Django Template" and it should be opened in a new window. However, it does not work and I cannot get why. When I press the button nothing happens, Django tries to render the template, however no new window is opened. [19/Jul/2021 14:47:11] "GET /home HTTP/1.1" 200 323 my Django template, some dummy url <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login PopUp</title> </head> <body> {% block content %} <script language="javascript" type="text/javascript"> window.open('https://www.google.com/','Test','height=200,width=150'); </script> {% endblock %} </body> </html> my views.py # just a dummy test view def home_view(request): test = 'a' if test == 'a': return render(request, 'connectors/registration/test-a.html') else: return render(request, 'connectors/registration/login-popup.html') my urls.py path('home', views.home_view, name="home"), my Vue function testHome: function() { fetch('http://localhost:8000/home'); } I cannot call the view in a new window from Vue cos it is not the full code. -
How to make two urls to the same app in Django?
It's my main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('account.urls')), ] And it's my urls.py of 'product' app: urlpatterns = [ path('<slug:slug>/', views.getProductPage), path('category/<slug:slug>/', views.getCategoryProducts), ] I would like to have such links: localhost/category/smartphones - shows all smartphones localhost/xiaomi-redmi-note-7 - shows a page of xiaomi redmi note 7 smartphone -
do signals such as post_delete get included in the initiating delete transaction
I have two models related by models.OneToOneField. I am using to post_delete signal to remove the related object. Are both these deletes included in the one transaction by default? If not how would I make sure they are. @receiver(post_delete, sender=Owner) def post_delete_owner(sender, instance, *args, **kwargs): if instance.address: instance.address.delete() -
Unable to redirect to __init__.py while uploading flask app on ubuntu server
I am very new to web development and I am following these two methods (both are same) to deploy flask app to ubuntu vps. https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps https://www.youtube.com/watch?v=YFBRVJPhDGY my folder structure is like this: |--------cwh |----------------cwh |-----------------------static |-----------------------templates |-----------------------venv |-----------------------__init__.py |----------------cwh.wsgi Below is my code of __init__.py: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello, I love my first website!" Below is my code of cwh.wsgi file: #!/usr/bin/python3 import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/cwh/") from cwh import app as application application.secret_key = 'Add-secret' Below is the code of cwh.conf file that i uploaded at /etc/apache2/sites-available <VirtualHost *:80> ServerName 143.198.190.148 ServerAlias www.saassusar.com ServerAdmin saassusar@gmail.com WSGIScriptAlias / /var/www/cwh/cwh.wsgi <Directory /var/www/cwh/cwh/> Order allow,deny Allow from all </Directory> Alias /static /var/www/cwh/cwh/static <Directory /var/www/cwh/cwh/static/> Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> The Problem is that after several attempts I am unable to display __init__.py message at my ipaddress. Instead default apache index file is being displayed. Even if there is no static folder, cwh.conf activation doesn't show any error. -
Showing specific model data in html - Django
I am creating a donation application that allows donors to donate stuff. I have a screen, called availablesupplies.html which renders out all of the donations from the database using a for loop. Each donation is displayed in a user-friendly way, and contains a button that allows them to see details about that specific donation. When the button is clicked, the user is redirected to a page, which I want to contain details about the donation that they clicked on My problem is that I can't figure out how to display a specific donation from my models, for example if my user clicked on an apple donation, I want to get the details for this donation and display it on another page My code: Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (this is where I want to render out the model data): {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div … -
Extending Django field raises exception in constructor
I have the following "custom" field: from django.db.models import DecimalField class CurrencyField(DecimalField): def __init__(self): super(DecimalField, self).__init__(max_digits=30, decimal_places=8) Where the constructor for DecimalField is: class DecimalField(Field): def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) Yet I'm getting: File "/x/x/custom_fields.py", line 13, in __init__ super(DecimalField, self).__init__(max_digits=30, decimal_places=8) TypeError: __init__() got an unexpected keyword argument 'max_digits' Why? -
Django how to write a function for changing user password
I want to write a function for changing the user's password after the first login, so I tried the following code. from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.decorators import login_required @login_required def change_password(request): if request.method == "POST": form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect("change_password") else: form = PasswordChangeForm(request.user) return render(request, "Authentication/change_password.html", {"form": form}) So, everything works fine, but when I type the old password and new passwords and submit the form, I get a popup dialog box with a list of my users that tells select which login to update. However, I am logged in as an active user. -
How to solve IntegrityError
I tried to write a review in a form,but after submitting the form it shows an error.I tried different ways to solve this issue but in vein.Actually I create a review form in such a way that any user can submit their review using this form or they can update their previous review.Here I used try and except methods.Can anyone suggest a solution for this. I got a Traceback like this: Internal Server Error: /User_Reviews/5 Traceback (most recent call last): File "D:\Project\movie_project\movie\review\views.py", line 42, in user_reviews ureview = reviews.objects.get( movie__id=movies_id,user__id=request.user.id) File "D:\Project\movie_project\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Project\movie_project\venv\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( review.models.reviews.DoesNotExist: reviews matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Project\movie_project\venv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "D:\Project\movie_project\venv\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "D:\Project\movie_project\venv\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "D:\Project\movie_project\venv\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1048, "Column 'movie_id' cannot be null") During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Project\movie_project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Project\movie_project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = … -
Cant resolve src/index.js
I've been trying to build a react app and I am encountering this error when I run my npm. My webpack.config file contains:- module.exports = { module: { rules: [ { test:/\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } } My package.json file contains:- { "name": "leadmanager", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/main.js", "build": "webpack --mode production ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.14.6", "@babel/preset-env": "^7.14.7", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "babel-plugin-transform-class-properties": "^6.24.1", "webpack": "^5.44.0", "webpack-cli": "^4.7.2" }, "dependencies": { "prop-types": "^15.7.2", "react": "^17.0.2", "react-dom": "^17.0.2" } } My file hierarchy looks like this:- I have tried lot of methods but none of them work. Please help -
How do I open my edit complaint page for one specific complaint in django
I have a view complaints page where a user can view the complaints he/she have submitted. When the user clicks on one of the cards, I need a new page to open where the user can view the details of that complaint and edit it as well. It should go from here: to here: Where they can view details and make changes as well: This is my models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: def EditComplaints(request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) template (the view history page): <div class="col right-pro-con"> <div class="img-cir"> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} {% if request.user.profile.profile_pic.url %} <img src={{request.user.profile.profile_pic.url}} alt="" width="100px" … -
Django - Got KeyError when attempting to get a value for field `address` on serializer `RegistrationSerializer`
I 'm trying to build a view to create a new user. In this view I call a serializer which must use 2 different tables Here is the request : { "email": "email@example.com", "name": "name", "surname": "surname", "phone": "0601234567", "password": "azerty", "address": { "osm": "N65719518", "lat": 18.072, "lon": 36.087, "street": "Name of the street", "postalCode": 123456, "city": "name of the city" } } I would like to separate the "address" field from my query which corresponds to another table. For this I use the pop method in my serializer Here is my serializer : serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class RegistrationSerializer(serializers.ModelSerializer): """Create an account""" address = AddressSerializer() class Meta: model = User exclude = ['joined', 'lastLogin', 'is_staff', 'is_superuser', 'is_admin', 'is_active'] extra_kwargs = { # For security to hide the password (we can't read it) 'password': {'write_only': True}, } def save(self): # Pop the address of the user address = self.validated_data.pop("address") user = User.objects.create(**self.validated_data) user.set_password(self.validated_data['password']) user.save() Address.objects.create(user=user, **address) token = Token.objects.get(user=user) confirmation(user, token.key) return user Here is the view in which I call my serializer : views.py class HandleUsers(HandleUsersView): def post(self, request): """For everyone""" serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() token = Token.objects.get(user=user).key … -
Django rest framework - Serializer always returns empty object ({})
I am creating first rest api in django using django rest framework I am unable to get object in json format. Serializer always returns empty object {} models.py class Shop(models.Model): id = models.PositiveIntegerField(unique=True) name = models.CharField(max_length=1000) address = models.CharField(max_length=4000) serializers.py class ShopSerializer(serializers.Serializer): class Meta: model = Shop fields = '__all__' views.py @api_view(['GET']) def auth(request): username = request.data['username'] password = request.data['password'] statusCode = status.HTTP_200_OK try: user = authenticate(username=username, password=password) if user: if user.is_active: context_data = request.data shop = Shop.objects.get(id = username) shop_data = ShopSerializer(shop).data if shop: print(shop_data) else: print('false') else: pass else: context_data = { "Error": { "status": 401, "message": "Invalid credentials", } } statusCode = status.HTTP_401_UNAUTHORIZED except Exception as e: pass return Response(context_data, status=statusCode) When i try to print print(shop_data) it always returns empty object Any help, why object is empty rather than returning Shop object in json format? -
Why my django server throws an error of invalid datatype?
Whenever i called my booking function with a post method in that it throws me an error of 'Invalid Data Type it expected dict but its an int'. So when i debug that i found a problem in my serializers so Please help me to resolve the error model.py class Booking(models.Model): details = models.ForeignKey(PersonalDetails, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) total_amount = models.IntegerField() show = models.ForeignKey(ShowTime, on_delete=models.CASCADE) def __str__(self) -> str: return self.total_amount views.py class BookingTicketsQuery(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): booking_id = request.query_params.get('booking_no', None) if booking_id is not None: queryset = Booking.objects.get(id=booking_id) else: return Response("invalid", status=status.HTTP_409_CONFLICT) seriliazer = BookingSerializer(queryset) return Response(seriliazer.data) def post(self, request, format=None): recieve_data = JSONParser().parse(request) showtime = ShowTime.objects.get(id=recieve_data['show']) print(showtime) if recieve_data['quantity'] > (showtime.total_seats - showtime.booked_seats): return Response("Error: No seats available", status=status.HTTP_409_CONFLICT) recieve_data['total_amount'] = showtime.total_price * \ recieve_data['quantity'] showtime.booked_seats += recieve_data['quantity'] showtime.save() serializer = BookingSerializer(data=recieve_data) if serializer.is_valid(): booking_obj = serializer.save() return Response(booking_obj.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class ShowMovieSerializer(serializers.ModelSerializer): cinema = CinemaSerializer() movie = MovieSerializer() class Meta: model = ShowTime fields = ('id', 'show_start_time', 'show_end_time', 'total_seats', 'booked_seats', 'cinema', 'movie') class BookingSerializer(serializers.ModelSerializer): show = ShowMovieSerializer() details = PersonalDetailsSerializer() class Meta: model = Booking fields = ('id', 'total_amount', 'quantity', 'details', 'show') my post data: { "details": 1, "quantity":1, "show":1 … -
No Procfile and no package.json file found in Current Directory - See run-foreman.js
I am trying to deploy a django app to heroku, and it is causing me errors. In the process of debugging when I run the command heroku local web -f Procfile.windows it shows me the following error: [FAIL] No Procfile and no package.json file found in Current Directory - See run-foreman.js --help From the application structure that is attached you can see that there is the Proc file and the content of the Procfile is as following: web: gunicorn klaviyo_integration.wsgi --log-file - Any guesses what might be wrong? And I am using Windows as OS, in case there is a problem with gunicorn on that sense. -
ModuleNotFoundError: No module named 'settings'
I had django project that was working just fine but I take all the apps and I copied them and pasted them in a new project so I got this. At first it was showing No module named 'backend' but I made few changes and now it shows this. The problem is the error message doesn't show where I mentioned a module named settings. So, how to know where is this mudle in my files? Traceback (most recent call last): File "/Users/apple/Desktop/vytrac-24106/backend/manage.py", line 21, in <module> main() File "/Users/apple/Desktop/vytrac-24106/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/core/management/base.py", line 367, in run_from_argv connections.close_all() File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/db/utils.py", line 208, in close_all for alias in self: File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/connection.py", line 73, in __iter__ return iter(self.settings) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/connection.py", line 45, in settings self._settings = self.configure_settings(self._settings) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/db/utils.py", line 144, in configure_settings databases = super().configure_settings(databases) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/utils/connection.py", line 50, in configure_settings settings = getattr(django_settings, self.settings_name) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/apple/.pyenv/versions/3.9.0/lib/python3.9/importlib/__init__.py", line …