Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
foreach in javascript menutoggle should be active in the icon I clicked in only
I hope you are doing well, I am using django, problem is I have a list of items that contains a menuToggle my code is like this <!--here is code .... --> <div class="container"> {% ifequal request.user.username obj.author.user.username %} <div class="action1"> <div class="icon" onclick="menuToggle1();"> <img src="{% static 'images/ore.svg'%}" class="svg"> </div> <div class="menupost" id="menupost"> <ul> <li><i class="fa fa-refresh" aria-hidden="true" style="margin-right:10px;"></i><a href="{% url ''%}">Update</a></li> <li><i class="fa fa-trash-o" aria-hidden="true" style="margin-right:10px;"></i><a href="{% url ''%}">Delete</a></li> </ul> </div> </div> <h2 id="title" class="title">{{obj.title}}</h2> <!--and so on...--> </div> <script> function menuToggle1(){ document.querySelectorAll('.menupost').forEach(function(element) { element.classList.toggle('active'); }); }; </script> so when I click on one of them , I see all the menu of all items. so I don't want to see all menutoggle when I click on just one of them.I think you understand my question, I hope you guys can help me. -
problem getting filterset data originating from a MultipleChoiceFilter
Let's say I have the following FilterSet: class ReportFilter(django_filters.FilterSet): type = django_filters.MultipleChoiceFilter(field_name="type", lookup_expr='exact') ... and Client submits the following request: www.exmaple.com/reports/?type=1&type=2 I want to be able to get the filterset data from the multiple choice filter as a list, i.e. do something like this: class ReportFilter(django_filters.FilterSet): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) types = self.data["type"] I would expect types to give me a list [1, 2] but instead I am getting a string 2. The strange this is that if I print self.data of the filterset, it displays what I am expecting to see <QueryDict: {'type': ['1', '2']}> Any thoughts about what I am doing wrong here? -
Django Models - How to tell if an entry is being updated vs a new entry being inserted?
For one of my models I am using, there is some conditional logic that occurs, and part of what I need to know is if an entry is being made for the first time, or if it's updating an existing model. My Model is below, I will follow it with an example of what I am needing. Shipment Model class Shipment(models.Model): CARRIER_CHOICES = [ ('GW', 'Greatwide'), ('SM', 'Sample'), ] dateTendered = models.DateField(default=date.today) loadNumber = models.CharField(max_length=50) masterBolNumber = models.CharField(max_length=50) carrier = models.CharField(max_length=100, blank=True, choices=CARRIER_CHOICES, default='GW') destinationCity = models.CharField(max_length=70) destinationState = models.CharField(max_length=50) rateLineHaul = models.DecimalField(max_digits=15, decimal_places=2) rateFSC = models.DecimalField(max_digits=15, decimal_places=2) rateExtras = models.DecimalField(max_digits=15, decimal_places=2, default=0.00) rateTotal = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True, default=0.00) loadDelivered = models.BooleanField(default=False) customCarrierRate = models.BooleanField(default=False) deliveryDate = models.DateField(null=True, blank=True) deliveryTime = models.TimeField(null=True, blank=True) driverName = models.CharField(max_length=70, null=True, blank=True) driverCell = models.CharField(max_length=70, null=True, blank=True) rateTotalCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0) shipmentMargin = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) shipmentMarginPercentage = models.DecimalField(max_digits=15, decimal_places=3, null=True, blank=True) trailer = models.ForeignKey(Trailer, on_delete=models.PROTECT, blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Here are some examples of why I need to differentiate between an update or an insert. Possible Scenarios When Adding a Shipment a. Only required fields are entered. Then the following happens 1a. Calculate rateTotal 1b. … -
Django: Import data from uploaded excel file
I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is where I've managed to arrive by myself: my file is uploaded without problems and I can pass the information from the file to the variable first_row and second row. My problem now is how I can save the information in the database. My views code: VIEWS @login_required def file_upload(request): data = None if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) data_form = DatasetForm(request.POST, request.FILES) raw_file= request.FILES if file_form.is_valid() or data_form.is_valid(): data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") first_row = data.iloc[[0]] second_row = data.iloc[[1]] file_form.instance.user = request.user.profile file_form.instance.filename = raw_file['file_upload'].name file_form.save() return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': data, 'second_row': second_row, 'file_form': file_form, 'message': message, } return render(request, 'upload_file.html', context) These are how my data and models looks: DATA code tot sd name_1 aa 3 1 name_2 bb 7 2 MODEL class File(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) filename = models.CharField(max_length=250) file_upload = models.FileField(upload_to=path) upload_date = models.DateField(default=datetime.now) def __str__(self): return self.user.name + 'file' class Dataset(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE) name_user_A = models.CharField(max_length=250) code_user_A = models.PositiveIntegerField(null=True) total_user_A = models.PositiveIntegerField(null=True) sd_user_A = models.PositiveIntegerField(null=True) … -
Django custom authentication class is not reading AllowAny
Here is the REST authentication class: def get_authorization_header(request): raw_token = request.COOKIES.get('auth_token', ) or None auth = request.META.get('HTTP_AUTHORIZATION', ) if isinstance(auth, str): auth = auth.encode(HTTP_HEADER_ENCODING) return auth class JWTAuthentication(BaseAuthentication): keyword = 'auth_token' def authenticate(self, request): raw_token = request.COOKIES.get('auth_token', ) or None if raw_token is None: return None return self.authenticate_credentials(raw_token) def authenticate_credentials(self, key): try: user_model = get_user_model() payload = jwt.decode(key, settings.SECRET_KEY, algorithms="HS256") user = user_model.objects.get(email=payload['email']) except (jwt.DecodeError, user_model.DoesNotExist): raise exceptions.ParseError('Invalid token') except jwt.ExpiredSignatureError: raise exceptions.ParseError('Token has expired') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted') return (user, payload) def authenticate_header(self, request): return self.keyword And here is the view: class GoogleLogin(APIView): permission_classes = [AllowAny] def post(self, request): data = request.data response = Response() token = data.get('tokenId', None) if not token: raise exceptions.AuthenticationFailed('No credentials provided.') try: token_info = id_token.verify_oauth2_token(token, requests.Request(), google_app_id) email = token_info['email'] user = authenticate(email) if not user: serializer = RegisterSerializer(data={'email': token_info['email'], 'first_name': token_info['given_name'], 'last_name': token_info['family_name']}) serializer.is_valid(raise_exception=True) serializer.save() jwt_token = gen_token(email) response.set_cookie( key='auth_token', value=jwt_token, expires=datetime.datetime.utcnow() + datetime.timedelta(days=30), secure=False, httponly=True, samesite='Lax' ) return response except ValueError: return Response('Invalid TokenId.', status=status.HTTP_400_BAD_REQUEST) I'm trying to implement Google social login where the frontend (ReactJS) sends tokenId to the backend (Django) to verify the token then returns a response with a JWT token stored in the cookies … -
How to get user object in template?
model.py class User(AbstractUser): is_agree = models.CharField(max_length=1, blank=True) is_verify = models.CharField(max_length=1, blank=True) type = models.CharField(max_length=1, blank=True) name = models.CharField(max_length=255, blank=True) address1 = models.CharField(max_length=255, blank=True) address2 = models.CharField(max_length=255, blank=True) bank_account = models.CharField(max_length=255, blank=True) phone_number = models.CharField(max_length=255, blank=True) I want to get users type in template. I tried {{ user.type }}. but was not worked -
Django declare subquery for re-use?
Is there a way to store a subquery in django the same way SQL DELCARE works? I've got multiple calculations using subqueries. I then reference these subqueries in further calculations. Problem is, once these subqueries are referenced, they "run again" and call another huge select query unnecessarily. Is there a way to call the query once then re use? Only stipulation is that this needs to be done in a single query using annotations. -
Why we use axios PUT method when we can use POST method that does the same job
I'm using axios in a REACT / Django project, the question that I didn't find an answer to is, Considering we can update a databate table, by first sending data with POST method from react to django view then django update the database table with .update function using the data in POST method... Then why we use PUT method or DELETE method ? Thank you -
How to disable sorting by multiple columns in Django Admin?
How can I disable sorting by multiple columns in Django Admin? I'd like to simplify sorting to only one column at a time. Currently, if you click on a column header, this column is added to the sorting order. I.e. http://localhost:8000/admin/core/user/?o=-2.5.3.1, where o query parameter determines the sort (see numbers 4, 1, 3 on the attached image) -
Python Django Async Def work with objects
I have this code in my Django Channels Consumer. async def connect(self): from .models import Chat, Menu from client.models import ChannelCommunication, VirtualAgent self.agents = await sync_to_async(VirtualAgent.objects.get, thread_sensitive=True)(pk=1) self.channel = await sync_to_async(ChannelCommunication.objects.get, thread_sensitive=True)(virtual_agent=agents.pk) self.chat = Chat() self.chat.channel = self.channel self.chat.menu_nav = await sync_to_async(Menu.objects.get(id=self.agents.flow_start)) await database_sync_to_async(self.chat.save)() self.menu_nav = self.chat.menu_nav # Join room group await self.channel_layer.group_add( self.general, self.channel_name ) await self.accept() And have error bellow: 2021-11-19 14:28:35,051 ERROR Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 173, in get rel_obj = self.field.get_cached_value(instance) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'flow_start' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in call return await application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 263, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "/usr/local/lib/python3.8/site-packages/channels/auth.py", line 185, in call return await super().__call__(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/middleware.py", line 26, in call return await self.inner(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 150, in call return await application( File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 58, … -
Adapt Django model (with djOngo) to MongoDB document
I have full database with documents like: { "_id": { "$oid": "6191419b42a21c7b38f028ae" }, "like_count": 58142, "slug": "the-elder-scrolls-iv-oblivion", "name": "The Elder Scrolls IV: Oblivion", "description": "The Elder Scrolls IV: Oblivion", "image": { "thumb": "https://cdn.website.com/c/04dcf5be7b651ef57c542bf5634b08c2/400x510/cdn.kanobu.ru/games/e17c468f-cd9e-48d7-bb23-6cbd736fa330.JPG", "origin": "https://cdn.website.com/games/e17c468f-cd9e-48d7-bb23-6cbd736fa330.JPG" }, "release_date": { "string": "20 марта 2006", "date": "2006-03-20", "is_precise": true, "precision_class": "day" }, "created": "2009-03-02T18:48:27", "rating": 8.94065934065934, "genres": [{ "id": 3649, "name": "Экшен", "slug": "action", "position": 10 }, { "id": 3656, "name": "Ролевые", "slug": "rpg", "position": 30 }], "platforms": [{ "id": 1, "name": "PC", "slug": "pc", "position": 0 }, { "id": 59, "name": "Xbox One", "slug": "xbox-one", "position": 2 }, { "id": 4, "name": "PlayStation 3", "slug": "ps-3", "position": 4 }, { "id": 6, "name": "Xbox 360", "slug": "xbox-360", "position": 5 }], "developers": [{ "id": 79, "name": "Bethesda Softworks", "slug": "bethesda-softworks" }], "publishers": [{ "id": 43, "name": "2K Games", "slug": "2k-games" }], "requirements": { "min_os": "Windows XP, Windows 2000, Windows XP 64-разрядная", "min_cpu": "Intel Pentium 4 с тактовой частотой 2 ГГц или аналогичный ", "min_gpu": "со 128 МБ видеопамяти, совместимая с DirectX 9.0 ", "min_ram": "1.0", "min_hdd": "5.0", "rec_os": "", "rec_cpu": "", "rec_gpu": "", "rec_ram": null, "rec_hdd": null } } I used CharField for fields like "name", "description", and EmbededField (from Djongo) for fields … -
Difference between web application architecture and design pattern?
I need to develop a photo album web app in Django, stored on cloud services, with user login authentication, metadata and database. It must be developed according to a specific software design pattern that is different to the architectural pattern chosen. Please explain the difference between design and architectural patterns. Any industry acceptable suggestions on these patterns, suitable for a small project as explained above, would be very helpful. -
Django RestFRamework filter a ManytoMany model field
In my django app i have these two models: class Device(models.Model): mac_id = models.CharField(max_length=400, primary_key=True, null=False) short_name = models.CharField(max_length=400, default='') ... class Anagrafica(models.Model): id = models.AutoField(primary_key=True) cod_imp = models.CharField(max_length=80, verbose_name="Codice impianto") rb_sel = models.ManyToManyField(Device) well i have to filter in my API using Django RestFramework the rb_sel field, so i try: in serialyzers.py: class RaspFilter(django_filters.FilterSet): rb_sel = django_filters.BaseInFilter( name ='rb_sel__short_name', lookup_type='in', ) class Meta: model = Anagrafica fields = ('cod_imp', 'rb_sel') class AnagraficaSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') rb_list = DeviceSerializer(read_only=True, many=True) class Meta: model = Anagrafica fields = ['id', 'cod_imp', 'soc', 'soc_sigla', 'regione', 'prov', 'comune', 'cap', 'indirizzo', 'coordinate', 'notes', 'rb_list', 'owner'] filter_class = RaspFilter and in my views.py i add: filter_backends = [DjangoFilterBackend] filter_class = RaspFilter but when i try my api i get a 500 error: TypeError at /api/anagrafica/ init() got an unexpected keyword argument 'name' where i am wrong? how can i filter on my manytomany rb_list field? So many thanks in advance -
show related images to product in Django?
Hi Here I am trying to display all the images related to a particular product in a popup My problem is the When I upload a photo for one of This Objects, it display on a both of Object how can i filter them for to display on the relavent object? Photo 1 Popup Admin Panel my models.py class Portfolio_Detail(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='Portfolio/') def __str__(self): return self.title class Portfolio_Image(models.Model): portfolio = models.ForeignKey(Portfolio_Detail, on_delete=models.CASCADE,related_name="portfolio") image = models.ImageField(upload_to='Portfolio_Image/') my views.py def home(request): portfolios = Portfolio_Detail.objects.all() portfolio_images = Portfolio_Image.objects.filter() context = { 'portfolios' : portfolios, 'portfolio_images' : portfolio_images, } return render(request, "index.html", context) My Template <!-- Portfolio Section Start --> <section class="portfolio-section sec-padding" id="portfolio"> <div class="container"> <div class="row"> <div class="section-title"> <h2>Recent Works</h2> </div> </div> <div class="row"> <!-- Portfolio Item1 Start --> {% for item in portfolios %} <div class="portfolio-item"> <div class="portfolio-item-thumbnail"> <img src="{{item.image.url}}" alt="portfolio item Thumb"> </div> <h3 class="portfolio-item-title">{{item.title}}</h3> <button type="button" class="btn view-project-btn">View Project</button> <div class="portfolio-item-details"> <div class="description"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> </div> <div class="general-info"> <ul> <li>Created : <span>4 dec 2020</span></li> <li>Technology : <span>Html</span></li> <li>Role : <span>Frontend</span></li> <li>View Online : <span><a href="#" target="_blank">www.domain.com</a></span></li> </ul> </div> </div> </div> <!-- Portfolio Item1 End --> {% endfor %} </div> … -
How to make a filtering in Django
I want to do a filtering in django and I want to do this with date_created from custumUser for my filter. I can show date_create using list_display to my admin panel, but I can't filter through it on the page. my models.py like that. class CustomUser(AbstractBaseUser): email = models.EmailField(max_length=200, unique=True, verbose_name='Email') username = models.CharField(max_length=150, verbose_name='Username') first_name = models.CharField(max_length=150, verbose_name='First Name') last_name = models.CharField(max_length=150, verbose_name='Last Name') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email # this methods are require to login super user from admin panel def has_perm(self, perm, obj=None): return self.is_admin # this methods are require to login super user from admin panel def has_module_perms(self, app_label): return self.is_admin class Meta: verbose_name = ('user') verbose_name_plural = ('users') class EmailConfirmed(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) activation_key = models.CharField(max_length=500) email_confirmed = models.BooleanField(default=False) date_confirmed = models.DateTimeField(auto_now=True) def __str__(self): return self.user.email class Meta: verbose_name_plural = 'User Email Confirmed' @receiver(post_save, sender=CustomUser) def create_user_email_confirmation(sender, instance, created, **kwargs): if created: dt = datetime.now().strftime('%Y-%m-%d … -
i can't make django to show pictures in my django project project is there any solution for it?
i can't make django to show pictures in my blog project hello, i am currently workin on a django blog project i have a really different problem i want to store each blogs post on a .pdf file and store it on a file in server the problem i have is that when i add the .pdf file and when django reads the file it just read the text and display the text as i want but it is unable to show pictures in the page. if there is a solution for this problem could you please share it and for that thank you a million times. -
Manager isn't accessible via class instance
I've recently faced Manager isn't accessible via model instance this error. By reading the Django doc I was able to resolve it. https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-objects This reason mentioned in the Django documentation is: Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations. I can't seem to understand the above statement. Can anyone explain it in simple words -
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
i'm making a django ecommerce site from a this youtube ecommerce tutorial.i have created a function for the delete from cart but when i press the delete button, i get this message TypeError at /cart/delete/ int() argument must be a string, a bytes-like object or a real number, not 'NoneType' here is the function def cart_delete(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) cart.delete(product=product_id) response = JsonResponse({'success':True}) return response > TypeError at /cart/delete/ int() argument must be a string, a > bytes-like object or a real number, not 'NoneType' Request > Method: POST Request URL: http://127.0.0.1:8000/cart/delete/ Django > Version: 3.2.8 Exception Type: TypeError Exception Value: int() > argument must be a string, a bytes-like object or a real number, not > 'NoneType' Exception > Location: C:\Users\DELL\Desktop\ecommerce\cart\views.py, line 30, in > cart_delete Python > Executable: C:\Users\DELL\Desktop\ecommerce\venv\scripts\python.exe > Python Version: 3.10.0 delete function def delete(self, product): product_id = str(product) if product_id in self.cart: del self.cart[product_id] self.session.modified = True my ajax script <script> $(document).on('click', '#delete-button', function(e){ e.preventDefault(); console.log($('#select option:selected').text()) $.ajax({ type:'POST', url:'{% url "cart:cart_delete" %}', data:{ productid: $('#add-button').val(), csrfmiddlewaretoken:"{{csrf_token}}", productqty: $('#select option:selected').text(), action: 'post' }, success: function (json){ }, error: function (xhr, errmsg, err){} }) }) </script> some please help. -
foreach queryselector in javascript
I hope you are doing well, I am working with django, problem is I have a list of items that contains a menuToggle my script code is like this <script> function menuToggle1(){ document.querySelectorAll('.menupost').forEach(function(element) { element.classList.toggle('active'); }); }; </script> so when I click on one of them , I see all the menu of all items. so I don't want to see all menutoggle when I click on just one of them.I think you understand my question, I hope you guys can help me. -
On click run query function script Django
In my Django project, on my HTML page, I have a script which runs Query depending on the other values ($("#id_report").val() values). Function runs 'on click'. Problem is, when I click on '#id_person' dropdown menu to select an option which I get from query, I run query again and my selection gets reset. <script> $("#id_person").click(function () { var value = $("#id_report").val(); var url = $("#PostForm").attr("data-person-url"); $.ajax({ url: url, data: { 'value': value, }, success: function (data) { $("#id_person").html(data); console.log(data); } }); }); </script> How can I run this only when I click on dropdown, not when I select (then it runs again because it's a click) -
I want to order my list by most liked content, for e.g. most liked thing shows on top and most disliked at bottom,, help me please
I want to order my list by most liked content, for e.g. most liked thing shows on top and most disliked at bottom,, help me please i'm using django 3 and in my DETAIL view i want to oder the queryset by likecount field. The main goal is to odering the post with mostlikes . Like, i want to show the most liked content on top. It's like todays top 10 content(mostliked). i have tried many ways but can't figure it out. I hope you guys can help me. ==MODEL== this is a model page class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date = models.DateField(auto_now_add=True) class Content(models.Model): name = models.CharField(max_length=255) body = models.TextField() post = models.ForeignKey(Post, related_name="contents", on_delete=models.CASCADE) liked =models.ManyToManyField(User, default=None, blank=True, related_name='liked') ==VIEWS== this is a view page class Home(ListView): model = Post template_name = 'home.html' class Detail(DetailView): model = Post template_name = 'detailview.html' ordering = Content.objects.annotate(like_count=Count('liked')).order_by('-like_count') ==HOME.HTML== {% for item in object_list %} <br> <a href="{% url 'detail' item.pk %}"> {{item.title}} </a> <br> {{item.body}} <hr> {% endfor %} == I WANT TO SHOW 'ORDER BY - MOST LIKED' CONTENT ON THIS DETAIL PAGE ==DETAILVIEW.HTML== {% if not post.contents.all %} no contents yet {% … -
how to generate a custom id for specific type of users when the user signup in django?
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] customer = models.BooleanField(default=False) vendor = models.BooleanField(default=False) id = models.AutoField(primary_key=True, editable=False) userid= models.CharField(max_length=100, unique=True) objects = UserManager() def __str__(self): return self.email def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.vendor == True and self.is_superuser == False: if not self.userid: self.userid = "VEN" + str(self.id + (10 ** 5)) # generating the uid and allocating the value self.userid.save() else: pass else: pass forms.py class CustomUserCreationForm(UserCreationForm): """ A Custom form for creating new users. """ class Meta: model = CustomUser fields = ['email','first_name','last_name','mobileno'] def save(self, commit=True): user = super().save(commit=False) user.customer = True if commit: user.save() return user """ For Vendor users forms""" class VendorCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['email','first_name','last_name','mobileno'] def save(self, commit=True): user = super().save(commit=False) user.vendor = True if commit: user.save() return user views.py #Vendor Signup def VendorSignup(request): vendorform = VendorCreationForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) if vendorform.is_valid(): new_user = vendorform.save() new_user.is_active = False new_user.save() return redirect('login') else: vendorform = VendorCreationForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform}) I want to generate a customID (that starts with VEND0001)for the vendor users only when (they're signup with vendorform) and shouldn't generated … -
Django AdminEmailHandler on daphne logs
I can use Django's AdminEmailHandler just fine for my API Errors. But I can not get it to work in my daphne. All I can do so far is showing my error logs in my console. I tried numerous attempts like: 'loggers': { 'daphne': { 'handlers': ['console', 'mail_admins'], }, } It did not work though. Basically, I want to get notified if my websockets and the process within produced errors -
How to store a list of keys of another model in a model in django?
Imagine that we have 2 tariffs and two entity classes: Person and Items. The first tariff contains several people and several objects, and people and objects are not related to each other. The second tariff also stores people and items, etc. How should I store this model? ManyToManyField creates its own object for each pair (Person, Item), isn't that optimal? I don't understand, is it really more efficient to store all kinds of pairs between two fields than to store two lists of keys? (I want to keep a list of Person keys and a list of Item keys.) How to store a list of keys of another model in a model in -
JavaScript function is not defined in Django
I have a small Django project. I have a JS script in the HTML file for one of my apps: <script type="text/javascript"> function intervalSelector() { let intervalField = document.getElementById("intervalField"); let hourField = document.getElementById("hourField"); let minuteField = document.getElementById("minuteField"); intervalField.addEventListener("change", function () { if (intervalField.value === "Hourly") { hourField.disabled = true; minuteField.disabled = false; } else { hourField.disabled = false; minuteField.disabled = false; } }); } </script> This function is called by a button element further down in the HTML document: <button style="background-color: orange; color: white; float:left; margin-right:5px;" class="btn" type="button" onclick="intervalSelector()" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample" aria-expanded="false" aria-controls="collapseWidthExample"> Schedule </button> The function gets three elements by their Id in the HTML document: <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" id="intervalField"> <option selected>Interval</option> <option value="1">Daily</option> <option value="2">Hourly</option> </select> <input name="hour" class="form-control" type="number" min="0" max="23" value="23" id="hourField"> <input name="minute" class="form-control" type="number" min="0" max="59" value="57" id="minuteField"> When I run my webapp, and click the button that calls the function, it says that the intervalSelector function is not defined. Any ideas on what the problem could be?