Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Checkout isn't working and so the orders aren't showing in the canteen order
My checkout isn't working so the orders aren't showing at the Canteen order So I don't know why the checkout isn't working I redirected to the success page and it's giving me error I need help It is urgent for a project Here is my github https://github.com/abuhviktor/Finalyearproject/tree/main I know the code isn't dynamic but I am trying to be better everyday I didn't paste the code cause it's alot So any part u need I will paste it -
Popup selected items from the form from python Django
I need to show the selected value from one page to another page, which means while I'm going to update my question I need to show the corresponding field to that form. Now I'm selecting the value using a drop-down list instead of that I need to the popup that value. Django form.py class QuestionForm(forms.ModelForm): #this will show dropdown __str__ method course model is shown on html so override it #to_field_name this will fetch corresponding value user_id present in course model and return it courseID=forms.ModelChoiceField(queryset=models.Course.objects.all(), to_field_name="id") This is my views.py def update_question_view(request,pk): question=QModel.Question.objects.get(id=pk) #course=QModel.Question.objects.get(id=question.course_id) questionForm=forms.QuestionForm(instance=question) #CourseForm=forms.CourseForm(instance=course) mydict={'questionForm':questionForm} if request.method=='POST': questionForm=forms.QuestionForm(request.POST,instance=question) if questionForm.is_valid(): question=questionForm.save(commit=False) course=models.Course.objects.get(id=request.POST.get('courseID')) question.course=course question.save() else: print("form is invalid") return HttpResponseRedirect('/admin-view-question') return render(request,'exam/update_question.html',context=mydict) This is my models.py class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() def __str__(self): return self.course_name class Question(models.Model): course=models.ForeignKey(Course,on_delete=models.CASCADE) question=models.CharField(max_length=600) option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) status= models.BooleanField(default=False) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) This is the template: [![form method="POST" autocomplete="off" style="margin:100px;margin-top: 0px;"> {%csrf_token%} <div class="form-group"> <label for="question">Skill Set</label> {% render_field questionForm.courseID|attr:'required:true' class="form-control" %} <br> <label for="question">Question</label> {% render_field questionForm.question|attr:'required:true' class="form-control" placeholder="Example: Which one of the following is not a phase of Prototyping Model?" %} <br> <label for="option1">Option 1</label> {% render_field questionForm.option1|attr:'required:true' class="form-control" placeholder="Example: Quick Design" %} <br> <label for="option2">Option 2</label> {% … -
Using static image for inline css background
I'm attempting to use a static image as an inline background-image declaration within my html. <div class="billboard" style="background-image: url('/static/images/friends.jpg');"> This renders ok in my local env, but not in production. I've seen people indicate that the use if {{STATIC_URL}} could be used, but this doesn't seem to work locally. Might work in prod. Any advice would be great. Thanks! -
Djando, two models inherited from the same parent, one of them has a ForienKey to the other
I created two models inherited from the same parent. In one of them, I am trying to make a ForienKey to the other child. The following error appears TypeError: ForeignKey(<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x7f2cdf0af9d0>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' user_model.py class AppUser(AbstractBaseUser, PermissionsMixin): objects = MyUserManager() username = models.CharField(max_length=128) email = models.EmailField(max_length=64, unique=True) . . class SupervisorUser(AppUser): objects = StudentManager() major = models.CharField(max_length=128) . . class StudentUser(AppUser): objects = StudentManager() GPA = models.DecimalField(max_digits=4,decimal_places=2) supervisor = models.ForeignKey(SupervisorUser, on_delete=models.CASCADE) . . I tried supervisor = models.ForeignKey(AppUser.SupervisorUser, on_delete=models.CASCADE) but the following error appeared AttributeError: type object 'AppUser' has no attribute 'SupervisorUser' -
How can i write a reverse url for a bridge table in django admin?
model.py class Project(models.Model): project_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) winners = models.ManyToManyField('TwitterUser', blank=True, symmetrical=False, related_name='winners') class TwitterUser(models.Model): projects = models.ManyToManyField(Project, blank=True, symmetrical=False, related_name='registered') This url worked for getting users that registered for a project admin.py url = ( reverse("admin:mint_twitteruser_changelist") + "?" + urlencode({"projects__project_id": f"{obj.project_id}"}) ) How do i get url to display the winners in the admin page -
Web Scraping with python I can't print my variable
In my Django project I use BeautifulSoup for web scraping.It works ut I can't print or slice it. When I try it give the error: (I'm doing this on the views.py) "UnicodeEncodeError 'charmap' codec can't encode character '\u200e' in position 59: character maps to <undefined " . How can I print x variable? URL = link user_agent = getRandomUserAgent() headers = {"User-Agent": user_agent} page = requests.get(URL, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') list = soup.find_all("td", class_="a-size-base prodDetAttrValue") for x in list: print(x) -
How to set imagefield in django model with dynamically set sub directories
I need to upload photos to specific directories. I have below model code. @reversion.register() class Student(BaseModel): uuid = models.UUIDField(default=uuid.uuid4, verbose_name=_("Unique Identifier"), unique=True) user = models.OneToOneField(User, on_delete=models.PROTECT, db_index=True, verbose_name=_("User")) photo = models.ImageField(upload_to="student/", null=True, blank=True, verbose_name=_("Photo")) std_status = models.IntegerField(choices=STD_STATUS, default=1, verbose_name=_("Stu Sta")) std_no = models.AutoField(primary_key=True, verbose_name=_("Stu Num")) name = models.CharField(max_length=100, db_index=True, verbose_name=_("Name")) surname = models.CharField(max_length=100, db_index=True, verbose_name=_("Surname")) For the photo line. It uploads photos to student/ directory. But i need to have subdirectories with User name and dates. Like "student/jenifer_argon/2022/07/01" I can set "student/" directory but username and date should be dynamically set. How can i do this? -
Django (proxy and abstract) add extra fields to child of a custom-user class (AbstrsactBaseUser)
I created a custom user class that is inherited from AbstractBaseUser, this class has a chil class. The problem is I can't add new fields to the children's classes because they had (class Meta: proxy = Ture). The following error appears: ?: (models.E017) Proxy model 'StudentUser' contains model fields. user_model.py class AppUser(AbstractBaseUser, PermissionsMixin): objects = MyUserManager() username = models.CharField(max_length=128) email = models.EmailField(max_length=64, unique=True) . . . class StudentUser(AppUser): objects = StudentManager() GPA = models.DecimalField(max_digits=4,decimal_places=2) #This causes the error if proxy=True class Meta: proxy = True def save(self, *args, **kwargs): self.password = make_password(self.password) return super().save(*args, **kwargs) sittings.py AUTH_USER_MODEL = "app.AppUser admin.py admin.site.register(AppUser) admin.site.register(StudentUser) When I remove (proxy = True) from the child and add (abstract = True) to the parent the following error appears: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.AppUser' that has not been installed user_model.py class AppUser(AbstractBaseUser, PermissionsMixin): objects = MyUserManager() class Meta: abstract = True username = models.CharField(max_length=128) email = models.EmailField(max_length=64, unique=True) . . . class StudentUser(AppUser): objects = StudentManager() GPA = models.DecimalField(max_digits=4,decimal_places=2) def save(self, *args, **kwargs): self.password = make_password(self.password) return super().save(*args, **kwargs) -
@xframe_options_exempt not working for Django view/template that displays an iFrame?
I am displaying an iFrame on my template, the contents of which is from a local .html that I have uploaded as a media file. I have X_FRAME_OPTIONS = 'SAMEORIGIN' set in my settings to allow the displaying of the contents, however when I run the --check deploy check, I get this message: WARNINGS: ?: (security.W019) You have 'django.middleware.clickjacking.XFrameOptionsMiddleware' in your MIDDLEWARE, but X_FRAME_OPTIONS is not set to 'DENY'. Unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to 'DENY'. Seems like I should be keeping this set to DENY when I go to production, however by doing that, my iFrame is "unable to connect" to display the content. I've read the documentation here that says you can set exemptions on the view level if you set it to DENY, however it's not working for me. On the view function, I've tried using the decorators @xframe_options_sameorigin and @xframe_options_exempt like: # @xframe_options_sameorigin # Doesn't work # @xframe_options_exempt # Also doesn't work # Setting X_FRAME_OPTIONS = 'SAMEORIGIN' # and use @xframe_options_deny also doesn't work def work_detail(request, pk): work = Work.objects.get(pk=pk) context = { 'work': work } return render(request, 'work_detail.html', … -
Django Form, form is not being submitted
I am pretty new to django and I am having some issues with my form. It is not submitting anything. I don´t have any idea why, no issue appears in the terminal. It displays the form correctly, but when filling it out and submitting, it just redirects me to the same form but blank. I check the database and nothing´s been added. My code below: #views.py def ContractView(request): form=contractsform(request.POST) if form.is_valid(): con =form.save() return redirect("{% url 'contracts' %}", con.id) else: form = contractsform() return render(request, 'contform.html', {'form': form}) #contform.html <div class="card-body"> <form action="" method="POST" class="row g-3"> {% csrf_token %} <label for="{{ form.subject.id_for_label }}">Name:</label> {{form.name}} <div class="col-md-6"> <label for="{{ form.subject.id_for_label }}">Contractor:</label> <div class="input-group input-group-sm mb-3"> {{form.contractor}} <button id="new-vendor" class="btn btn-outline-secondary" type="button">+</button> </div> </div> <div class="col-md-6"> <label for="{{ form.subject.id_for_label }}">Contractee:</label> {{form.contractee}} </div> ... <div class="col-md-6"> <button type="button" onclick="javascript:history.back()">Cancel</button> </div> <div class="col-md-6"> <input type="submit" value="Submit" class="btn btn-primary" style="float: right;"> </div> </form> #forms.py class contractsform(forms.ModelForm): class Meta: model = Contratos fields = '__all__' widgets = { 'name': forms.TextInput(attrs ={'class': 'form-control'}), 'contractee': forms.TextInput(attrs={'class': 'form-control'}), 'contractor': forms.Select(attrs={'class': 'form-control', 'id': 'contractor_view' }),} #urls.py urlpatterns = [ path('contracts/', views.contratostabla, name='contracts'), path('contracts/add/', ContractView, name='new-contract'), ] -
Django Treebeard - showing hierarchy in admin page
I've used Django.treebeard to create a hierarchical system to classify books like so: The 'genres' model is related to another model by a many-to-many relationship, and I need to be able to select the right genres (ie, Fiction>Adult>Science Fiction>Hard Science Fiction) in the admin page for the other model. Checkboxes seem to be the best way to do this, but when I use them in they look like this: So I can't see the different levels of the hierarchy. The best I've been able to come up with is adding the following to the Models: def __str__(self): return '%s%s' % ('--' * self.depth, self.name) Which results in this, which is not much better: What I need is for the checkboxes themselves to move, not just the text, and to have functionality like being able to 'open' and 'shut' the parent categories, select/deselect all children by selecting the parent etc. Is there any way to do this? -
How to keep html form data after submission using django?
I created a form in html that returns data to Django each time it is submitted. However, when the page is reloaded after submission, the data entered in the form is lost. In order to solve this problem, I took inspiration from the documentation and this blog and then I modified my views.py file: def search(request): if request.method == 'POST': search = request.POST['search'] form = MyForm(request.POST) max_pages_to_scrap = 15 final_result = [] for page_num in range(1, max_pages_to_scrap+1): url = "https://www.ask.com/web?q=" + search + "&qo=pagination&page=" + str(page_num) res = requests.get(url) soup = bs(res.text, 'lxml') result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'}) for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text final_result.append((result_title, result_url, result_desc)) context = {'final_result': final_result} form = MyForm() return render(request, 'index.html', context,{'form':form}) I wrote the following code in my models.py file: from django import forms from django.db import models # Create your models here. class MyForm(forms.Form): search = forms.CharField(max_length=500) here is the content of my index.html file: <form method="POST" action="search"> {% csrf_token %} <input type="search" name="search" placeholder="Search here..." value="{{form.search.value}}" autofocus x-webkit-speech/> </form> Despite my modifications, the form data is not kept after submission. -
Use function from another file in Django views.py
I've created a whole function in my Django views.py and it works. It looks like this: SOME IMPORTS def get_campaigns(request): SOME CODE campaign_data = [] for batch in stream: for row in batch.results: data = {} data["campaign_id"] = row.campaign.id data["campaign_name"] = row.campaign.name campaign_data.append(data) return render(request, 'hello/get.html',{ 'data' : data }) But then I learned that having your whole functions on views.py is not a good practice at all. I should move the "big" functions to a different file and then call them on views.py, right? So I tried different options and the only one that worked for me is copying exactly that same code on a different file and then adding to my views.py: def index(request): data = get_campaigns(request), return render(request, 'index.html',{ 'data' : data }) So I'm repeating the same line (return render...) in both files. It works, but looks very ugly and maybe it's slow, buggy or even insecure. Is there a better solution? P.D: As you can guess from my question, I'm a complete beginner and I don't really know what I'm doing, so any pointers to beginner-friendly tutorials related to this are much appreciated. 😅 -
Django: mixing models and modelForms in same row of a table
I'm building a tournament organizing tool and I'm trying to display the scheduled matches in a table where each row represents a match, and the columns are player1, player1score, player2, player2score, player3, player3score, and "Submit Match Result". So the way I would like it is that the player1, player2, and player3 entries in the table are the names of the 3 players in the match (which is already determined previously when the match was scheduled) while I want the 3 score fields to be input fields. This way, the user puts in the three scores of the players and clicks "submit" which should then update the match in the database, changing it from "scheduled" to "finished" and recording the three scores. What I am having an issue with is how to do this mix of data from the Match model and from the MatchForm modelForm. My Match class: class Match(models.Model): status = models.CharField(max_length=256, default='Scheduled') player1 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'player1') player2 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'player2') player3 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'player3') player1score = models.IntegerField(default=0) player2score = models.IntegerField(default=0) player3score = models.IntegerField(default=0) And my MatchForm: class MatchForm(forms.ModelForm): class Meta(): model = Match fields = ('player1score', 'player2score', 'player3score') And … -
Django + Celery logging
There are alot of resources on this topic but none of them worked unfortunately. Here is my django setting for logging: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "format": "[%(asctime)s: %(levelname)s/%(processName)s] [%(name)s] %(message)s" } }, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "default", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "my_custom_handler": { "level": "INFO", "class": "my_custom_handler_class", }, }, "loggers": { "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, "": { "handlers": ["console", "my_custom_handler"], "level": "INFO", "propagate": True, "formatter": "default", }, "celery": { "handlers": ["console", "my_custom_handler"], "level": "INFO", "propagate": True, }, }, } Celery is initialized before base.py is imported/settings are initialized (which may be the culprit) I tried setting CELERYD_HIJACK_ROOT_LOGGER = False, use the after_setup_task_logger signal (I tried printing to see if that signal is dispatched at all but it isn't) and none of them had any effect I tried using setup_logging which kind of worked: def config_loggers(*args, **kwags): my_handler = MyCustomHandler() root_logger = logging.getLogger() root_logger.addHandler(my_handler) root_logger.level = logging.INFO``` and then in: @worker_process_init.connect def init_worker(**kwargs): logger = get_task_logger(__name__) # or Logger.get_logger(__name__), no difference logger.info("My log message") and I say it kind of worked only because when … -
How can I capture a picture from webcam and store it in a ImageField in Django?
I want to take a picture from a webcam and save it in ImageField. I've seen some results related to this question, but I'm not able to understand how they work. For example: How can I capture a picture from webcam and store it in a ImageField or FileField in Django? My HTML form <div class="contentarea"> <div class="Input"> <form method="POST" name="inputForm" enctype='multipart/form-data'> {% csrf_token %} <div id="camera" class="camera"> <video id="video">Video stream not available.</video> <button id="startbutton" type="button">Take photo</button> <input id="webimg" value="" name="src" type="text" style="display: none;"> <canvas id="canvas"> </canvas> </div> <br> <div> <img id="photo" alt="your image"> </div> <br> <button type="submit" class="btn btn-outline-warning" id="submit">Save</button> </form> </div> <img src="{{ path }}" alt="The screen capture will appear in this box."> Javascript (function() { var width = 320; var height = 0; var streaming = false; var video = null; var canvas = null; var photo = null; var startbutton = null; function startup() { video = document.getElementById('video'); canvas = document.getElementById('canvas'); photo = document.getElementById('photo'); startbutton = document.getElementById('startbutton'); navigator.mediaDevices.getUserMedia({video: true, audio: false}) .then(function(stream) { video.srcObject = stream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); video.addEventListener('canplay', function(ev){ if (!streaming) { height = video.videoHeight / (video.videoWidth/width); if (isNaN(height)) { height = width / (4/3); } … -
How can I get my html to display my django model?
I'm trying to get my django model to be shown in the footer of my base.html but I can't get it to show up. I've looked at a few videos and I can't figure out where I'm going wrong. I know that the model works as I've made 4 entries in my database and I can view them on the admin page. The code also doesn't show any errors so I have nothing to go off of there. Here it is: Models.py class SocialMediaPlatform(models.Model): name = models.CharField(max_length=50, blank=True, null=True) font_awesome_class = models.CharField(max_length=50, blank=True, null=True) base_url = models.CharField(max_length=50, blank=True, null=True, default='https://instagram.com/ or https://tiktok.com/@') def __str__(self): return self.base_url Views.py def social_media_base_view(request): context = {} smbase = SocialMediaPlatform.objects.all() context['smbase'] = smbase return render(request, 'index.html', context) Urls.py urlpatterns = [ path('', views.social_media_base_view), ] Admin.py @admin.register(SocialMediaPlatform) class SocialPlatformAdmin(admin.ModelAdmin): list_display = ('name', 'font_awesome_class', 'base_url') base.html {% for smlink in smbase %} <a href="{{ smlink.SocialMediaPlatform.name }}"> <i class="{{ smlink.SocialMediaPlatform.font_awesome_class }}"> </a> {% endfor %} -
How can I see how many child-tasks a pool worker is currently executing?
I'm using Celery in Django and the workers are eating up all of the memory of my Dynos in Heroku. Setting the --max-tasks-per-child seems to be a valid solution but I can't seem to find what the ramifications of setting a low number might be. So, I wanted to know if it's possible to either monitor the amount of child-tasks a worker is currently running or log this data somewhere. -
Unable to setup mysql with Django on Mac
I installed the recent version of MySQL for my mac (macOS 12(ARM, 64-bit), DMG Archive) and created a database called storefront. I'm working in a pipenv virtual environment and install mysqlclient. I've also updated my DATABASES settings to point to my new database in my settings.py file. DB Settings. But whenever I try to run the server I get an error. NameError: name '_mysql' is not defined Also at the top, (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e') I thought by installing the ARM version I wouldn't deal with this error. I wonder if it's pointing to the wrong file within my env despite adding the PATH to my .zshrc info. Is there a special way to point to the correct mysql or am I setting things up incorrectly? Here's my error message " Traceback (most recent call last): File "/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): tried: '/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/a0c08w6/Documents/Scripts/Django/storefront/manage.py", line 22, in <module> main() File "/Users/a0c08w6/Documents/Scripts/Django/storefront/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/django/core/management/__init__.py", line … -
Django Trigram Similarity for list of strings in Postgres
I have a list of names ["May", "Brown", "Chaplin", etc...] containing about 200 names. For each name string I want return a corresponding object from the database using Django TrigramSimilarity. Normally I would do something like this: result = [] for surname in surnames: person = Person.objects.annotate( similarity=TrigramSimilarity("surname", surname) ) .filter(similarity__gt=0.3) .order_by("-similarity").first() if person: result.append(person) but executing 200 queries in a row doesn't seem very optimal. Is there a way to create a single query for this operation? Also what are the ways to optimize this task even more? Here is my Django model: class Person(models.Model): name = models.Charfield(max_length=100) surname = models.Charfield(max_length=100) age = models.IntegerField() etc... -
how can i prevent access to streamlit outside of django?
I have django and Streamlit running independently, but with an Iframe I can access streamlit by placing the ip inside a template, from django. The question is... How can I prevent access to streamlit by placing the ip directly in the browser. so that it is only see through django. Any help would be greatly appreciated -
Why do I get the path error to view the contents of a single email in the below code.?
In the inbox.js file I am trying to listen for a click event for each email single_email_div and send it to the email view in views.py inbox.js function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector("#emails-view").style.display = "block"; document.querySelector("#compose-view").style.display = "none"; // Show the mailbox name document.querySelector("#emails-view").innerHTML = `<h3>${ mailbox.charAt(0).toUpperCase() + mailbox.slice(1) }</h3>`; // Show the emails of that particular mailbox fetch(`/emails/${mailbox}`) .then(response => response.json()) .then(emails => { // Print emails console.log(emails); // ... do something else with emails ... emails.forEach(email => { const single_email_div = document.createElement('div'); single_email_div.innerHTML = `<a href="{%url 'email' email.id %}"> <br> ${email.id} <br> From: ${email.sender} <br> Subject: ${email.subject} <br> TimeStamp: ${email.timestamp} <br> Read: ${email.read} <br><br> </a>` if(`${email.read}` === false) {single_email_div.style.backgroundColor = "white";} else {single_email_div.style.backgroundColor = "grey";} const emails_div = document.querySelector('#emails-view'); emails_div.append(single_email_div); // When a user clicks on an email, the user should be taken to a view where they see the content of that email document.querySelector("single_email_div").addEventListener('click', () => { fetch(`/emails/${id}`) .then(response => response.json()) .then(email => { // show email and hide other views document.querySelector("#emails-view").style.display = "none"; document.querySelector("#compose-view").style.display = "none"; document.querySelector("#email-view").style.display = "block"; // display email const view = document.querySelector("#email-view"); view.innerHTML = `<ul> <li> From: ${email.sender} </li> <li> To: ${email.recipients} </li> <li> Subject: ${email.subject} … -
Django Jinja2 variables in CSS occur red highlights in VSCode
I'm using Visual Studio Code. And I liked it. But when I use jinja in css or javascript, VSC always highlited in red. How can I fix it? It's sometimes annoying. I'm using Better Jinja plugin. -
DRF- how to return field which is not included in model in response
I have view: class SomeView(APIView): def get(self,request): serializer = serializers.SomeViewSerializer return Response({'result_url': ???}) and serializer: class SomeViewSerializer(serializers.Serializer): url = serializers.SerializerMethodField() def get_url(self): res_id = genetare_url(self.id) return res_id in this case url is not part of any model, but I want to return only this (result of get_url) in response, but I couldn't figure out how to write it in view above. any help will be appriciated, thank you -
How to validate the fields by combining lambda and regx?
I want to get a username and password from the user, which should be validated as a function as follows Terms and conditions for input: Password length greater than or equal to 6. Username length greater than or equal to 4. No one is allowed to join with 'test' and 'codecup' usernames. A user whose password consists only of numbers is not allowed to join. def check_registration_rules(**kwargs): li = list() for user,passwd in kwargs.items(): # print(passwd) # print(user) if user == 'test' or user == 'codecup': continue elif len(user) < 4: continue elif str(passwd).isdigit(): continue elif len(passwd) < 6: continue else: li.append(user) return li print(check_registration_rules(username='p', sadegh='He3@lsa')) Now, instead of these nested conditions, I want to use a combination of lambda and regex library