Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, combine two querysets and sort them by a common m2m field
I have two models: class Course(models.Model): course_type = models.ForeignKey(CourseType, related_name='course_type_courses', on_delete=models.PROTECT) name = models.CharField(max_length=255) course_category = models.ForeignKey(CourseCategory, related_name='category_courses', on_delete=models.PROTECT) course_format = models.ForeignKey(CourseFormat, related_name='format_courses', on_delete=models.PROTECT) school = models.ForeignKey(School, related_name='school_courses', blank=True, null=True, on_delete=models.PROTECT) room = models.IntegerField(blank=True, null=True) active_status = models.IntegerField(default=1, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) schedule = models.ManyToManyField(Schedule) sessions = models.IntegerField(default=0) progress = models.CharField(max_length=100, default="P1W1") start_date = models.DateField(blank=True, null=True) class Demo(models.Model): course_category = models.ForeignKey(CourseCategory, related_name='category_demos', on_delete=models.PROTECT) date = models.DateField(blank=True, null=True) schedule = models.ManyToManyField(Schedule) weekly = models.BooleanField(default=False) pm = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='pm_demos', on_delete=models.PROTECT) cf = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='cf_demos', on_delete=models.PROTECT) active_status = models.BooleanField(default=1) demo = models.BooleanField(default=1) Both share a common m2m relationship to a 'Schedule' model: class Schedule(models.Model): day = models.ForeignKey(Weekdays, on_delete=models.PROTECT) start_time = models.TimeField() end_time = models.TimeField() I have one more table linking users to courses class UserCourse(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_courses', on_delete=models.PROTECT) course = models.ForeignKey(Course, related_name='course_user_courses', on_delete=models.PROTECT) I want to retrieve all the courses associated with one user: def courses(self): from holos_apps.holos.models import Course all_user_courses = self.user_courses.all().values_list('course', flat=True) return Course.objects.filter(id__in=all_user_courses).distinct().order_by('schedule__day', 'schedule__start_time') def active_courses(self): return self.courses().exclude(active_status=0) and all the demos associated with one user def demos(self): if self.user_type.name == 'PM': return self.pm_demos.all().distinct().order_by('schedule__day', 'schedule__start_time') return self.cf_demos.all().distinct().order_by('schedule__day', 'schedule__start_time') and I want to combine them but keep them ordered by that schedule day and schedule start … -
Django:How to load new recent comments in Django template without refreshing a page?
Actually, i am working with the comments section in Django. comments model in models.py from django.db import models from django.contrib.auth.models import User class comment(models.Model): message=models.CharField(max_length=300) time=models.DateTimeField(auto_now_add=True) user=models.ForeignKey(User,related_name="my_comment",on_delete=models.CASCADE) post=models.ForeignKey(posti,on_delete=models.CASCADE,related_name="post_comment") #posti is a post model class Meta: ordering=['time'] def __str__(self): return self.message simple view in views.py to create a new comment. @csrf_exempt def add_comment(request,pk): if request.method == "POST": obj=posti.objects.get(pk=pk) value=request.POST.get("message") new=comment(message=value,user=request.user,post=obj) new.save() return HttpResponse(new) HTML file to load posts as well as comments. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> </head> <body> <div> <p>{{post_data}}</p> </div> <br> <div id="add"> {% for i in comments%} <div><p>{{i.message}}</p><br><span>{{i.time}}{{i.user}}</span></div> {% endfor %} </div> <div> <form id="my_form" action="{% url 'a' pk=id %}" method="POST"> {% csrf_token %} <input name="message" type="text"><br> <button id="click" type="submit">Comment</button> </form> </div> <h1></h1> <script> $(document).ready(function(){ $("#my_form").submit(function(){ $.ajax({ url:$(this).attr("action"), type:$(this).attr("method"), data:$(this).serialize(), success:function(data){ //$("h1").text(data['time']); console.log(data); } }); return false; }); }); </script> </body> </html> Here I'm using ajax so that users can post new comments on a post without refreshing a page. New comments in the database are storing without refreshing a page but how I can load new comments in this HTML file without a refreshing page. If you have any idea please tell me. -
Type error when trying to (apply py -m pip install Pillow?)
I am using Pycharm on windows 7 32bit, i am learning to make a website using django. i am trying to make imagefield, so i tried to install Pillow in the command window and it give me this error: (venv) C:\Users\مرحبا\PycharmProjects\TryDjango>py -m pip install Pillow Collecting Pillow Exception: Traceback (most recent call last): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\basecommand.py", line 228, in main status = self.run(options, args) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\commands\install.py", line 291, in run resolver.resolve(requirement_set) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\resolve.py", line 257, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\resolve.py", line 210, in _get_abstract_dist_for self.require_hashes File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\operations\prepare.py", line 245, in prepare_linked_requirement req.populate_link(finder, upgrade_allowed, require_hashes) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\req\req_install.py", line 307, in populate_link self.link = finder.find_requirement(self, upgrade) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 484, in find_requirement all_candidates = self.find_all_candidates(req.name) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 442, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 587, in _get_pages page = self._get_page(location) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 705, in _get_page return HTMLPage.get_page(link, session=self.session) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 814, in get_page "Cache-Control": "max-age=600", File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\download.py", line 397, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\sessions.py", line 658, in send r.content File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\models.py", … -
How does a document/file storage website 'full stack' work?
Hi there Stackoverflow, I have dabbled with coding in the past and built very simple apps with python and java. During the lockdown my mind has become more inquisitive and i'm peeling the onion of how websites, back and front end work. I have sporadically been learning about html, java(script), node.js, nginx, apache, mongoDB, amazon aws, then django, ruby on rails etc etc. However, one thing i haven't been able to find in any one location is the component layers of a website that would hosts files that users might interact with, what the best infrastructure of Full Stack for such a website might be and how the role of each of the languages/interfaces works. I would be very grateful if someone could shed some light on the subject, or direct me to the best place to learn about this. Specifically to my case I would like to know how a file hosting website might work, an example being a legal datasite that can grant users different permissions, or DocuSign contract lifecycle management. Many Thanks. -
Sending image from Android Retrofit to Django server
The problem is that I’m probably sitting already a day and racking my brains. It is required to send a regular multipart / form-data request with an image and several lines. Here is the Retrofit interface code: @Multipart @POST("edit/profile/image") Call<ImageAddResponse> change_avatar(@Part MultipartBody.Part image, @PartMap Map<String, RequestBody> requestBodyMap); There is also a backend to Django. Testing everything locally, everything works perfectly, but when I put django on a real server, I get this error when requesting above: Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_responseHow to send an object with data and an image in retrofit to Django server response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ioienv/ioi/api/views.py", line 349, in edit_user_image userid = request.POST.get('userid' , 1) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/wsgi.py", line 102, in _get_post self._load_post_and_files() File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 326, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 286, in parse_file_upload return parser.parse() File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 154, in parse for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 640, in __iter__ for sub_stream in boundarystream: File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 464, in __next__ … -
Modifying app_index (AdminSite)
So I'm in the middle of modifying my Django sites admin pages. I'm currently trying to move all apps/models over to a sidebar that will exist on every admin page. This is going pretty well as you can see here my issue now is that the sidebar changes depending on where you are in the admin panel, and I've come to assume that this is due to the app_label here def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404("The requested admin page does not exist.") # Sort the models alphabetically within each app. app_dict["models"].sort(key=lambda x: x["name"]) app_name = apps.get_app_config(app_label).verbose_name context = { **self.each_context(request), "title": _("%(app)s administration") % {"app": app_name}, "app_list": [app_dict], "app_label": app_label, **(extra_context or {}), } request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ "admin/%s/app_index.html" % app_label, "admin/app_index.html" ], context) as this is the docstring for _build_app_dict Build the app dictionary. The optional label parameter filters models of a specific app. So I followed the docs on customizing the adminsite-class in hopes of being able to overwrite this one function and solve my issues, but sadly when I enable this overwrite no apps at all show up in the sidebar. As seen here: Here … -
Requesting django UpdateView via post method and passing argument
I want to open an UpdateView in Django via post method and I want to pass custom parameter via html input hidden. However, Django tells me that request (from request.POST['parameter']) is not defined. How could I access the post data? I have read a lot how the CBV manages all methods and processes them in some way before it gets translated for the callable the URL conf needs, but I do not understand everything of that. -
Unable to pass the values to django through ajax
I have a html file with many select tag coming from the view.py , I want to calculate the score each time the user click on the drop-down, for that i need to pass the value of the drop-down to view.py through ajax. Below are my html & ajax code html <form method="post" id="test"> {% csrf_token %} {% for x in data %} <select class="form-control" id="{{ x }}" name="{{ x }}" required> <option>Yes</option> <option>No</option> </select> {% endfor %} </form> ajax $(document).ready(function(){ $("#test select").change(function(){ $.ajax({ url: "/quality/auto_audit_score_calculation", type: "GET", dataType: "json", data:{ $("#text select").each(function(e){ var result =$(this).val() var parameter = $(this).attr("id") parameter : result, }); } success: function(data) { $("#score_output").text("Success"); } }); }); }); I am unable to pass the value there. request someone to help me out of this problem. -
Django : adaptive form
I want to create an adaptive form with the following models : class MetaInstance(models.Model): name = models.CharField() options = models.ChoiceField(choices = mychoices) class Instance1(models.Model): param1 = models.IntegerField() param2 = models.IntegerField() class Instance2(models.Model): param4 = models.IntegerField() param5 = models.IntegerField() In the view : if the user chooses the option 1 of the MetaInstance then he will create the model Instance1 if he chooses the option 2, then he will create the Instance2 How can I do it in Django 3 ? -
Username_field error while migrating to database
I was implementing django's custom user model but during migration it gives me a USERNAME_FILED error.Also the username field is clearly mentioned in the account class.I am extending django's custom user model for creating a blog like website. account/models.py from django.db import models from django.db import models from django.contrib.auth.models import BaseUserManager,AbstractBaseUser class MyAccountManager(BaseUserManager): def create_user(self, email, username, password = None): if not email: raise ValueError('Users must have an email') if not username: raise ValueError('Users must have a username') user = self.model(email=self.normalize_email(email),username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user(email=self.normalize_email(email),password=password,username=username) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60,unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # firstname = models.CharField(max_length=30) USERNAME_FILED = 'email' REQUIRED_FIELDS = ['username',]#firstname objects = MyAccountManager() def __str__(self): return self.email def has_perm(self,perm, obj=None): return self.is_admin def has_module_perms(self,app_label): return True AttributeError: type object 'Account' has no attribute 'USERNAME_FIELD' -
Filtering Fields with Custom User Model -- Django
Very new to Django. I created a custom user model as below. I also created a page for the users to update their details. I want the two user 'groups' to use the same page 'account.html' to update their details. But if the user is an 'Employee' I want to display additional fields. Simply put, I'm trying to achieve the following logic: If users group = 'Client' then display fields A & B to update If users group = 'Employee' then display fields A, B, C & D update Any help much appreciated Models.py group_types = [('Client', 'Client'), ('Employee','Employee')] class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) groups = models.CharField(choices=group_types, default="client", max_length=60) company_name = models.CharField(verbose_name='company name', max_length=30) account.html <form class="form-signin" method="post">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Account Details</h1> <p> Email Address </p> <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus value={{account_form.initial.email}}> <br> <p> Username </p> <input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username" required autofocus value={{account_form.initial.username}}> <br> <p> Company Name </p> <input type="text" name="company_name" id="inputCompany_Name" class="form-control" placeholder="Company Name" required autofocus value={{account_form.initial.company_name}}> -
Email not being sent using Django send_mail()
settings.py: EMAIL_HOST = 'smtp.mail.yahoo.com' SMTP_PORT = 456 EMAIL_HOST_USER = 'my_email@yahoo.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_USE_SSL = True the method: def contact(*args,**kwargs): contactform = ContactForm(request.POST, prefix='contactform') send_mail( 'Contact from website by '+contactform.name, contactform.message, settings.EMAIL_HOST_USER, ['saxoya8501@emailhost99.com'], fail_silently=False, ) It does not send any email. In the logs I get: "GET /?contactform-name=myname&contactform-email=aaaa%40gnm.com&contactform-message=aaaaaaaaaaaaaa HTTP/1.1" 200 20808 The form that I am using is this: class ContactForm(forms.Form): prefix = 'contactform' name = forms.CharField(max_length=50) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea(attrs={'class':'materialize-textarea'})) Any suggestions on how to get it to work? -
Creation WYSIWYG and upload images
I'm developing an application in Django, so I'm trying to develop a minimal wysiwyg. One of the main task of this editor is to upload images, so I was wondering how can I upload some images to the server? <form class="formTrepeat" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form.as_p}} <div class="toolbar"> <input type="button" name="" value="Bold" onclick="document.execCommand('bold', false, '');"> <input type="button" name="" value="Italic" onclick="document.execCommand('italic', false, '');"> <input class="tool-items fa fa-file-image-o uploaderImages" type="file" accept="image/*" id="file" style="display: none;" onchange="getImage()"> <label for="file" class="tool-items fa fa-file-image-o"></label> <input type="button" name="" value="Undo" onclick="document.execCommand('undo',false,'')"> <input type="button" name="" value="Redo" onclick="document.execCommand('redo', false, '');"> </div> <div class="center"> <div class="editorPostClass" contenteditable> </div> </div> <input type="button" name="" value="Invia" onclick="copyContent()"> <input type="submit" class="btn btn-lg btn-block" style="background: #FCC844 !important;" name="Create" value='{% trans "Create Post" %}'> </form> Now I'm testing it so I added a button that copy the text to a textarea, so when I add an image, the code is blob:....., how can I upload it? js code: var editorContent = document.querySelector(".editorPostClass"); function getImage() { var file = document.querySelector(".uploaderImages").files[0]; var reader = new FileReader(); var tmppath = URL.createObjectURL(event.target.files[0]); var img = new Image() img.src = tmppath img.onload = function() { editorContent.appendChild(img); // revoke the url when it's not needed anymore. //URL.revokeObjectURL(this.src) } img.onerror = function() { … -
ModuleNotFoundError on running makemigrations
here is the code of my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'libraryapp', ] for reference: https://imgur.com/a/cbjmrTx the Error stack: (venv) C:\Users\ZinonYT\PycharmProjects\CRUD\library>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 "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_ line utility.execute() File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\ZinonYT\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'libraryapp' -
Fetch table data from database without a model related to it
Im looking for a way to fetch some data to display to the user.(Run a raw sql query like) select * from "DB-table" where Name like "%blabla%" and Year like "%2020%" My problem is that the "DB-table" lives in my database but its already populated with important data which is not related to some model in my django-app. Its a standalone table with a lot of data. How can i refer to that table from my views.py file? -
Can't add username to logging record using Middleware
I'm trying to log (by default) username and project (which can be decided from request object). I don't want to add context to every log manually. The problem is that I can't make Django to add request or straight username and project to the LogRecord. I tried tens of ways. This is my code: middlewares.py import threading local = threading.local() class LoggingRequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_request(self, request): setattr(local, 'request', request) def process_response(self, request, response): setattr(local, 'request', request) return response settings.py def add_username_to_log(record): record.username = '-' print(record.request) if hasattr(record, 'request') and record.request.user.is_authenticated: record.username = record.request.user.username return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': LOGGING_VERBOSE_FORMAT, 'style': '{', }, }, 'filters': { 'context_filter': { '()': 'django.utils.log.CallbackFilter', 'callback': add_username_to_log, }, }, 'handlers': { 'console': { 'level': DEFAULT_LOG_LEVEL, 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'filters': ['context_filter'], }, 'file_main': { 'level': DEFAULT_LOG_LEVEL, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(LOG_PATH, 'main.log'), 'maxBytes': DEFAULT_LOG_SIZE, 'formatter': 'verbose', 'filters': ['context_filter'], 'backupCount': 0, }, }, 'loggers': { '': { 'handlers': ['file_main'], 'level': DEFAULT_LOG_LEVEL, 'propagate': False, }, }, } But Django raises: AttributeError: 'LogRecord' object has no attribute 'request' And moreover, it raises: Traceback (most recent call last): File … -
Custom User Model Registration In Django Rest Framework
I'm new in django rest framework. I have User model that I created with (models.Model) and now I want to make API for register User in this model and I don't know what should I do in views.py and serializers.py? class Restaurant_User(models.Model): Restaurant_Owner_UserName = models.EmailField(unique=True, default='') # Email Of Restaurant Owner. Restaurant_Owner_Phone = models.IntegerField(unique=True, default='') # Phone Number Of Restaurant Owner. Restaurant_Password = models.CharField(max_length=32, default='') -
is_valid() function returning false based in the traceback from a IntergerField in forms
is_valid() function returning false based in the traceback from a IntergerField in forms. I am probably missing out on something in the is_valid() line of code. Any input is appreciated. template <form action="{% url 'playlist_add' P_id=p.id %}" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Add Song</button> </form> traceback [26/Apr/2020 15:32:59] "GET / HTTP/1.1" 200 9195 coo voo [26/Apr/2020 15:33:23] "POST /playlist/add/6/ HTTP/1.1" 200 4373 forms.py class IdForm(forms.Form): id = forms.IntegerField() Views.py class PlaylistAddFormFunction(View): form_class = IdForm #determine fields template = 'homepage_list.html' def get(self, request): form = self.form_class(None) print('soo') return render(request, self.template, {'form':form}) @method_decorator(login_required) def post(self, request, P_id): print('coo') form = SongForm(request.POST, request.FILES) if form.is_valid(): print('xoo') id = form.cleaned_data['id'] song = Song.objects.get(id=id) playlist, created = Playlist.objects.get_or_create(id=P_id) playlist.song.add(song) return redirect('home') else: form = self.form_class(None) print('voo') return render(request, self.template, {'form':form}) -
Django REST upload multiple files with data
I'm trying to create an endpoint that accepts (key/value) data and multiple files. The user can send serial and multiple files along with his request. Uploaded files must be saved in FileModel and add a relation to the RequestModel. The problem is when I send the request the RequestSerializer can't resolve the files and I get an error about missing the files field. #tests.py def test_create_request_with_files(self): with tempfile.NamedTemporaryFile() as file: file.write(b"SomeFakeData") file.seek(0) request = { 'files': [file], 'serial': "SomeSerial", } res = self.client.post( '/CreateRequest/', request, format='multipart') print(res.data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) #--------------------------------------------------------------------------- # models.py class FileModel(models.Model): file = models.FileField(upload_to='upload_files') class RequestModel(models.Model): serial = models.CharField(max_length=100) files = models.ManyToManyField('FileModel', blank=True) def __str__(self): return str(self.id) #--------------------------------------------------------------------------- # serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = '__all__' read_only_fields = ('id',) class RequestSerializer(serializers.ModelSerializer): files = FileSerializer(many=True) def create(self, validated_data): files = validated_data.pop('files') request_model = RequestModel.objects.create(**validated_data) for file in files: file_model = FileModel.objects.create(file=file) request_model.files.add(file_model) request_model.save() return request_model class Meta: model = RequestModel fields = '__all__' read_only_fields = ('id') #--------------------------------------------------------------------------- #views.py class RequestList(generics.ListCreateAPIView): queryset = RequestModel.objects.all() serializer_class = RequestSerializer parser_classes = (FormParser, MultiPartParser) def post(self, request, *args, **kwargs): serializer = RequestSerializer(data=request.data) if serializer.is_valid(): request_model = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The output of test: {'files': … -
How to implement spelling insensitive search in django & ProstgreSQL?
What I wanted to achieve is, if user enters search for "laptp" then database should return results with actual word "Laptop". Similarly if user enters "ambroidery", then database should return results with both "embroidery" and "embroidred" words containing strings. Hope it clears!! So what I tried is, I went through whole django documentation and closest thing I found is "Trigram Similarity" search. I followed documentation and tried this: data = 'silk' data= Product.objects.annotate( similarity=TrigramSimilarity('description', data)).filter(similarity__gt=0.3).order_by('-similarity') In my database, I have Products whose description contains word "silky" but everytime I runs this qury I get empty query set. Even when I put data value "silky", again I got empty query set. So first of all suggest me that whether this is right approach for what I wanted to achieve and secondly if it is, then why it is returning empty query set? -
How to install tensor flow for Django Applications
I am trying to use tensorflow for my django web application. I installed tensor flow in anaconda using the following commands conda create -n tensorflow_env tensorflow conda activate tensorflow_env Now I am trying to impot tensor flow and executing the belwo script in django shell but I am getting an error ModuleNotFoundError: No module named 'tensorflow' I have read similar questions but they talk about the tensorflow environment is different from the conda environment. How do I make sure that the tensorflow imports work in my anaconda environment. I am pretty confused about these environments. Here is my code from django.db.models import Avg,Sum from django.db.models.functions import TruncDate import pandas as pd import tensorflow as tf import matplotlib as mpl import matplotlib.pyplot as plt # Create your views here. from myapp.models import Order orders = Order.objects.all().annotate(date = TruncDate('timestamp')).values('itemName','date').annotate(itemPrice = Avg('itemPrice'),quantity=Sum('quantity'),orderPrice = Sum('orderPrice')) df = pd.DataFrame(list(orders)) -
Passing Trait Value to SubFactory Django
I have two factories. class DispatchDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.DispatchData order = factory.SelfAttribute('order_data.order') sku = factory.LazyAttribute(lambda obj: '%d' % obj.order_data.sku) category = SKUCategory.SINGLE quantity = 50 class Params: combo_sku=False order_data = factory.SubFactory(OrderDataFactory, combo_sku=factory.SelfAttribute('combo_sku')) combo_sku = factory.Trait( sku=factory.LazyAttribute(lambda obj: '%d' % obj.order_data.sku), category=SKUCategory.COMBO, quantity=1 ) class OrderDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.OrderData order = factory.SubFactory(OrderFactory) category = SKUCategory.SINGLE quantity = 75.6 price_per_kg = 10.5 sku = factory.SelfAttribute('crop_data.id') class Params: crop_data = factory.SubFactory(CropFactory) combo_data = factory.SubFactory(ComboSkuFactory) combo_sku = factory.Trait( sku=factory.SelfAttribute('combo_data.id'), category=SKUCategory.COMBO, quantity=1, price_per_kg=34.56 ) so if combo_sku is True then it must on combo_sku in OrderDataFactory. I am getting following error. Cyclic lazy attribute definition for 'combo_sku'; cycle found in ['category', 'combo_sku'] Is there any other way to pass trait value to SubFactory. -
'The view dashboard.views.index didn't return an HttpResponse object. It returned None instead.' when using POST request of specific variable
So I am trying to build a simple view which allows user to change their avatar using form submission. Rendering the view before the POST request works just fine however when a user submits a new image file through form submission I got the following error: Value Error at / The view dashboard.views.index didn't return an HttpResponse object. It returned None instead. The following is a snippet from my view.py @login_required(login_url='/accounts/login/') def index(request): if request.method == 'POST': if 'imagefile' in request.POST: form = forms.AvatarUpdate(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] request.user.avatar = image request.user.save() return redirect('/') else: form = forms.AvatarUpdate() return render(request, 'dashboard/index.html', {"this_page": "home", "form": form}) While the forms.py is as follow: class AvatarUpdate(forms.Form): imagefile = forms.ImageField(widget=forms.FileInput(attrs={'name': "imagefile"}), label="Change user avatar") My intention here is that the model would only be saved only if the POST request contains the variable imagefile. How should I go about fixing the problem? -
Django delete in a transaction
In a Django view, if two requests enter an atomic block that gets a model instance (that exists) and deletes it with transaction.atomic(): MyModel.objects.get( id=1234 ).delete() what happens when they exit the block? Would an exception be raised on one of them? If so, what exception? (i.e. so I can catch it) -
Django Simplejwt: Return existing valid token on relogin
I am using djangorestframework-simplejwt for jwt based authentication in my DRF project. But every time i login a new token is getting generated. How can i make sure when a valid token exists for a user then same is returned on relogin.