Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Object by pk in URL in Django Rest Framework
I want to retrieve objects from the ORM by the "pk" in URL. Here's what I am trying This is my Url: path('api/dispatchhistoryitem/<int:pk>/', views.dispatchhistoryitemsview.as_view(), 'dispatchhistoryitem'), Views.py class dispatchhistoryitemsview(ListAPIView): queryset = ItemBatch.objects.all() serializer_class = holdSerializer def get(self, request, pk, *args, **kwargs): items = get_object_or_404(ItemBatch, id=self.kwargs.get('pk')) serializer = holdSerializer(items) return Response(serializer.data) Serializer.py class holdSerializer(serializers.ModelSerializer): class Meta: model = ItemBatch fields = "__all__" But when I run this it says : ValueError at /api/dispatchhistoryitem/43/ dictionary update sequence element #0 has length 1; 2 is required What is that I am doing wrong here ? Please Help! -
filter data according to dates
I want to filter data according to a given date range picked up in templates by user.I have a list I want that if User enter date and it matches with the date in a list then that data should be shown .But problem in my code is that it doesn't filter actually nothing happens so please help me.And my date is in "%m %dd %yyyy" format.Thank you in advance. javascript $(function() { var oTable = $('#datatable').DataTable({ "oLanguage": { "sSearch": "Filter Data" }, "iDisplayLength": -1, "sPaginationType": "full_numbers", }); $("#datepicker_from").datepicker({ showOn: "button", buttonImageOnly: false, "onSelect": function(date) { minDateFilter = new Date(date).getTime(); oTable.fnDraw(); } }).keyup(function() { minDateFilter = new Date(this.value).getTime(); oTable.fnDraw(); }); $("#datepicker_to").datepicker({ showOn: "button", buttonImageOnly: false, "onSelect": function(date) { maxDateFilter = new Date(date).getTime(); oTable.fnDraw(); } }).keyup(function() { maxDateFilter = new Date(this.value).getTime(); oTable.fnDraw(); }); }); minDateFilter = ""; maxDateFilter = ""; $.fn.dataTableExt.afnFiltering.push( function(oSettings, aData, iDataIndex) { if (typeof aData._date == 'undefined') { aData._date = new Date(aData[2]).getTime(); } if (minDateFilter && !isNaN(minDateFilter)) { if (aData._date < minDateFilter) { return false; } } if (maxDateFilter && !isNaN(maxDateFilter)) { if (aData._date > maxDateFilter) { return false; } } return true; } ); template.html <p id="date_filter"> <span id="date-label-from" class="date-label">From: </span><input class="date_range_filter date" type="date" id="datepicker_from" /> <span … -
How to specify GROUP BY field in Dajngo ORM?
I have the following working SQL statement: SELECT id FROM ops_kpitarget WHERE (site_id = 1 AND validFrom <= "2019-08-28") GROUP BY kpi_id HAVING validFrom = (MAX(validFrom)) But I cannot get this to work inside Django ORM. The best I got was the code below, but then the database is complaining that it is missing a GROUP BY clause to make HAVING work. How can I get the same query with specifying "kpi_id" as the GROUP BY clause using Djangos ORM? Any ideas? KpiTarget.objects .filter(validFrom__lte=fromDate) .values("id", "kpi") .filter(validFrom=Max("validFrom")) ... which translates to: SELECT "ops_kpitarget"."id", "ops_kpitarget"."kpi_id" FROM "ops_kpitarget" WHERE "ops_kpitarget"."validFrom" <= 2019-08-14 HAVING "ops_kpitarget"."validFrom" = (MAX("ops_kpitarget"."validFrom")) I played around with annotate but this is not really giving me what I want... -
How to correct limit values in Django models
Please help to understand how to correct limit for "team" field by "company" team? It's my code : class CustomCompany(models.Model): company_name = models.CharField(max_length=30, default="None", unique=True ) class CustomTeam(models.Model): team_name = models.CharField( max_length=30, default="None" ) company_name = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, related_name='company_name+', to_field='id', ) class CustomUser(AbstractUser): phone = models.CharField(max_length=20, blank=True) company = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, default='None', to_field='company_name', related_name='company' ) team = models.ForeignKey(CustomTeam, on_delete=models.CASCADE, default=1, related_name='team_name+', limit_choices_to={"company_name_id":"company_id"}, ) And problem in last string (limit_choices_to) How to correct do this, limit teams by company? Current error, if it's required the next : invalid literal for int() with base 10: 'company_id' -
How to Retrive previously entered form in django?
I want the user to login and fill the form and when he login again the form must be filled with previously entered data how to make it possible .Thanks in advance I tried accessing with request.user but it didn't work @login_required def surveyform(request): form = SurveyForm(request.POST,request.FILES,instance = request.user) if request.method == "POST": form = SurveyForm(request.POST,request.FILES,instance = request.user) if form.is_valid(): form.save() email = form.cleaned_data.get('email') messages.success(request,f'Thanks for your feedback!') else: form = SurveyForm(instance = request.user) context={ 'form' : form } return render(request,'surveyform/form.html',context) I need the form to be pre occupied with previously entered data if anyone know the solution plzz help me out I am not declaring each html field I used {{ form }} to display the form in html -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 874: '><li><span'. Did you forget to register or load this tag?
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 789 "> < li>< span" Did you forget to register or load this tag? legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for(var i=0;i<datasets.length; i++){%><li><spanstyle="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>' -
How to format json response in django?
I am retrieving data from multiple tables in Django. my current response is : { "status": 0, "message": "Client details retrived successfully...!!!", "results": [ { "id": 11, "client_id": "CL15657917080578748000", "client_name": "Pruthvi Katkar", "client_pan_no": "RGBB004A11", "client_adhar_no": "12312312313", "legal_entity_name": "ABC", "credit_period": "6 months", "client_tin_no": 4564565, "client_email_id": "abc@gmail.com", "head_office_name": "ABC", "office_name": "asd234", "office_email_id": "zxc@gmail.com", "office_contact": "022-27547119", "gst_number": "CGST786876876", "office_country": "India", "office_state": "gujrat", "office_district": "vadodara", "office_taluka": "kachh", "office_city": "vadodara", "office_street": "New rode 21", "office_pincode": 2344445, "contact_person_name": "prasad", "contact_person_designation": "DM", "contact_person_number": "456754655", "contact_person_email": "asd@gmail.com", "contact_person_mobile": "5675545654", "created_at": "2019-08-14T14:08:28.057Z", "created_by": "Prathamseh", "updated_at": "2019-08-14T14:08:28.057Z", "updated_by": "prasad", "is_deleted": false }, { "id": 11, "user_id": "CL15657917080578748000", "bank_details_id": "BL15657917080778611000", "bank_name": "Pruthvi", "branch": "vashi", "ifsc_code": "BOI786988", "account_number": 56756765765765, "account_name": "Pruthvi", "is_deleted": false }, { "id": 10, "document_details_id": "DL15657917080808598000", "user_id": "CL15657917080578748000", "document_type": "Pruthvi ID", "document": "www.sendgrid.com/pan", "is_deleted": false } ] } Expected Response : I am getting the queryset form db in models.py and i am sending it to the views.py and i am iterating over the dict but not getting the expected response. views.py @csrf_exempt def get_client_details(request): try: # Initialising lists for storing results result = [] temp_array = [] # Getting data from request body client_master_dict = json.loads(request.body) # Response from get client data records = ClientDetails.get_client_data(client_master_dict) # Create response … -
using attr in elasticsearch field for indexing
/.models.py lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) @property def type_to_string(self): x1 = Locations.objects.all() return {'lat': self.lat, 'lon': self.lng} ./documents.py loc1 = fields.GeoPointField(attr='type_to_string') fields = [ 'name', 'address', 'provider', ] I want to add loc1 field in fields section so that I can index it and use it in elasticsearch. But when I put loc1 in fields section I get error TypeError: unhashable type: 'GeoPointField' How can I add rectify this error. -
PyInstaller Django compilation <frozen importlib._bootstrap>
I'm trying to compile my django Project With PyInstaller, cuz of be safe in a shared disk driver That every One can review My Code. and when Compile I get this output: (env) D:\__DEV__>pyinstaller Chortke/manage.py --onedir 222 INFO: PyInstaller: 4.0.dev0+46286a1f4 222 INFO: Python: 3.7.4 (conda) 222 INFO: Platform: Windows-10-10.0.16299-SP0 222 INFO: wrote D:\__DEV__\manage.spec 222 INFO: UPX is not available. 239 INFO: Extending PYTHONPATH with paths ['D:\\__DEV__\\Chortke', 'D:\\__DEV__'] 239 INFO: checking Analysis 239 INFO: Building Analysis because Analysis-00.toc is non existent 239 INFO: Initializing module dependency graph... 244 INFO: Caching module graph hooks... 256 INFO: Analyzing base_library.zip ... 6561 INFO: Caching module dependency graph... 6664 INFO: running Analysis Analysis-00.toc 6679 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\users\mab\.conda\envs\env\python.exe 7249 INFO: Analyzing D:\__DEV__\Chortke\manage.py 7307 INFO: Processing pre-find module path hook distutils 7311 INFO: distutils: retargeting to non-venv dir 'c:\\users\\mab\\.conda\\envs\\env\\lib' 8887 INFO: Processing pre-find module path hook site 8887 INFO: site: retargeting to fake-dir 'c:\\users\\mab\\.conda\\envs\\env\\lib\\site-packages\\PyInstaller\\fake-modules' 15264 INFO: Processing module hooks... 15264 INFO: Loading module hook "hook-distutils.py"... 15264 INFO: Loading module hook "hook-django.core.cache.py"... 15439 INFO: Loading module hook "hook-django.core.mail.py"... 15601 INFO: Loading module hook "hook-django.core.management.py"... 15634 INFO: Import to be excluded not found: 'tkinter' 15635 INFO: Import to be excluded … -
New project not finding my reusable app's admin template override which I installed using pip
I had created a django-app which possesses only admin panel, some tables and no front views. Then I created its build with PYPI docs and uploaded it to PYPI. After that I created a new django project and installed my reusable app through pip. The problem is, I override few of admin templates and they were working fine in the project I created this app, but not working when I installed it through pip in the new Project. Note: This is the only app in the new project and the User is a CustomUser. I tried Project not finding my reusable app's admin template override, but nothing happened, then in the new project, I created a templates folder containing admin folder which contains the admin templates (same name files) I override, the folder structure is like: my_new_project/ |_ my_new_project/ |_ __init__.py |_ settings.py |_ urls.py |_ manage.py |_ templates/ |_ admin/ |_login.html and the code of login.html file is: {% extends "myapp: myapp/login.html" %} I got invalid syntax error, then I also tried: {% extends "myapp/admin/login.html" %} still nothing happened. I expected to see the changes I made in the admin templates in my reusable app to reflect in the … -
How to display image in a HTML page the Django Framework?
I have a webpage which will show the logo of an music album and the mark the favorite songs of the album. For that I've added a database field named album_ logo and add the path name of the images folder "C:\Python Projects\Test_App\website\music\static\music\Image" in database. But in the HTML page neither the images are rendering. I've tried loading the static files in the html page and giving the full path. Here is the attached code snippet. <body> {% load static %} <img src = "{{album.album_logo}}"> <h1>{{album.album_title}}</h1> <h3>{{album.artist}} - {{album.genre}}</h3> {% if error_message %} <p>{{error_message}}</p> {% endif %} <form action="{% url 'music:favourite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}" /> <label for="song{{forloop.counter}}"> {{song.song_title}} {% if song.is_favourite %} <img src="{% static 'music/fav.png' %}"> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favourite"> </form> </body> -
Django validate DateTime
I have booking API endpoint and i want to check each time user want booking hall if DateTime and hall that user want booking is available. I try this queryset in validate in Serializer to check if this time and hall is booking or not def validate(self, data): BookingModel.objects.filter(date_time__exact=data['date_time']).get(hall_id__iexact=data['hall']).exists() but it give this Error: BookingModel matching query does not exist. -
What is the difference of form_class and model in django CreateView?
why only "form_class" work but using "model" with "fields" not work error : 'ModelFormOptions' object has no attribute 'private_fields' -
When I send a letter to the mail gives an error 'tuple' object has no attribute 'get'
I do so that after registration to the post office a letter is sent but it gives me an error The letter arrives in the mail, but gives an error and should redirect to another url 'tuple' object has no attribute 'get' my Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\deprecation.py" in call 96. response = self.process_response(request, response) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\middleware\clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /register/ Exception Value: 'tuple' object has no attribute 'get' Settings EMAIL_HOST = 'smtp.mail.ru' EMAIL_PORT = 2525 EMAIL_HOST_USER = "itraptor@mail.ru" EMAIL_HOST_PASSWORD = "labrador75" EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] context = {'form': form, 'username': username, 'password1': password1, 'password2': password2, 'email': email} if form.is_valid(): form.save() return redirect('/loginNow/') , send_mail('Тема', 'Тело письма', settings.EMAIL_HOST_USER, [email]) else: form = RegisterForm() context = {'form': form } return render(request, 'registration/registred.html', context) -
Why is this code failing in a 32-bit enviroment?
I'm moving a very simple django app from my desktop pc to a virtualbox server. I have copied the hole proyect, except for the virtualenv sources folder. Then, i've created a virtualenv and installed dependencies in the same way. When i run manage.py a circular reference error cames in claming The included URLconf 'pmkwebPdf.urls' does not appear to have any patterns in it This is the project dir: PmkwebPdf media pmkwebPdf __init.py settings.py urls.py wsgi.py src migrations ... processor ... __init__.py admin.py apps.py models.py tests.py urls.py views.py templates ... venv ... db.sqlite3 manage.py It's certanly an error with the urlpatterns. So i did this. pmkWebPdf.urls from django.contrib import admin #from django.urls import path, include urlpatterns = [ #path('', include('src.urls')), path('admin/', admin.site.urls), ] In this file, if i remove the path('', include('src.urls')), and its dependecies the error is gone. src/urls.py from django.conf.urls.static import static from django.urls import path from pmkwebPdf import settings #from src.views import index urlpatterns = [ #path('', index, name='index') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) After leaving the pmkWebPdf.urls without the lines commented, i discovered that, in this file, if i leave the urlpatters empty and remove the from src.views import index line. The server runs. I've created the … -
How auto create model in Django?
i has model where i add writes , how at add write auto- create model in other apps with name of this added record? In which I can create entries -
Django forms : how to use Html and css template forms
How can I use (Html+CSS Template forms ) in django ? Hi Guys. I really don't like django forms appearances or even crispy_forms so I downloaded a form Html and Css from this website "colorlib.com" and pasted in my 'signup.html', and 'signup.css' ,form showed up but after filling from and sending it it shows error . I use CBVs .... I'm sure view and url are correct but I think I have to change tags in html to django Tags, Thank you in advance :Btw I use bootstrap , do i need change its href This is form template in django which is very simple and I need more beautiful one : <!-- templates/signup.html --> {% extends 'base.html' %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} Html of form (https://codepen.io/colorlib/pen/aaaoVJ) which i like to use <!-- Author: Colorlib Author URL: https://colorlib.com License: Creative Commons Attribution 3.0 Unported License URL: http://creativecommons.org/licenses/by/3.0/ --> <!DOCTYPE html> <html> <head> <title>Creative Colorlib SignUp Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- Custom Theme files … -
Is there default logging for an errors?
I'm new to Django and programming and failed to write loggers for my application. Is there a way to get all the default errors that come up with out explicitly capturing them with a logger. Maybe this is a basic question and just not true. For instance, I try to run my application and a ValueError comes up like: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.3 Exception Type: ValueError Is there a way for this to log this without having wrapping the logger output around that specific function. -
Django - How to add items to Bootstrap dropdown?
For some background I'm using Django and Bootstrap to build a to-do list as a side project. The issue I'm having is that I can't add items to the dropdown list. I want to have a dropdown to have a list of people's names but when i try to add them to the dropdown they do not appear. this is my view. As you can see I'm passing a list of names as an example. def index(request): form = TodoForm() people = ['person1', 'person2', 'person3'] if request.user.is_authenticated is False: return render(request, 'main/index.html', {'todo_list': [], 'form': form}) user = User.objects.get(pk=request.user.id) todo_list = user.todo_set.all().order_by('id') return render(request, 'main/index.html', {'todo_list': todo_list, 'form': form, 'people': people}) This is dropdown which I got from Bootstrap: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Remind others </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for person in people %} <a class="dropdwon-item" href="#">{{ person }}</a> {% endfor %} </div> </div> When I run this code, I do see the dropdown button but when I clicked, it drops down but it doesn't show any names. It's just a blank dropdown. I know the dropdown list work because when I run the code below it works perfectly. <div class="dropdown"> <button … -
Passing and element form DetailView into CreateView in django
Am Building this voting playform where voters can simply pay for vote cast for a candidate. Am having problem biding a selected candidate to the VoteAmount model I display all the nomination list but i can't get the selected candidate bid into a form in createview to save into database model.py class Award(models.Model): STATUS_PUBLISHED = ( ('Closed', 'Closed'), ('Opened', 'Opened'), ) slug = models.SlugField(max_length=150) name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='award_images') status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') def __str__(self): return self.name class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.CASCADE) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=150) image = models.ImageField(upload_to='nominations_images') def __str__(self): return self.Fullname class VoteAmount(models.Model): Nominee = models.ForeignKey(Nomination, on_delete=models.CASCADE) votes_amount = models.IntegerField(default=0) def __str__(self): return self.votes_amount Views.py class AwardView(ListView): template_name = 'award.html' context_object_name = 'award_list' queryset = Award.objects.filter(status='Opened').order_by('-date') class CategoryView(DetailView): model = Award template_name = 'category.html' class NominationView(DetailView): model = Category template_name = 'nomination.html' class VoteAmountView(DetailView): model = Nomination template_name = 'voteamount.html' class AmountView(CreateView): template_name = 'voteamount.html' form_class = VoteAmountForm class PaymentView(DetailView): model = VoteAmount template_name = 'PaymentView.html' form.py class VoteAmountForm(forms.ModelForm): class Meta: model = VoteAmount fields … -
How to send mail to admin email address for withdrawal in django?
I am working on a project. For each user there is payment and I want to make a withdraw option for user whenever he/she needs a payment, they write the amount they need and click on withdraw button. But I don't know how to send email to admin page to make aware admin that he/she needs money and you should send him/her. How to do it? Especially the one I have commented. -
PYTHON 3.7.4 NOT USING SQLITE 3.29.0
OS/Software installed: root@TACIT admin]# cat /etc/*release* CentOS Linux release 7.6.1810 (Core) root@TACIT admin]# python3.7 --version Python 3.7.4 [root@TACIT admin]# sqlite3 --version 3.29.0 2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88bfa6 (T3PSA) [root@TACIT src]# django-admin --version 2.2 Software locations: [root@TACIT admin]# which python3.7 /usr/local/bin/python3.7 [root@TACIT admin]# which sqlite3 /usr/bin/sqlite3 (T3PSA) [root@TACIT src]# which django-admin /root/.local/share/virtualenvs/T3PSA-6bzDXn0f/bin/django-admin I compiled Python 3.7.4 from source and installed following these instructions without any problems: https://tecadmin.net/install-python-3-7-on-centos/ I upgraded from Sqlite 3.7.17 to Sqlite 3.29.0 following these instructions without any problems (other than I had to install some additional ".so" libraries): https://linuxhint.com/upgrade-to-latest-sqlite3-on-centos7/ Unfortunately Python 3.7.4 is still using the old version of Sqlite3 (3.7.17): [root@TACIT admin]# python3.7 Python 3.7.4 (default, Aug 16 2019, 16:34:12) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.sqlite_version '3.7.17' I'm using Django and need it to run at least v3.8.3 (see the very end of the following output): (T3PSA) [root@TACIT src]# python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/root/.local/share/virtualenvs/T3PSA-6bzDXn0f/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/.local/share/virtualenvs/T3PSA-6bzDXn0f/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/root/.local/share/virtualenvs/T3PSA-6bzDXn0f/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
Allow CustomUser staff member to create new users in Django admin
I'm creating a new CustomUser to extend the current User and add some new fields. My problem is that I want to allow to staff members to add new users without see the create Group in the admin view, but when I tried to give some perms to the staff member this show all the fields (Group and CustomUser) in my admin view. Is there any way to show only the CustomUser field in the staff session? models.py from django.contrib.auth.models import AbstractUser from django.db import models from core.models import University, Campus, School, Career from core.models import Country, Region, City from django.core.validators import RegexValidator from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Los usuarios deben tener un Email') user = self.model( email=self.normalize_email(email), ) user.is_staff2 = False user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) rut = models.CharField(verbose_name="Rut",max_length=8, null=True, blank=True, … -
I need help,How to transfrom object via celery
I want use celery upload image ,but there have some error. Object of type InMemoryUploadedFile is not JSON serializable please help me ,thank you very much. class UserViewSet(CusModelViewSet): queryset = UserProfile.objects.all().order_by('-last_login') serializer_class = UserSerializer pagination_class = PageSet def create(self, request, *args, **kwargs): data = request.data serializer = self.get_serializer(data=data) if serializer.is_valid(): self.perform_create(serializer) image = data self.upload_files.delay(image) return json_response(serializer.data, status.HTTP_200_OK, '创建成功!') return json_response(serializer.errors, status.HTTP_400_BAD_REQUEST, get_error_message(serializer)) EncodeError at /get_data/users/ Object of type InMemoryUploadedFile is not JSON serializable Request Method: POST Request URL: http://127.0.0.1:8000/get_data/users/ Django Version: 2.1.7 Exception Type: EncodeError Exception Value: Object of type InMemoryUploadedFile is not JSON serializable Exception Location: /usr/local/lib/python3.7/dist-packages/simplejson/encoder.py in default, line 273 Python Executable: /media/morgan/project/develop/WebOnline/venv/bin/python Object of type InMemoryUploadedFile is not JSON serializable -
Cannot Import name from myapp.models
I am using django 2.2.4 and python 3.7.3 When I try to import anything from forum.models into gallery/models.py , I get importError: cannot import name 'Project' from 'forum.models', but it works fine the other way around (importing from gallery.models into forum/models.py. ├── db.sqlite3 ├── forum │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ └── views.py ├── gallery │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ └── views.py ├── makerplatform │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py With that said, I tried this in gallery/models.py: import forum.models as m print(m.__dir__()) and its when I run manage.py runserver: ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'models', 'User', 'post_save', 'receiver'] Notice that User,post_save, and receiver are all modules I imported into forum/models.py. I also tried importing forum.models in the django shell, and it works fine. Thanks in advance for any help.