Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why practically the same path written in different forms doesn't works correct?
I am working in one django project. I am trying to show image that is saved in Django models attribute (ImageFielf), and it's path is: ../projectname/appname/static/img/imgname.png Considering that,I write in HTML code that: class="result-item-preview fadeIn animated " style="background-image:url('../../projectname/appname/static/img/1202296.jpg'), url('../static/img/default-movie.png'); But this doesen't works. It only works if it is written in usually form: class="result-item-preview fadeIn animated " style="background-image:url('../static/img/1202296.jpg'), url('../static/img/default-movie.png'); How to solve this problem ? -
Running PlayWright for python running on google cloud app engine
Hello PlayWright has the setup command playwright install that needs to be run before it can be used. How could I setup a install script on GCP,s app engine to run this command before running my Django app? -
django (no such column: id) using AbstractUser
So I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this error "django.db.utils.OperationalError: no such column: social_app_user.id" And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password" I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless. Please help, thanks! Note: the 'id' field in this models.py file was added after i got the error. from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class User(AbstractUser): is_verified = models.BooleanField(default=True) id= models.AutoField(primary_key=True, null=False) REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): f"{self.username} {self.email}" return class main_feed(models.Model): content= models.CharField(unique=True, max_length=255, default='', null=False) poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username') likes = models.IntegerField(default=0, null=False) favorites = models.IntegerField(default=0, null=False) date_posted = models.DateTimeField(auto_now=True) def __str__(self): f"{self.content} {self.likes} {self.poster} {self.date_posted}" return -
sqlite3.IntegrityError: FOREIGN KEY constraint failed
I have an sqlite database in my flask server with three tables as seen below: from database import db class ChordNode(db.Model): __tablename__ = 'chordnode' id = db.Column(db.Integer, primary_key=True) hashed_id = db.Column(db.String) successor = db.Column(db.String) predecessor = db.Column(db.String) is_bootstrap = db.Column(db.Boolean, default=False) storage = db.relationship("KeyValuePair") node_map = db.relationship("NodeRecord", cascade="delete") def __repr__(self): return 'Chord node {}, with successor: {}, predecessor: {}, ' \ 'bootstrap: {}'.format(self.hashed_id, self.successor, self.predecessor, self.is_bootstrap) class KeyValuePair(db.Model): __tablename__ = 'keyvaluepair' id = db.Column(db.Integer, primary_key=True) chordnode_id = db.Column(db.String, db.ForeignKey('chordnode.hashed_id'), nullable=True) hashed_id = db.Column(db.String) value = db.Column(db.String) def __repr__(self): return '<key-value pair: {}:{}, responsible Chord node: {}'.format(self.hashed_id, self.value, self.chordnode_id) class NodeRecord(db.Model): __tablename__ = 'noderecord' id = db.Column(db.Integer, primary_key=True) bootstrap_id = db.Column(db.Integer, db.ForeignKey('chordnode.id'), nullable=False) ip_port = db.Column(db.String) def __repr__(self): return 'Node record {} on boo tstrap node with id {}'.format(self.ip_port, self.bootstrap_id) When i insert into ChordNode class or Noderecord everything works fine but inserting a record into KeyValuePair produces this error: sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) FOREIGN KEY constraint failed However KeyValuePair's foreign key is exactly the same as ChordNode's corresponding. Any ideas about what else could be wrong with this and why this error occurs? -
Authentication credentials were not provided on login with username and password
I have a such misunderstanding with my django I make a login from DJANGO built in view for testing, lofin is successful But from postman or any other place i get an ERROR Authentication credentials were not provided CAN ANYBODY PLEASE EXPLAIN WHAT IS WRONG!!! If i did not provide full explanation, please inform me, and i will add This is settings.py DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "tsundoku", 'rest_framework', 'rest_framework.authtoken', 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] ROOT_URLCONF = "backend.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "backend.wsgi.application" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ … -
Product Images - 'cannot write mode RGBA as JPEG'
I'm trying to get started with Django Oscar and I can't get my images to load properly. Once I upload an image, I get this error - 'cannot write mode RGBA as JPEG'. The error comes from line 11: 6 {% block product %} 7 <article class="product_pod"> 8 {% block product_image %} 9 <div class="image_container"> 10 {% with image=product.primary_image %} 11 {% oscar_thumbnail image.original "x155" upscale=False as thumb %} <!-- this line throwing error --> 12 <a href="{{ product.get_absolute_url }}"> 13 <img src="{{ thumb.url }}" alt="{{ product.get_title }}" class="thumbnail"> 14 </a> 15 {% endwith %} 16 </div> 17 {% endblock %} Would this be because I don't have libjpeg properly installed? I'm running this on Windows and it's still not clear to me if I have installed libjpeg correctly. What exactly to I need to do with that package after downloading if that is my issue? Let me know if I can provide more information that would be helpful. -
pandas dataframe to django database
I need to create an SQL table from a pandas dataframe inside django. this is the code I'm using: from django.db import connection import pandas as pd # .... pf = pd.DataFrame({'name': ['Mike', 'Chris', 'Alex']}) pf.to_sql(name='customers', con=dj, if_exists='replace') But all I'm getting is this error: Traceback (most recent call last): File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1681, in execute cur.execute(*args, **kwargs) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\contextlib.py", line 88, in __exit__ next(self.gen) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\django\db\backends\utils.py", line 113, in debug_sql sql = self.db.ops.last_executed_query(self.cursor, sql, params) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 160, in last_executed_query return sql % params TypeError: not all arguments converted during string formatting The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "F:\Programming\Python\Django\sandbox\django_sandbox\polls\models.py", line 32, in go_big pf.to_sql(name='go_big', con=dj, if_exists='replace') File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\core\generic.py", line 2615, in to_sql method=method, File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 598, in to_sql method=method, File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1827, in to_sql table.create() File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 721, in create if self.exists(): File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 708, in exists return self.pd_sql.has_table(self.name, self.schema) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1838, in has_table return len(self.execute(query, [name]).fetchall()) > 0 File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1693, in execute raise ex from exc pandas.io.sql.DatabaseError: Execution failed … -
Django Model structure to fetch data from a foreign key table using a key from another table
I am new to Django and I could not find a correct answer to fetch my progress. I think it is because my model is wrong and so I am searching wrong thing. I am trying to find all the Progress status for a particular Item. My workaround is that in views.py parse through all the objects in the Progress object and if the item_id matches with the id then add it to the list and send the list to the template. But my progress list is huge like 10000 and scaling and each item has only 4 o 5 progress. so I don't know if its a good idea to parse through all the list of progress each time an item URL is clicked Models.py class Item(models.Model): name = models.CharField(max_length=256) id =models.AutoField(primary_key=True) def __str__(self): return self.name class Progress(models.Model): text=models.CharField(max_length=256) id=models.AutoField(primary_key=True) item_id=models.ForeignKey(Item,on_delete=models.CASCADE) start_date = models.DateField(default=django.utils.timezone.now) def __str__(self): return self.name and views Views.py def item(request,item): pp = Progress.objects.all() ip=get_object_or_404(Item,id=item) print(item) show=[] for each in pp: if each.item.id ==int(item): print(each.item.id) show.append(each) return render(request,'main/item.html',{'show':show,'ip':ip}) Example of Desired Output: localhost/main/item/3 Item: Launch A progress: |- Initiated |- fetched all the metadata |- informed stakeholders |- waiting for approval localhost/main/item/9 Item: Automate Bots progress: |-Bot … -
How can I count the fields of All Objects in a Database Table by date in Django?
How can I count the fields of All Objects in a Database Table by date in Django? For example: I can access the number of all records of my model named "MateryalEkle" with this code below {{materyalIstatistik}}. But I want to reach the count of all fields separately. And I want to do them by date range i.e. weekly, monthly and yearly. for example: how many "TELEFON", how many "SIM KART", how many "SD KART". and I want to filter these count by date range. for example : 01.03.2021 - 07.03.2021 or 01.01.2021 -.01.01.2022 How can I do that? Thanks for your help. models.py class MateryalEkle(models.Model): MATERYALCINSI = [ ('TELEFON', 'TELEFON'), ('SIM KART', 'SIM KART'), ('SD KART', 'SD KART'), ('USB BELLEK', 'USB BELLEK'), ] materyalMarka = models.CharField(max_length=50, verbose_name='MATERYAL MARKA', blank=True, null=True, default="-") cinsi = models.CharField(max_length=50, choices=MATERYALCINSI, verbose_name='MATERYAL CİNSİ', blank=True, null=True, default="-") gelisTarihi = models.DateTimeField(auto_now_add=True) slug = AutoSlugField(populate_from='materyalMarka', unique=True, blank=True, null=True) def __str__(self): return self.materyalMarka views.py def istatistik(request): materyalIstatistik = MateryalEkle.objects.all().count() return render(request, 'delil/istatistikler.html', {'materyalIstatistik':materyalIstatistik}) istatistikler.html `<p>materyal : {{materyalIstatistik}} </p>` -
How can I return dynamic response in my django application?
I have a dynamic Django web application. Which takes CSV files as input, basically a list of URLs. Then with the help of beautiful soup, it returns me a processed CSV file. My code and localhost Django do this job perfectly, but it sometimes takes a huge amount of time to process the data. So when I use it on Heroku or somewhere else, I get request timeouts. But on my localhost, it is not the issue. I guess I have to do something with ajax or return dynamic values to the HTML template so that my request never gets timeout? I want to show the status of processed files where after each iteration of processed files, the value is returned to the browser so that I can know how many items have been processed so far. -
No such file or directory Django in production
Django test went fine in the test environment. When I went for production and typed in my ip address in the browser I get the following error snippet from the browser. FileNotFoundError at / [Errno 2] No such file or directory: 'mainAboutUs.txt' Request Method: GET Request URL: http://139.162.136.239/ Django Version: 3.1.7 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'mainAboutUs.txt' Exception Location: /home/jianwu/HD_website/website/index/views.py, line 50, in importTextFile Python Executable: /home/jianwu/HD_website/env/bin/python Python Version: 3.8.5 Python Path: ['/home/jianwu/HD_website/website', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/jianwu/HD_website/env/lib/python3.8/site-packages'] Server time: Thu, 11 Mar 2021 19:24:51 +0000 I have verified that the mainAboutUs.txt is located in my project folder. The views.py is located in index folder. I am serving my website using apache2. (env) jianwu@django-server:~/HD_website/website$ ll total 188 drwxrwxr-x 7 jianwu www-data 4096 Mar 7 15:48 ./ drwxrwxr-x 6 jianwu jianwu 4096 Mar 7 15:44 ../ -rw-rw-r-- 1 jianwu jianwu 1968 Mar 7 15:24 'aboutUs2900 2.txt' -rw-rw-r-- 1 jianwu jianwu 1968 Mar 7 12:54 aboutUs2900.txt -rw-rw-r-- 1 jianwu jianwu 3008 Mar 7 12:54 aboutUsNytorv.txt -rw-rw-r-- 1 jianwu www-data 131072 Mar 7 12:54 db.sqlite3 -rw-r--r-- 1 jianwu jianwu 168 Mar 7 15:48 emailCred.txt drwxrwxr-x 4 jianwu jianwu 4096 Mar 11 18:42 index/ -rwxrwxr-x 1 jianwu www-data … -
Integrity error in django for null condition
I am new to django and trying to run simple application, currently I am getting data from 3rd party api and I try save that json into my db so below is my Model class. class CollisionDetails(models.Model): crossStreetName = models.CharField(max_length=30) onStreetName = models.CharField(max_length=40, default='') offStreetName = models.CharField(max_length=40, default='') numberOfPersonsInjured = models.IntegerField(default=0) def json_to_class(self, json_data, city): collision_detail = json_data #json.loads(json_data) self.crossStreetName = collision_detail.get('cross_street_name') self.onStreetName = collision_detail.get('on_street_name', 'Unspecified') self.offStreetName = collision_detail.get('off_street_name', 'Unspecified') but when I am trying to save my object it is giving me integrity error saying django.db.utils.IntegrityError: (1048, "Column 'crossStreetName' cannot be null") but I checked my db as well there is no not null condition I have kept, I am not sure why django is treating that as not null = True, is it default behavior? -
How to get RetrieveAPIView path variables in django?
I am writing django application with rest framework for the first time and I've got a problem while getting path variable value of uuid. I need to get User by id, but I suppose my url is avaliable litteraly like this users/<user_id>/ So, I wrote next code: views.py class UserRetrieverView(RetrieveAPIView): permission_classes = (AllowAny,) lookup_field = 'user_id' lookup_url_kwarg = 'user_id' # Retrieving user by id def get(self, request, **kwargs): try: user = User.objects.filter(user_id=self.kwargs.get(self.lookup_url_kwarg)).first() And connected it in urls.py like this url('users/<user_id>', UserRetrieverView.as_view()) And the thing is that when I try to get user by url kinda like this /users/d540c1f8c86f4c5ba755459c366aa97c Server gives 404 NOT FOUND error message GET /api/users/d540c1f8c86f4c5ba755459c366aa97c HTTP/1.1" 404 2554 But if I try to make my request litteraly like users/<user_id>/ there is no 404 error, so I think it tries to set available path just like it is set in urls I have searched many times to solve this, but nothing works. I would appreciate if you could help me. -
Redirect User to external site and get response
I‘ve wrote this Python package to make requests to the non-publicly Audible API. To use this package, the user has to authorize himself to Amazon. Now I’m writing a Django App to give the user a new experience when using the API. My problem is to implement the authorization part. Best solution where to redirect the user to a special Amazon login site and set some cookies on client-side which then be send to Amazon. During authorization, the user have to solve a Captcha (when init cookies doesn’t set correctly) and a 2FA prompt! After a successfully authorization the user are redirected by Amazon to a Url, which contains the needed access token. How I can get this Url with Django? Questions over Questions but no answers yet. My intention is not to write multiple views to condition race the result (successfull/Captcha/2FA/...)! -
WooCommerce Python API Returning 404 on Valid Routes
My API is instantiated like this: wc_api = API( url = 'https://www.example.com', consumer_key='xxxxxxxxxxx', consumer_secret='xxxxxxxxxxx', wp_api=True, version='wc/v3', timeout=10 ) This is the line I'm making a request: wc_response = wc_api.get(f'{endpoint}?page={page}') And the function it's a part of: def get_all(endpoint:str): records = [] page = 1 while True: wc_response = wc_api.get(f'{endpoint}?page={page}') if wc_response is None or wc_response.status_code >= 400: if wc_response is not None and wc_response.status_code == 401: raise PermissionDenied('WooCommerce API denied access to tags') else: raise Exception('Unexpected error from WooCommerce API', wc_response) data = wc_response.json() if len(data) == 0: break records.extend(data) page += 1 return records The specific endpoint I'm having a problem with is products/attributes, although I suspect other valid routes are also going to return 404. I've tested that route using Postman and it returns the data just fine, it's only 404'ing through the Python API. I have previously made a successful call to products using the Python API and I don't think I've changed my configuration at all. This is the URL I used for that test: https://www.example.com/wp-json/wc/v3/products/attributes?page=1 Any ideas on why this request is 404'ing through the Python API and not Postman? -
Python function that takes a json object returns mongodb query object
I need to take a JSON (conditions to filter data), example data: query = { "and": [ { "field": "model", "operator": ">", "value": "2005" }, { "or": [ { "field": "brand", "operator": "=", "value": "Mercedes" }, { "field": "brand", "operator": "=", "value": "BMW" } ] } ] and write a function that transforms this JSON as a MongoDB query so I can directly filter the data while reading from MongoDb (I will use this data inside of apache beam ReadFromMongoDB function, as filter object) so the output should be like: {'$and': [{'field': 'model', 'operator': '>', 'value': '2005'}, { '$or': [ {'field': 'brand', 'operator': '=', 'value': 'Mercedes'}, {'field': 'brand', 'operator': '=', 'value': 'BMW'} ] }]} ( I have a function that transforms each single object into a MongoDB query so don't worry about that) WHAT I TRIED As I don't know how nested data will come, I used recursion in my function. But it becomes complicated and output is not as I expected. def splitToItems(query, items={}): if 'and' in query: for item in query['and']: if 'and' in item or 'or' in item: splitToItems(item) else: if '$and' not in items: items['$and'] = [item] # print(items) else: items['$and'].append(item) # print(items) if 'or' in … -
Django import-export duplicating rows when importing same file multiple times
I am building a tool that allows users to upload CSV files to update the database using the django-import-export tool. I uploaded my test CSV file with one data row, then uploaded it again and got a duplicated row (with a new primary key but all the other values are the same). The row.import_type value is "updated" but the only thing that is updated is the id. Then I upload the same file a third time and get an error: app.models.Role.MultipleObjectsReturned: get() returned more than one Role -- it returned 2! (I really appreciate the exclamation point in that error message, by the way.) Ideally I would get a skipped row on the second import and third import of the file. I suppose I'd be okay with an error. The file's contents are: Sales Role,System Role,System Plan,id Sales Rep,Account Executive,951M-NA, This is the format users get when they export the csv dataset. Ideally they would export a file, change a few columns (aside from the name which is the import_id_field), and re-upload the data. In app/resources.py: class RoleResourec(resources.ModelResource): name = Field(attribute='name', column_name="Sales Role") default_role = Field(attribute='default_role', column_name="System Role") default_plan = Field(attribute='default_plan', column_name="System Plan") class Meta: models=Role fields= ('id', 'name', 'default_role', … -
I have JSONField use a library to call this object for sql postgres How to use sqlite the same library
I have JSONField use a library to call this object for sql postgres How to use sqlite the same library models.py: from django.contrib.postgres.fields import JSONField class DeclareResult(models.Model): marks = JSONField(blank=True) -
(React and Django) Displaying products on the homepage is working fine, but when I click on any particular product, then the rendering is wrong
this post is a third part of this series - (You can skip these first two parts, however - it can serve as a reference) A large number of problems with React, Django, Django REST and Axios Products on the homepage are not being displayed properly (Django, Django Rest and React) My homepage looks like this - But when I click on any particular product, I get this result - I was consulting this issue with my friend, who has told me, that my React code should be fine and the problem should be somewhere inside the Django. HomeScreen.js - import React, { useState, useEffect } from "react"; import { Row, Col } from "react-bootstrap"; import Product from "../components/Product"; import axios from "axios" function HomeScreen() { const [products, setProducts] = useState([]) useEffect(() => { async function fetchProducts() { const { data } = await axios.get('/api/products/') setProducts(data) } fetchProducts() },[] ) return ( <div> <h1>Latest Products</h1> <Row> {products.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> </div> ); } export default HomeScreen; ProductScreen.js - import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import { Row, Col, Image, ListGroup, Button, … -
Django Rest Framework: How to bulk_create nested objects during de-serialization?
I have three models: class Customer(models.Model): name = models.CharField(max_length=30) class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE) class LineItem(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) name = models.CharField(max_length=30) Here is my test: class CreateOrdersTest(APITestCase): def setUp(self): self.TEST_SIZE = 10 self.factory = APIRequestFactory() self._setup_source() self.data = self._build_data() def _setup_source(self): Customer.objects.create(name='test-customer') def _build_data(self): return [{'customer':'test-customer','lineitems':[{'name':'apples'},{'name':'oranges'}]} for x in range(self.TEST_SIZE)] def test_post_orders(self): request = self.factory.post('/create_orders',self.data) response = create_orders(request) response.render() self.assertEqual(response.status_code,status.HTTP_201_CREATED) so the post object looks like [{'customer': 'test-customer', 'lineitems': [{'name': 'apples'}, {'name': 'oranges'}]}, .... ] here are the serializers: class BulkLineItemSerializer(serializers.ModelSerializer): def create(self,validated_data): lineitems = [LineItem(**validated_data) for item in validated_data] return LineItem.objects.bulk_create(**validated_data) class LineItemSerializer(serializers.ModelSerializer): order = ModelObjectidField() def create(self,validated_data): return LineItem.objects.create(**validated_data) class Meta: model = LineItem list_serializer_class = BulkLineItemSerializer fields = ['name','order'] class BulkOrderSerializer(serializers.ListSerializer): def create(self,validated_data): orders = [Order(**item) for item in validated_data] return Order.objects.bulk_create(orders) class OrderSerializer(serializers.ModelSerializer): customer = serializers.SlugRelatedField(slug_field='name',queryset=Customer.objects.all()) def create(self,validated_data): return Order.objects.create(**validated_data) class Meta: model = Order fields = ['customer'] list_serializer_class = BulkOrderSerializer then here is that ModelObjectidField I use for the order object. class ModelObjectidField(serializers.Field): def to_representation(self, value): return value.id def to_internal_value(self, data): return data Because I am passing the actual object into the field like <Order(1)>, I just return it directly for the internal_value. And finally here is my view. This is how I match … -
Django - AWS S3 - Moving Files
I am using AWS S3 as my default file storage system. I have a model with a file field like so: class Segmentation(models.Model): file = models.FileField(...) I am running image processing jobs on a second server that dump processsed-images to a different AWS S3 bucket. I want to save the processed-image in my Segmentation table. Currently I am using boto3 to manually download the file to my "local" server (where my django-app lives) and then upload it to the local S3 bucket like so: from django.core.files import File import boto3 def save_file(segmentation, foreign_s3_key): # set foreign bucket foreign_bucket = 'foreign-bucket' # create a temp file: temp_local_file = 'tmp/temp.file' # use boto3 to download foreign file locally: s3_client = boto3.client('s3') s3_client.download_file(foreign_bucket , foreign_s3_key, temp_local_file) # save file to segmentation: segmentation.file = File(open(temp_local_file, 'rb')) segmentation.save() # delete temp file: os.remove(temp_local_file) This works fine but it is resource intensive. I have some jobs that need to process hundreds of images. Is there a way to copy a file from the foreign bucket to my local bucket and set the segmentation.file field to the copied file? -
Django: 'utf-8' codec can't decode byte 0xd1 in position 2: invalid continuation byte
I'm new in Django so I got stuck. I'm having troubles with Django and MySQL connection. Instead of Cyrillic characters I got a bunch of strange symbols, but I'm using utf8_unicode_ci as character and collation in MySQL for database and tables. How can I solve this problem? This is the error I'm getting: This is what I got in MySQL: -
Problem with 'specify' field in jQuery, not returning to the default value
I'm having a problem with the following code. $(document).ready(function(){ $('#list').change(function(){ $('#specify')[$(this).val()=='Other' ? 'show' : 'hide'](); }); }); /// id 'list' is the id of the choice field form and id 'specify' is the id of the field that appears when 'Other' is selected, that is '0' by default. I'm creating an app with Django that has a choice field with some of the popular selections. But I wanted that if the choice 'Other' is selected another field appears. I managed to do it, and it's working but with the following 'bug': if 'Other' is selected, and you type an input and then change again to one of the items in the list, the input is still there. How can I use jQuery in order to write a '0' if it goes from 'Other' to one of the other choices of the list? -
(django.db.utils.OperationalError: near ")": syntax error) while creating custon django user model
So i have been racking my beain for literal hours trying to create a simple user model. I believe Abstractbaseuser creates default id, email, and password columns, and I added a couple more fields. I also added the AUTH_USER_MODEL into settings.py so I'm pretty sure all the set up should be done to at least be able to run the migration. makemigrations works and passes, but migrate gives me that error every time. So I think, I set up the model correctly(hopefully) but there has to be something I'm missing. from django.contrib.auth.models import AbstractBaseUser from django.db import models class User(AbstractBaseUser): username = models.CharField(unique=True, max_length=64, default='') email = models.EmailField(unique=True, max_length=64) is_verified = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): f"{'username'} {'email'}" return -
How to configure sqlite of django project with pythonanywhere
I have deployed my project to pythonanywhere. It is working locally. But with pythonanywhere I am getting no such table exception. I have configured sqllite as in this link Just mentioned to generate the sqlite file using runmigrations. I have changed the settings.py to use os.path.join at that Database section also but still same issue.