Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pip is not working Within virtual environment (venv)
I install python and set its path too. When I check in CMD pip, It shows me the following... C:\Users\maher>pip --version pip 21.1.2"" But after activation of virtual environment when I want to install any packeg using pip, thew see following error. (data) PS D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection> pip install tablib Traceback (most recent call last): File "c:\users\maher\appdata\local\programs\python\python37-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\maher\appdata\local\programs\python\python37-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\Masters_FIT\4th\Webdatabese\Project\Code\data\Scripts\pip.exe\__main__.py", line 4, in <module> ModuleNotFoundError: No module named 'pip' (data) PS D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection> My Project and environment director. "data" is my environment name "Data_Collection" is the Project name. any help or suggestion will be welcome and thanks in Advance. -
AttributeError: 'NoneType' object has no attribute 'decode' when sending a form through JS
I'm trying to send some data through a form using JavaScript Fetch to a Django view, including an image. I keep getting this error message nine times as if no data was sent to the back end: My view is as follows: if "contributors" in data: try: Project.objects.get(title=data['title']) return JsonResponse({'error': 'Project title already exists!'}, status=406) except Project.DoesNotExist: form = ProjectForm(request.POST, request.FILES) project = Project.objects.create( title=data['title'], description=data['description'], logo=data['logo']) return JsonResponse({"message": "Project successfully created!"}, status=201) and my JavaScript: const projectName = document.getElementById("project_name"); const contributors = document.getElementById("id_contributors"); const description = document.getElementById("id_description"); const logo = document.getElementById("id_logo"); const projectCsrf = document.getElementsByName("csrfmiddlewaretoken")[0]; document.getElementById("submitProjectForm").addEventListener("click", () => { let formData = { title: projectName.value, contributors: contributors.value, description: description.value, logo: logo.files[0], }; submitForm(projectCsrf, formData); }); function submitForm(csrf, fields) { const request = new Request(window.location.origin, { headers: { "X-CSRFToken": csrf.value, "Content-Type": "multipart/form-data", }, }); fetch(request, { method: "POST", body: JSON.stringify(fields), }) .then((response) => response.json()) .then((result) => alert(result.message ? result.message : result.error)) .catch((err) => console.log(err)); } is it maybe due to python's Json.loads method not being able to decode the JavaScript File object? Thanks in advance! -
How Can i save instagram stroies in my media folder using media url?
def save_media(story_id, media_url): try: link = media_url[:media_url.find('?')] extension = link[::-1][:link[::-1].find('.')+1][::-1] if 'video' in media_url: extension = '.mp4' filepath = r'{0}\file path for media to save stories\{1}{2}'.format(os.getcwd(), story_id, extension) if not os.path.exists(filepath): response = requests.get(media_url) if response.status_code==200: with open(r'{}'.format(filepath), 'wb') as file: file.write(response.content) file.close() newpath = filepath.replace(f'{os.getcwd()}\\influnite', '') return newpath except Exception as error: print('Error saving story media!') print(error) return '' media url is fetched from api after running this code i am not getting media data(videos and stories) in media folder someone can please tell what mistake am i doing? -
Retrieving a single object of interest rather than Blog.objects.all() in django rest framework
I am comfortable using Class Based View in Django/DRF rahter than functional views. But I think my database hits is tremendously increased thus resulting my API to become slow. For eg: I have an endpoint which updates or deletes the concern object of which the id is sent in the url. My view looks like this. class UpdateOrderView(UpdateAPIView,DestroyAPIView): permission_classes = [IsAuthenticated] queryset = Order.objects.all() serializer_class = OrderUpdateSerializer def perform_destroy(self, instance): instance.delete() As we can see above, my queryset is all the objects from Order table. If I print the queryset, it gives all the objects from the Order table which makes it slow. How can I get just the particular object here using id? In a functional view, we can do this. def Update_or_delete(request,pk) But, pk is not recognized in the class-based view. 2. My second question is this. Many senior developers are a fan of using APIView in Django Rest Framework instead of using Generic Class Based Views because one can write custom code inside APIView more rather than in CBV. For eg all CRUD APIs can be integrated into a single API under APIView. Is the above statement actually true?? So, should I stop using CBV and move … -
Django-react native : request failed with status code 400
i m trying to POST an image from react-native frontend using android emulator to my api but i m getting this error : Request failed with status code 400 this is my axios request : useEffect(() => { const uploaded = new FormData() uploaded.append('image_file',image) axios.post('http://10.0.2.2:8000/upload/', uploaded) .then(response => console.log(response)); }, []); this is my Views.py : def methodes(self,request,*args,**kwargs): if request.method=='POST': image_file=request.data['image_file'] #title=request.data['title'] Upload.objects.create(image_file=image_file) serializer=ImageSerializer(data=request.FILES['image'], required=False) if serializer.is_valid(): serializer.save() return HttpResponse({'message':'ok'},status=200) return HttpResponse({'message':'error'},status=400) -
How Do I access Object and serializer Value in same Validate function?
I have following model class Search(models.Model): trip_choice = ( ('O', 'One way'), ('R', 'return') ) booking_id = models.IntegerField(db_index=True, unique=True) trip_type = models.CharField(max_length=20, choices=trip_choice) and Booking Moddel is Fk with search class Booking(models.Model) flight_search = models.ForeignKey(Search, on_delete=models.CASCADE) flight_id = models.CharField( max_length=100 ) return_id = models.CharField( max_length=100, blank=True, null=True ) I have following rule if trip type is Return 'R' the return id cannot be sent empty in serializer. class AddBookSerializer(BookSerializer): class Meta(BookSerializer.Meta): fields = ( 'flight_search', 'flight_id', 'return_id', ) def validate_flight_search(self, value): print(value.trip_type) I want to access and check return_id and if it is empty Validation error is to be raised I dont know how I shall proceed as value.trip_type give me R but I cannot compare that with return id. -
How to set a UniqueConstraint in a ManyToMany relationship in Django Models
I have a model (MyModel) which can have multiple User as owners (ManyToMany relationship). Each User can own multiple MyModel instances. The idea is that a user can create a MyModel instance through an API. But I want to set a constraint that the MyModel instance that the users create has to have a unique name within the MyModels that the user owns. It can be non-unique across the database though. I am trying to do so by explicitly defining a MyModelOwner as the through model in a ManyToMany field but I am confused on how should I handle the UniqueConstraint? class MyModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.CharField( max_length=1000, unique=True, ) owner = models.ManyToManyField( User, related_name='+', through='MyModelOwner' ) class MyModelOwner(models.Model): my_model = models.ForeignKey(MyModel, on_delete=models.PROTECT) owner = models.ForeignKey(User, on_delete=models.PROTECT) class Meta: constraints = [ UniqueConstraint( fields=['owner', 'my_model'], name='unique_my_model_owner'), ] -
Django - null value in column "author_id" violates not-null constraint (Image uploading)
I am trying to get my head around how to upload and post an image through my Django form. I have sussed out how to post content, but not Images. At the moment, when I try to upload an image with my Post, the following error is returned: null value in column "author_id" violates not-null constraint Views.py class CreatePostView(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image'] template_name = 'core/post_new.html' success_url = '/' @login_required def post_image(request): form=upl() if request.method == 'POST': form = upl(request.POST, request.FILES) upl.save() return render(request, 'core/post_new.html', {'form': form}) def form_valid(self, form): form.instance.author_id = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['tag_line'] = 'Create new post' return data Models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.png', upload_to='core_media') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.content[:5] 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) Any assistance/direction would be most appreciated. Thank you :) -
Djoser use a different domain in emails
I have a VueJS/Django rest framework application and working on the confirmation email when a user signup. My frontend is on another URL than my backend so I try to configure djoser to put the activation link with the good domain. I finally managed to do it kind of adding DOMAIN and SITE_NAME informations but the result is not as expected because my domain name is surrounded by brackets. In my settings Django I have: DOMAIN = 'localhost:8080', SITE_NAME = 'Frontend', DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': {}, } But the result in the email is: You're receiving this email because you need to finish activation process on ('Frontend',). Please go to the following page to activate account: http://('localhost:8080',)/activate/MzE/an7e2w-73af66245317921904307cc266f4983e Thanks for using our site! The ('Frontend',) team Does anyone have an idea why these brackets pop here? -
Django creating model from existing one
I do a little project connected with CS:GO match history. I play pools of matches (7 in each) and compare them with previous ones. I started doing it with my friend in .xlsx file, but now I want to do it in python with django. I have a model for each match containing some data like map, date, kills, deaths, etc. Now I want to do (I think) another model for each pool which will constain informations like total kills from 7 matches, KD ratio, rounds won and lost, etc and don't have an idea on how can I do it in good way and if it is good idea or not. I was also wondering if there is a way to include 7 match objects in pool object so that I won't be doing recreation of each pool object every time I add new match to the list. Thanks for some ideas, I'am still learning and don't have full understanding what is bettter than other. -
TypeError: save() got an unexpected keyword argument 'force_insert' [closed]
This is my views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'user/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'user/profile.html', context) this error is occouring when I wanted to register my new user please help me. How to solve it? It is really stopping me to make my website. And Another error is while logging in Iam typing correct password but I can't login execpt the superuser every login is not happening this is my login.html: {%extends "blog/base.html"%} {% load crispy_forms_tags%} {%block content%} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{form|crispy}} <div class="form-group"> <button type="submit" class="btn btn-outline-info">Login</button> </div> </fieldset> </form> <div class="border-top pt-3"> <small class="text-muted"> Need … -
Changing name of an app in django project using 'mv' command causes an error
Django: 3.2.3 Python: 3.9.0+ Ubuntu: 20.04 LTS Pycharm: 2021.1.1 I started a django project using Pycharm in a virtual environment. I created an app called 'blog'. Then I changed the name using mv blog blog_app in command line. Then python manage.py runserver gives me the following error and I don't know where I should make change if I want to hold onto the name 'blog_app': Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/apps/config.py", line 244, in create app_module = import_module(app_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/thebjko/PycharmProjects/my_site/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
Django_filter - pass slug from views.py function to filters.py class
I have written a function that filters certain parameters. This function needs the slug, which I get from the url. Inside my views.py function I defined the slug as a variable. I want to pass this to the function in the filters.py. views.py def platform_list(request, slug): category = Category.objects.get(slug=slug) f = PlatformFilter(request.GET, queryset=Platform.objects.filter(category=category)) return render(request, 'core/platform-list.html', { 'category': category, 'filter': f }) filters.py class PlatformFilter(django_filters.FilterSet): def nesseccary_functionalities(slug): # select nesseccary functionalities category = Category.objects.get(slug=slug) categoryNesseccary = list(category.filter_functions.values('functionality')) filter_funcs = list(Functionality.objects.values_list('functionality', flat=True)) for count, x in enumerate(categoryNesseccary): if x['functionality'] in filter_funcs: filter_funcs.remove(x['functionality']) return filter_funcs # return ['a','b'] nesseccary = Functionality.objects.all().exclude(functionality__in=nesseccary_functionalities(<slugNeededHere>)) The nesseccary_functionalities returns an array of values I want to exclude(it works fine). Is there a way to transfer the slug from the platform_list function in views.py to the filters.py so I can use the slug to run the nesseccary_functionalities function? -
How to solve ValueError Assign problem in Django?
I created a system with Django. In this system, user uploads an excel table and I creating a new customer from that excel. But in this excel I have 2 important columns. They are entity and parent. I want to when a user uploads this excel table but If there is an entity or parent that is not registered in my database, I want to create it and then save it. I user get_or_createe for that but I am getting an error: ValueError at /customers/upload Cannot assign "(<ParentCompany: TESTP>, False)": "Customer.parent" must be a "ParentCompany" instance. How can I solve it? views.py def customer_excel_upload(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = CustomerExcelForm(request.POST, request.FILES) if form.is_valid(): new_excel = form.save() new_excel = new_excel.excel df = pd.read_excel('C:/fray/otc/' + new_excel.name, index_col=0, engine='openpyxl') for index, row in df.iterrows(): if row is not None: new_customer = Customer() new_customer.customer_name = index country = Country.objects.get(country_name=row['Country']) new_customer.address = row['Address'] new_customer.customer_number = row['Customer Number'] new_customer.phone_number = row['Phone Number'] new_customer.email_address = row['Email Adress'] new_customer.credit_limit = row['Credit Limit'] new_customer.currency_choice = row['Currency choice'] new_customer.risk_rating = row['Risk rating'] parent = ParentCompany.objects.get_or_create(parent=row['Parent Company'], company=request.user.company) entity = Entities.objects.get_or_create(entities=row['Entity'], company=request.user.company) new_customer.parent = parent new_customer.entity = entity new_customer.country = country … -
In Api URL how to Increment Page NUmber in Django
i amnot getting in Django Pease help me .. In my Api request i have particular page number i amnot able to understand how to increment that page number by dynamically please help in this #URL base_url = 'https://api.kayzen.io/v1/reports/336960/report_results?end_date={}&page=1&per_page=25&sort_direction=desc&start_date={}'.format( today,today) In this URL page is their that number should increment not other number. -
NoReverseMatch at/Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<product_slug>[^/]+)/$']
Hello I am a student currently learning Django. The following error occurs in the project I'm making. We are implementing a function related to product registration, but we can't do anything because of an error. Actually, I don't know much about slug or Django. What should I do to solve it? Great developers, please help me. I have attached the files for our project. Help would be appreciated. I don't know where and how to designate the slug. I've applied all the results from the search, but I'm only looking at the same screen. I would really appreciate it if you could help me. error content : NoReverseMatch at / Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Exception Location: D:\anaconda3\envs\vnv_zn\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\anaconda3\envs\vnv_zn\python.exe Python Version: 3.7.6 Python Path: ['C:\zeronine_project (1)', 'D:\anaconda3\envs\vnv_zn\python37.zip', 'D:\anaconda3\envs\vnv_zn\DLLs', 'D:\anaconda3\envs\vnv_zn\lib', 'D:\anaconda3\envs\vnv_zn', 'D:\anaconda3\envs\vnv_zn\lib\site-packages'] Server time: Tue, 25 May 2021 12:19:01 +0900 model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # member class Member(AbstractUser): username = models.CharField(primary_key=True, … -
Is there a package like django-sphinxdoc for django3.X or how to make it work with django3.X
I need to make docs and i was in need to use django-sphinxdoc and i got this error when i make migrates Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hassanyoussef/.cache/pypoetry/virtualenvs/djangotrainingcart-TmT73HM3-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() ... File "/home/hassanyoussef/.cache/pypoetry/virtualenvs/djangotrainingcart-TmT73HM3-py3.8/lib/python3.8/site-packages/sphinxdoc/decorators.py", line 7, in <module> from django.utils.decorators import available_attrs ImportError: cannot import name 'available_attrs' from 'django.utils.decorators' (/home/hassanyoussef/.cache/pypoetry/virtualenvs/djangotrainingcart-TmT73HM3-py3.8/lib/python3.8/site-packages/django/utils/decorators.py) anyone know how to solve this or similar package? -
How to load django template tags in static javascript file
I've provided such a function which has to add a new row to the form after pressing a button: const addNewRow = () => { const numberOfRows = document.querySelectorAll('.order-form-row').length const orderForm = document.querySelector('.order-form') orderForm.innerHTML += ` <div class="row order-form-row"> <div class="col-md-3"> <select required id="order-form-material" class="form-control"> <option value="" selected disabled>{% trans 'Select an option' %}</option> </select> <label class="form-label" for="order-form-material">{% trans 'Material' %}</label> </div> </div> ` } but it renders this way: -
how to track the position of the user in django
i am planning to build a site, which requires to track the location of the user and a specific address and show the distance between both points , kind of like uber Please any suggestions how i can deal with this issue,i have not started to code yet so.... waiting for your precious guidance. thanks -
Celery worker does not write logs when detached
I have a Django application and I use celery & rabbitmq to execute async tasks. I have configured celery to write logs to file, and when I execute celery -A project_name -b <broker_url> worker -l INFO everything works fine and the logs are printed both in console and into the file. However, when I execute the aforementioned command with -D option, i.e. detach the worker, the file is no longer appended with logs. My logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level': LOGGING_LEVEL, 'class': 'logging.NullHandler', }, 'logfile': { 'level': LOGGING_LEVEL, 'class': 'logging.handlers.RotatingFileHandler', 'filename': log_file_path, 'maxBytes': 5000000, 'backupCount': 2, 'formatter': 'standard', }, 'console': { 'level': LOGGING_LEVEL, 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': "WARNING", }, 'django.db.backends': { 'handlers': ['console'], 'level': "INFO", 'propagate': False, }, 'celery': { 'handlers': ['console', 'logfile'], 'level': LOGGING_LEVEL, }, }} The celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.signals import setup_logging os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_service.settings') app = Celery('my_service') app.config_from_object('django.conf:settings', namespace='CELERY') @setup_logging.connect def config_loggers(*args, **kwags): from logging.config import dictConfig from board_ownership_service import settings dictConfig(settings.LOGGING) # Load task … -
Django Form is Not saving to Database
I have searched the site for a solution, many related questions, but no direct response given. I have 3 apps on my projects, and 2 worked pretty well, except for this app, which is not writing to the database. Yes, the other 2 apps write to the postgres database, and I can view the table, but this return empty rows, and I don't see any problem. I hope someone can help me, see below my Model, Form and View.py. MY View.py from django.shortcuts import render, redirect from .forms import EngForm def EngineerList(request): return render(request, "Engineers/elist.html") def EngineerForm(request): if request.method == "GET": form = EngForm() return render(request, "Engineers/eform.html", {'form':form}) else: form = EngForm(request.POST) if form.is_valid(): form.save() return redirect('/engineer/') #pointing to urls.py paths My Forms.py from django import forms from .models import Engineers class EngForm(forms.ModelForm): class Meta: model = Engineers fields = '__all__' labels = { 'workarea' : 'Zone', 'face' : 'Picture', } def __init__(self, *args, **kwargs): super(EngForm, self).__init__(*args, **kwargs) self.fields['position'].empty_label='Select' self.fields['workarea'].empty_label='Select' self.fields['face'].required = False My Model.py from django.db import models class Engineers(models.Model): position = ( ('NOC', 'NOC'), ('Supervisor', 'Supervisor'), ('Site Manager','Site Manager'), ('Site Engineer', 'Site Engineer'), ) region = ( ('SS','South-South'),('SW','SW'),('SE','SE'), ('NE','NE'),('NW','NW'),('NC','NC'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = … -
Django foreign model from third party API
On our project we have CartItem, where users can store both Package - foreign model, and Ticket Group id - in relation to the entity that should be fetched from third party service API: class CartItem(models.Model): id = models.AutoField(_('id'), primary_key=True) cart = models.ForeignKey(Cart) package = models.ForeignKey(Package, null=True) quantity = models.IntegerField(_('quantity')) ticket_group_id = models.IntegerField(_('ticket_group_id'), null=True) What is the most convenient way to fetch ticket group information, and is there any way to do it on the model level? -
Python Django: Is it possible to convert comma separated values in a column and retrieve each value as query set rows
My data set in the table is like this, lets call table name as plans_tracker (1st screen shot) I am trying to retrieve query set like (2nd screen shot). can some one please help me on this, I could not modify the table structure. I am trying to do this in Django templates -
S3 files can only be opened in read-only mode
I have an image field in django model. before i save the image from the form, i want to resize and crop image and then only to save in s3 bucket. when i was using django-storages, it worked fine. moving to django-s3-storage, gives me the error of S3 files can only be opened in read-only mode. this is the code snippet of my resizing and editing in django form: def save(self): photo = super(ProfileUpdateForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.image) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) fh = default_storage.open(photo.image.name, 'wb') resized_image.save(fh, 'png') fh.close() return photo also, if i remove the mode arg of open (fh = default_storage.open(photo.image.name) ), it does not edit and crop the image and just upload the original. also, i tries: to open a PIL image format, but no luck: fh = default_storage.open(resized_image, 'wb') resized_image.save(fh, 'png') fh.close() finally; i tried to make my s3 bucket publicly accessible and give all permissions. also did not works. I realized that it gotta be django-s3-storages. i would be supper and more then happy to be advised and or any help as i am stacked at … -
How to flatten serialized data with only 1 field in Django Rest Framework
I have the following serializer: class SomeSerializer(serializers.ModelSerializer): some_user = UserSerializer() class Meta: model = UserFollowing fields = ("some_user",) And the model UserFollowing associated to it: class UserFollowing(models.Model): some_user = models.ForeignKey(User, on_delete=models.CASCADE) The serializer returns something like this: [ { "some_user": { "username": "jane", "profile_picture": "/media/picture.jpg" } }, ... ] For consistency and simplicity, I would like to return: [ { "username": "jane", "profile_picture": "/media/picture.jpg" }, ... ] How can I achieve this?