Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i restrict adding a new record?
I want to use a table as options table by id = 1. Is that a good practice? How do i NOT let adding new records via admin panel? Thank you! -
cannot load library 'C:\Program Files\R\R-4.1.in': error 0x7e
I am getting a exception in thread django-main-thread error. when referencing ffi.dlopen('C:\Program Files\R\R-4.1.0\bin'). The error is "cannot load library 'C:\Program Files\R\R-4.1.in': error 0x7e" I don't understand why it changes "bin" to "in". any help would be appreciated. I am new to Django so it could be a super simple problem. Thanks -
AttributeError 'str' object has no attribute 'add'
I am working on a project which has multiple types of users. Such as students, teachers, staff, etc, I use Django AbstractBaseUser to define my own fields. Problem: At the time that I save a user as a student; in addition to email and password, I also want to save some more information about the student user, such as profile info. The same pattern should be applied to other types of users as well. I tested various ways which came appropriate for this problem but none of them work. accounts/models.py objects = UserManager() username = models.CharField(max_length=255, null=True, blank=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) student = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] students/models.py class Student(models.Model): first_name = models.CharField(max_length=200) father_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) ... accounts/form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from django.forms import formsets from django.forms.forms import Form from .models import CustomUser from students.models import Student, InterestTopic class StudentSignUpForm(UserCreationForm): first_name = forms.CharField(max_length=200, required=True) class Meta(UserCreationForm.Meta): model = CustomUser fields = ['email', 'password1', 'password2'] @transaction.atomic def save(self): user = super().save(commit=False) user.student = True user.save() student = Student.objects.create( user=user, ) student.first_name.add(*self.cleaned_data.get('first_name')) return … -
Type Error: expected string or bytes-like object in python
I am facing an error that occurs whenever I try to python manage.py migrate. It says: Apply all migrations: admin, aufgabenzettel, auth, contenttypes, sessions Running migrations: Applying aufgabenzettel.0005_auto_20210526_1527...Traceback (most recent call last): File "C:\Users\adam_\Documents\Coding\My_First\Aufgabenliste\manage.py", line 22, in <module> main() File "C:\Users\adam_\Documents\Coding\My_First\Aufgabenliste\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field self._remake_table(model, create_field=field) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table self.effective_default(create_field) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 303, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 823, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1378, in get_db_prep_value value = self.get_prep_value(value) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1357, in get_prep_value value = … -
Graphene Subscription error (has no attribute 'execute')
I am trying to make subscriptions work in my Django application. I have have followed the tutorial on the apollo client subscriptions part (https://www.apollographql.com/docs/react/data/subscriptions/): For the backend I have used this plugin (https://pypi.org/project/graphene-subscriptions/) and followed the instructions step by step as well, installing Django channels and setting the channel layers adding the query in the schema etc. However, I get an error when I try to 'do' the subscription and I believe it's a more general problem than one caused by the plugin I used. I was hoping one of you might have an idea what I did wrong. This is some of the relevant code: const httpLink = new HttpLink({ uri: "http://localhost:8000/graphql/", // use https for secure endpoint }); // Create a WebSocket link: const wsLink = new WebSocketLink({ uri: "ws://localhost:8000/graphql/", // use wss for a secure endpoint options: { reconnect: true } }); // using the ability to split links, you can send data to each link // depending on what kind of operation is being sent const link = split( // split based on operation type ({ query }) => { const { kind, operation } = getMainDefinition(query); return kind === 'OperationDefinition' && operation === 'subscription'; }, … -
Custom Id in Django Models
In my model I need an ID field that is different from the default ID given by Django. I need my IDs in the following format: [year][ascending number] Example: 2021001,2021002,2021003 The IDs shall not be editable but model entries shall take the year for the ID from a DateTimeField in the model. I am unsure if I use a normal Django ID and also create some kind of additional ID for the model or if I replace the normal Django ID with a Custom ID. -
The boolen field is not editable in django admin error
there is a error like this <class 'shop.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'available', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'shop.Product'. class Product(models.Model): .... availabel=models.BooleanField(default=True) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'slug', 'price','available', 'created', 'updated') list_editable = ('price', 'available') list_filter = ('available', 'created', 'updated') prepopulated_fields = {'slug': ('name',)} -
How to identify if a field's choices have changed in django model?
I have a model like this: class MyModel(models.Model): status_choices = ( ('in_progress', 'In Progress'), ('in_review', 'In Review'), ('active', 'Active'), ) # I want to detect when these choices are changed and trigger a function status = models.CharField(choices=status_choices, max_length=20, blank=True) # other model fields Here the status choices can be changed, and I want to detect if the choices have changed and then trigger a function call. I know there is post_init listener, but how can I compare my cuurent choices with the previous choices when initializing the model? -
How to solve ATTRIBUTE ERROR: 'function' object has no attribute 'get_host'
When ever i run my server i get this error ATTRIBUTE ERROR: 'function' object has no attribute 'get_host' in my context_proccessors.py file please how do I solve this?? Here is my full code __author__ = 'derek' from chat.settings import VALIDATION_IS_OK, API_ADDRESS_PATTERN, JS_CONSOLE_LOGS def add_user_name(request): """ Adds commons template variables tornado url, authorized, username, success constant """ return { # "wss://%s:PORT/" % domain, 'apiUrl': API_ADDRESS_PATTERN % request.get_host().split(':')[0], 'successResponse': VALIDATION_IS_OK, 'username': request.user.username if request.user.is_authenticated() else '', 'userid': request.user.id if request.user.is_authenticated() else 0, 'logs': request.user.userprofile.logs if request.user.is_authenticated() else JS_CONSOLE_LOGS } Thanks in advance -
How to prevent a new line character (\n) of a string from being the part of the string and not doing its job in python?
Looking for help solving an issue. I have stored a public key in .env file, public key is having \n in it and for .env i have used python dcouple but when I am using the environment variable in a function then \n is not doing its job but it is becoming the part of the string. .env KEY=-----BEGIN PUBLIC KEY-----\nAp4k567H7J7\nG2rtJH\nLok1FG3\n-----END PUBLIC KEY-----\n utility.py var = data(KEY=config('KEY')) print(config('KEY')) #it is not giving the desired result its printing below result -----BEGIN PUBLIC KEY-----\nAp4k567H7J7\nG2rtJH\nLok1FG3\n-----END PUBLIC KEY-----\n but i need this string to be like this when used in utility.py -----BEGIN PUBLIC KEY----- Ap4k567H7J7 G2rtJH Lok1FG3 -----END PUBLIC KEY----- -
how to capture the execution time in django error logs?
class Request(APIView): @api_view(["GET"]) def test_api_method(self): db_logger = logging.getLogger("db") try: 1 / 0 except Exception as e: db_logger.exception( e, extra={ "user": self.user.username, "module_name": __package__, "execution_time": __________, }, ) return Response({"data": True}, status=status.HTTP_200_OK) In the "execution_time" section in the logger part, I want to capture the execution/ response time. How to do that? I have tried time(), process_time() etc. But not working fine -
Why djangoRest framework retrieveAPIView not able to filter with email?
I am trying to use retrieveAPIView to look up details based on 'email'. But its throwing error: Not Found: /apii/list/ [27/May/2021 19:53:28] "GET /apii/list/?email=%22xxx.zzz@gmail.com%22 HTTP/1.1" 404 2801 project level urls.py urlpatterns = [ path('admin/', admin.site.urls), path('apii/', include('AUTHENTICATION.urls')), ] app urls.py urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register'), path('login/', loginAPIView.as_view(), name='login'), re_path(r'^list/(?P<email>[\w\-]+)/$', IndividualUserDetails.as_view(), name='list'), ] views.py class IndividualUserDetails(RetrieveAPIView): queryset = NewEmployeeProfile.objects.all() permission_classes = [AllowAny] serializer_class = UserSerializer lookup_field = 'email' The url I am entering in postman is http://127.0.0.1:8000/apii/list/?email="xxx.zzz@gmail.com" I am assuming I am calling the url in a wrong way may be. Please suggest. Thank you -
Tagulous - Getting AutoComplete Fields to work
I have installed Tagulous successfully in to my Django app, and I have created a Tag textfield although, I'm struggling to get the AutoComplete process to work. I have been referencing the Tagulous instructions. I have installed AutoComplete and have included the relevant JS and CSS libraries within my Settings.py. Along with ensuring that "dal" and "dal_select2" is installed under INSTALLED_APPS. When I go to my form, I'm not receiving any errors and the Skills tag field appears. Although, there is no sign of any autocompletion working, the field just currently behaves as a regular tag field without the autocomplete feature. Here's my code so far: Views.py - (I have imported from dal import autocomplete in to this file) class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image', 'skills'] widgets = { 'skills': autocomplete.ModelSelect2(url='skills-autocomplete') } template_name = 'sfsrv/post_new.html' success_url = '/' def form_valid(self, form): form.instance.author = 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 class SkillsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Skills.objects.none() qs = Skills.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs URLs.py (I have imported from sfsrv.views … -
sen_email error define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure()
django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER='myemail' EMAIL_HOST_PASSWORD='mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'myemail' BASE_URL = '127.0.0.1:8000 -
Django: make favorites accessible from home-view. Try to filter for liked posts by user on the frontpage
I know that there are some questions, that are close to what I am asking but still I am struggeling with finding the correct way: In a grid-like-view I am trying to display a heart-icon (filled/not filled) representing if the logged in user has favorited that post or not. My code: views.py def home_view(request): # all posts posts = Post.objects.filter(date_posted__lte=timezone.now(), is_active=True).order_by('-date_posted') is_favorite = False #liked_posts = Post.objects.get(id=request.user.id).liked.all() liked_posts = User.objects.prefetch_related('liked').get(id=request.user.id).liked.all() # https://stackoverflow.com/questions/63547411/django-filter-liked-posts-by-user if liked_posts.exists() : is_favorite = True context = { 'posts':posts, ... 'liked':liked_posts, 'is_favorite':is_favorite, } return render(request, 'blog/home.html', context) @login_required def PostLikeToggle(request): posts = Post.objects.all() user = request.user if request.method == 'POST': post_id = request.POST['post_id'] post = get_object_or_404(posts, id=post_id) user_liked = user in post.liked.all() if user_liked : post.liked.remove(request.user) else: post.liked.add(request.user) return JsonResponse({'liked':user_liked}) models.py class Post(models.Model): liked = models.ManyToManyField(User, related_name='liked') title = models.CharField(max_length=150) date_posted = models.DateTimeField(null=True, blank=True, editable=True, default=timezone.now, verbose_name="Published at") #... class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['-created_at'] def __str__(self): return self.title urls.py urlpatterns = [ path('', home_view, name="home"), #... path('like/', PostLikeToggle, name="like"), ] home.html <button data-item-id="{{ post.id }}" class="addToFavsContainer-{{ post.id }}" value="{{ post.id }}"> <i class="thumb-{{ post.id }} fas fa-thumbs-up"></i> </button> <script> $(".addToFavsContainer-{{ post.id }}").click(function () { var item_id = $(this).data('item-id'); $.ajax({ type: "POST", … -
Python not decoding JSON because "encoding" is an unexpected argument
I have a Django 2.2.23 app, running on Python 3.9.4. I have django-extensions 2.2.9. I have a model that has a django_extensions.db.fields.json.JSONField attribute (which, AFAIK, is just a text field auto-serialized). I mention this because when the JSON is deserialized, the django-extensions library does it like this: def loads(txt): value = json.loads( txt, encoding=settings.DEFAULT_CHARSET ) return value The problem is that the library imported by import json gives me an error when it's called this way: Python 3.9.4 (default, Apr 5 2021, 01:50:46) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import json >>> json.loads("{}", encoding="UTF-8") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 359, in loads return cls(**kw).decode(s) TypeError: __init__() got an unexpected keyword argument 'encoding' >>> The end result is that I am unable to load any of the records that contain a JSONField from the database because the JSONDecoder can't handle being passed an encoding argument. I was under the impression that Python's json library was simplejson. But looking at the source for that, it does handle encoding. But if I look at the json library in "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/init.py" (as specified in the error above), … -
Setting blank = False for email field in django authentication
I am using django built-in authentication and for that authetication system, we are given different fields like username, email, password etc. Username by default is required and also not blank but for email it is not required (i.e, it is null) which makes it blank also. Now for making it required, i added this code; extra_kwags = {'email': {'required': True}} I tried the same with blank; extra_kwags = {'email': {'required': True, 'blank': False}} But it gives error saying blank is not a valid keyword there. So i want to know if there is a way to set blank=False for the email field in django. Though i know a way which is by making the email_verification mandatory and making email the way to autheticate; ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' But i want to know if there is another way as i don't want it to make authentication_method. -
How to bring the values of while loop in the Response in Django Rest Framework?
I am trying to calculate the counts of each day sales/orders made in the last 30 (7 days for now). My view look like this. class DashboardView(ListAPIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): count_1 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk']).count() startdate_1 = datetime.today() - timedelta(days=1) enddate_1 = startdate_1 + timedelta(days=1) startdate_2 = datetime.today() - timedelta(days=2) enddate_2 = startdate_2 + timedelta(days=1) startdate_3 = datetime.today() - timedelta(days=3) enddate_3 = startdate_3 + timedelta(days=1) ...............................#upto 30 days count_8 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate_1, enddate_1]).count() count_9 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate_2, enddate_2]).count() count_10 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate_3, enddate_3]).count() ..................#upto 30 days return Response( {'active_users_now': count_2, 'total_orders_one_day_ago': count_8, 'total_orders_two_days_ago': count_9, 'total_orders_three_days_ago': count_10, #"total_orders_i_days_ago":count_i, }, status=status.HTTP_200_OK) What I want is to use loop instead of writing such long codes for 30 days. Here is what I have tried: This is just a logic not actual code for python i = 1 while (i<=7): startdate[i] = datetime.today() - timedelta(days=i) enddate[i] = startdate[i] + timedelta(days=1) count[i] = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate[i], enddate[i]]).count() i+= i return Response( {i:count[i],}, status=status.HTTP_200_OK ) -
Make image file stored outside django root accessible to Django admin
I need to upload images through django admin to a remote directory. I am able upload the images without issues, the problem is that although the file location is correct, the link in admin to the image does not work (displayed as 1/screenTest.png). I only want this image to be accessible from admin, how do I do this? models.py from django.db import models from .storages import upload_to, media_storage class Newsletter(models.Model): image_1 = models.ImageField(upload_to=upload_to, storage=media_storage, null=False, blank=False) storages.py from django.core.files.storage import FileSystemStorage ef upload_to(instance, filename): return '%s/%s' % (instance.pk, filename) media_storage = FileSystemStorage( location='Users/somedirectory/Documents/dev/mediatest/', base_url='Users/somedirectory/Documents/dev/mediatest/' ) Page not found (404) Request Method: GET Request URL: http://localhost:8000/Users/somedirectory/Documents/dev/mediatest/1/an-image.png Using the URLconf defined in backoffice.urls, Django tried these URL patterns, in this order: etc. `` -
Fetch data from django backend having parts of dynamic URL private
Let's say I am developing a django REST api that is secured via token and basic authentication. The idea is to list juices. So I am having an URL that lists all juices from specific brands. So I got a dynamic URL like: path("juices/<str:brand>/" ...) What I want to do now is to show all juices of the brand coca-cola in my frontend where no authentication is required. So all visitors should see the list of juices from coca-cola. I need to use JS fetch since it has to be asynch. Thus my code is something like: async function get_juices() { let juices = await fetch( `${hostname}/api/v1/juices/coca-cola/ ) result = await juices.json(); return juices; } My backend is a simple ListView that dynamically filters by brand. But my problem now is that the API is private and I can't use my credentials in my frontend for obvious security reasons. Because any user could just read the frontend code and use my credentials to access the juices of other brands too. I was reading now in some posts that it is possible to have a proxy server which only accepts requests from a specific client and reroutes the request with credentials … -
How to make sure that when I click the button in django form it redirects me to another page
I am making a forms page and I would like when I click the "Submit" button it renders the person on another page that I will create. Prenotazioni.html {% extends 'base.html' %} {% block content %} <br><br><br><div class="container" style="max-width: 600px;"> <form method='POST'> {% csrf_token %} {{ form.as_p }} <input type='submit' class="btn btn-warning" value='Submit' /> </form> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% endblock %} forms.py from django import forms from .models import Prenotazioni class PrenotazioniForm(forms.ModelForm ): class Meta: model = Prenotazioni fields = [ 'Nome', 'Codice_di_Sicurezza', 'Telegram', 'Livello_di_conoscenza_della_economia_da_1_a_10', ] ] The more I search online, the more confused I get. Many thanks in advance! -
How to insert my django model to postgres?
Whenever i change my model and after running makemigrations , there should be changes in the database. I faced this problem while i was trying to add an user foreign key to my table. no changes were made to the table. So, I delete my entire table and initial migrations . and again, i run makemigrations and migrate to transfer my model to postgresql Ever since , i deleted my model from postgres, I cannot view my table in database. My migrations Migrations for 'affiliation': affiliation\migrations\0001_initial.py - Create model ProductView - Create model ProductDetails - Create model ProductImages - Create model AffProduct After this i checked on postgresql server , but no table was created? -
Django SearchVector doesn't work with search query containing whitespace
I have a name field on which I am trying to annotate with a SearchVector. It works fine if I don't add a whitespace in search string but returns empty list if I add a whitespace. Same string works just fine with regular filter queryset. >>> r = Resource.objects.filter(name__icontains='LAKSHMI NURSING') >>> r <QuerySet [<Resource: LAKSHMI NURSING HOME>]> >>> Using Search vector without a white-space string >>> r = Resource.objects.annotate( ... search=SearchVector('name', 'type') ... ).filter(search__icontains='LAKSHMI') >>> r <QuerySet [<Resource: LAKSHMI NURSING HOME>]> >>> With White-space: >>> r = Resource.objects.annotate( ... search=SearchVector('name', 'type') ... ).filter(search__icontains='LAKSHMI NURSING') >>> r <QuerySet []> >>> -
SyntaxError with ImageField in Python Shell
I am learning forms on django documentation. I got stuck at ImageField. While doing the example it is reflecting Syntax Error The code is exactly as mentioned by Django in documentation Please advise what is wrong in it from PIL import Image from django import forms from django.core.files.uploadedfile import SimpleUploadedFile class ImageForm(forms.Form): img = forms.ImageField() file_data = {'img': SimpleUploadedFile('test.png', <file data>)} form = ImageForm({}, file_data) Please see the syntax error as represents in the python shell file_data = {'img': SimpleUploadedFile('test.png', <file data>)} File "<console>", line 1 file_data = {'img': SimpleUploadedFile('test.png', <file data>)} ^ SyntaxError: invalid syntax Thank You -
Data validation in Serializer return empty OrderedDict
I am trying to add multiple ManytoMany relationship in a model but when I am trying to add the data it shows OrderedDict() in the validated data in serializer Models.py class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) client_shipping_address = models.CharField(max_length=500, default=0,blank=True, null=True) class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) #try user name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) receiver_clients = models.ManyToManyField(ReceiverClient) warehouses = models.ManyToManyField(Warehouse) Views.py class GroupsCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): d = request.data.copy() print(d) serializer = GroupsSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: print('error') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serilalizer.py class GroupSenderClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" read_only_fields = ('user',) class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = GroupSenderClientSerializer(many=True) receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("sc objects", sc_objects) if len(sc_objects)>0: for i in sc_objects: print("id", i['id']) inst = Client.objects.get(pk=i['id']) sc.append(inst) if len(rc_objects)>0: …