Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
speech recognition in multiple form fields in django
Im using localhost server for my website. I have integrated speech recognition in my form fields. As I needed speech recognizer in every field of form therefore I used different view function for that and rendering back to same page. The speech is working perfectly but the problem is When I submit the form The speech recognition starts working however it should save that data into database. When I donot use speech recognizer it is saving data perfectly but not with speech recognizer as it again starts to run speech algo. I really do not know what should be done at this point. Form code <form action="" method="POST" > {% csrf_token %} <div class="txtb" style="color:#022739"> <input type="text" name="" value="{{p}}" readonly style=" font-size: 15px;color:#022739;" > <input type="hidden" name="patientname" value="{{pid}}" readonly style=" font-size: 15px;color:#022739;" required=""> </div> <div class="txtb" style="color:#022739"> <input type="text" name="" value="{{doc}}" readonly style=" font-size: 15px; color:#022739;"> <input type="hidden" name="docname" value="{{docid}}" readonly style=" font-size: 15px;color:#022739;" required=""> </div> <div class="txtb" style="display:none;color:#022739"> <input type="hidden" name="date" value="{{d}}" readonly style=" font-size: 15px;color:#022739;" required=""> </div> <div class="txtb" style="color:#022739"> <input type="text" name="cal" value="{{sp}}" placeholder="Enter total calories" style=" font-size: 15px;color:#022739;" required="" pattern="[0-9]+" > <a href="/speechCal" style="font-family: FontAwesome" > <i class="fa fa-microphone" aria-hidden="true" style="margin-left:160px;"></i> </a> </div> <div class="txtb" > … -
DateField shows None in template, but correct date in Django Admin
I have this field in my model cancel_date = models.DateField(null=True, blank=True), but it's acting weirdly. In my admin it shows correctly with the date added, but when returning it in the template as {{subscription.cancel_date}}, it displays None instead. Is there a reason why that would be? model class Subscription(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) start_date = models.DateField(auto_now_add=True) renewal_day = models.IntegerField() next_renewal_date = models.DateField(null=True, blank=True) cancel_date = models.DateField(null=True, blank=True) view def subscription_index(request): title = "Subscriptions" current_date = datetime.date.today() sub_list = Subscription.objects.all().filter(cancel_date=None).order_by('-renewal_day') paginator = Paginator(sub_list, 10) page = request.GET.get('page') try: subscriptions = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. subscriptions = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. subscriptions = paginator.page(paginator.num_pages) context = { 'title' : title, 'subscriptions' : subscriptions } return render(request, 'accounts/subscriptions_index.html', context) template {% for subscription in subscriptions %} {{subscription.cancel_date}} {% endfor %} -
Django Redirect returns 200, but page does not redirect
I have a django project where I am doing google oauth2. I click on a google signin button, I receive a post request from Googles api, and then I interpret that request and want to redirect the user to a page where they can create their own account. Right now everything appears to work up until the redirect is suppose to happen. The terminal where my django project is running shows that it was successful (the print statements I wrote to confirm it reaches the render function work, and I see a 200 response also), but I remain on the login page. I am wondering if the redirect and render are happening on another website session, or otherwise somewhere besides where the user is currently on the website? Here is the code for my google webhook: token = request.POST.get('idtoken') print(token) try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), settings.GOOGLE_CLIENT_ID) print(idinfo) print('got past token') google_user_id = idinfo['sub'] google_email = idinfo['email'] try: # authenticates user who already exists as a google signed in user. user_from_sub = User.objects.get(google_sub_id=google_user_id) user = user_from_sub.get_user_object() if user.type == Types.BUSINESS: backend = 'user_accounts.auth_backends.BusinessAuthBackend' login(request, user, backend=backend) # TODO: add auth backend cred elif user.type == Types.CONSUMER: backend = 'user_accounts.auth_backends.ConsumerAuthBackend' login(request, user, … -
Restarting django-q qcluster gracefully
How can we restart qcluster gracefully for server changes? E.g. We use gunicorn to run django server which lets you gracefully restart workers without down time. How can you restart qcluster workers without disturbing any ongoing worker processing? Thanks. -
Aggregating a windowed annotation in Django
Background Suppose we have a set of questions, and a set of students that answered these questions. The answers have been reviewed, and scores have been assigned, on some unknown range. Now, we need to normalize the scores with respect to the extreme values within each question. For example, if question 1 has a minimum score of 4 and a maximum score of 12, those scores would be normalized to 0 and 1 respectively. Scores in between are interpolated linearly (as described e.g. in Normalization to bring in the range of [0,1]). Then, for each student, we would like to know the mean of the normalized scores for all questions combined. Minimal example Here's a very naive minimal implementation, just to illustrate what we would like to achieve: class Question(models.Model): pass class Student(models.Model): def mean_normalized_score(self): normalized_scores = [] for score in self.score_set.all(): normalized_scores.append(score.normalized_value()) return mean(normalized_scores) if normalized_scores else None class Score(models.Model): student = models.ForeignKey(to=Student, on_delete=models.CASCADE) question = models.ForeignKey(to=Question, on_delete=models.CASCADE) value = models.FloatField() def normalized_value(self): limits = Score.objects.filter(question=self.question).aggregate( min=models.Min('value'), max=models.Max('value')) return (self.value - limits['min']) / (limits['max'] - limits['min']) This works well, but it is quite inefficient in terms of database queries, etc. Goal Instead of the implementation above, I would prefer … -
HTML <input> tag vs <button> tag giving different behaviors in django
I'm testing an update button on my HTML form and have noticed that when I create it using this method it works just as expected: <form method="POST"> <input type ="submit" class="btn" value="Edit Data" name="edit_btn"> however when I try this method it doesn't work <div class ='form-group'> <button type="submit" class="btn btn-default" name="edit_btn"> Edit Data </button> </div> This is the function I'm calling when the button is clicked: def updatedata(request): form = FormShipmentForm(request.GET or None) if (request.POST.get('edit_btn')): selection = Shipment.objects.get(id=1) selection.booked_by = 'Dingus McDongles' selection.save(update_fields=['booked_by']) return redirect('/show') else: print('Something went wrong when updating db') context = {'form':form} return HttpResponse(render(request,'enterdata/shipmentform.html',context)) -
django url запрос на домен с пробелом [closed]
У меня есть url: .../home/<int>/bla bla как мне перенаправить пользователя на этот url с помощью {% url 'home' int.? %} -
lookup field in ModelViewSet django rest framework
I have an users endpoint in drf. I want the lookup_field for retrieving user to be something like @username not username. How can I implement this? -
django. view. testing. to check correct calculated values in view
I have a view to recalculate values (g -> kg). Quite simple. I did it just for self-education. There is a django form to add data inside of view and simple formula to re-calculate. Now, i want to test such view to give it the value and compare "output" with correct figure somehow in tests.py. Is it possible to do somehow? there is a code of view itself: def weight_converter(request): if request.method == 'POST': form = Adder(request.POST) if form.is_valid(): try: value_in_g = int(form.cleaned_data['added_data']) result_kg = value_in_g/1000 return render(request, 'weight_converter.html', {'result': result_kg, 'initial_value': value_in_g,}) except ValueError as e: e.message = 'Enter the number, not the string' return render(request, 'weight_converter.html', {'message': e.message}) else: form = Adder() return render(request, 'weight_converter.html', {'form': form}) https://pastebin.com/tUkzsUvR trying to do something like: def test_weightconverter_view_calculation(self): response = self.client.get('/weight_converter/', {'value_in_g': '1234'}) self.assertEqual(response.context['result'], 1.234) Thanks in advance for any advice! ) -
How to create an index that optimizes queries that involves 2 tables and ManyToManyFieldfield?
I want to query the below data models for Snapshots that are on a specific Branch and have one or more tags associated with the snapshot. It involves data from 3 tables, ManytoMayField, and a Foreign field. How do I define indexes that optimize this query to be fast? class Branch(models.Model): ''' Branch model One per branch ''' class Meta(object): ''' Override the default plural ''' verbose_name_plural = 'Branches' unique_together = ('branch_name', 'twig_name', 'team') branch_name = StringField("Branch Name", max_length=60) twig_name = StringField("Twig Name", max_length=60, blank=True, default='') created_at = models.DateTimeField('Created At') def __unicode__(self): return '%s:%s:%s' % (self.branch_name, self.twig_name, self.team) class Snapshot(models.Model): ''' Snapshot model One per Snapshot ''' class Meta(object): ''' Override the default plural ''' verbose_name_plural = ' Snapshots' snapshot_name = StringField("Snapshot Name", max_length=60, unique=False) branch = models.ForeignKey(Branch, related_name='branch_snapshots', on_delete=models.PROTECT, blank=True, null=True) created_at = models.DateTimeField('Created At') active = models.BooleanField("Active", default=False) def __unicode__(self): return '%s : %s: %s' % (self.snapshot_name, self.volume, self.branch) class SnapshotTag(models.Model): ''' Snapshot Tag model One per Snapshot Tag ''' class Meta(object): ''' Override the default plural ''' verbose_name_plural = ' Snapshot Tags' name = StringField("Snapshot Tag Name", max_length=60, unique=True) snapshots = models.ManyToManyField(Snapshot, related_name='snapshot_tags') def __unicode__(self): return '%s' % (self.name) -
Error in Django when I use createsuperuser command
When I use the command createsuperuser in Django, I got an error and I can execute this command, this is my traceback. Also, my Visual Studio Code give me warnings in the imports with the app "miapp". Thank you, very much. Traceback PS C:\xampp1\htdocs\Proyecto Python\AprendiendoDjango> python manage.py createsuperuser Traceback (most recent call last): File "C:\xampp1\htdocs\Proyecto Python\AprendiendoDjango\manage.py", line 21, in <module> main() File "C:\xampp1\htdocs\Proyecto Python\AprendiendoDjango\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return … -
Using get_children runs into problems with custom Page model and Wagtail
I have a model for pages I want to make with Wagtail, befitting a blog post, so there are some extra fields. This works fine as far as creating and viewing pages, but when trying to iterate through them it becomes an issue. For example, when doing something like: {% for post in self.get_children %}{{ post.date }}</a><br />{% endfor %} This will return the error AttributeError at / 'Page' object has no attribute 'date' Except the child being referred to (there is only one) absoultey has a date attribute, and when viewing the page the date attribute works just as it should. How do I inform Wagtail about custom page models? -
Not saving the record into mongodb DB in Django, Actually I am trying explore multiple different DB (Postgresql, Mongodb) in a single app
I am trying to use multiple different DB in a single app(todo). I am using Djongo package for dealing mongodb. Settings.py DATABASES = { 'default':{}, 'sql_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'USER': '******', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '5432', }, 'mongodb':{ 'ENGINE': 'djongo', 'NAME': 'mongo_db' } } todo/models.py class Task(models.Model): todo = models.CharField(max_length=200) status = models.BooleanField(default=False) def __str__(self): return self.todo todo/serializers.py class TodoSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' todo/views.py @api_view(['POST']) def todoCreate(request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() serializer.save(using='mongodb') return Response(serializer.data) it successfully saved the record into 'sql_db' but not save in the 'mongodb'. -
Updating two fields at once with choices in django admin
I have x and y in my model as DecimalField. Something like this: class MyModel(models.Model): x = models.DecimalField() y = models.DecimalField() I want user to select these x and y from a list of dictionaries I have. It has to be selected together. As an example: [ { "x": 1, "y": 2, }, { "x": 3, "y": 4, }, ] We have two dictionaries in the example list so user should see two choices in a dropdown. Choice one with x: 1 and y: 2 Choice two with x: 3 and y: 4 Do I need to customize some widget or field for that? If I need how can I do that? -
Translation with variable is not working in django templates
I am using django translation to swith language. It is working fine but when get variable from database and try to translate in template, it's not working but it's working in views. example: msg = ugettext_noop('New van booking has been made - %(pk)d') % {'pk': booked.pk} Notification.objects.create(note_category='4', message=msg, role='Admin', booking=booked, van=van) I have also tried msg = gettext('New van booking has been made - %(pk)d') % {'pk': booked.pk} Notification.objects.create(note_category='4', message=msg, role='Admin', booking=booked, van=van) and message is as New van booking has been made - 8. I have also done makemessages and compilemessage #: .\van\views.py:563 #, python-format msgid "New van booking has been made - %(pk)d" msgstr "" "Une nouvelle réservation de van a été faite. Numéro de réservation - %(pk)d" but when I loop this in template, that does not work. {% for note in admin_note %} <span class="d-block">{% trans note.message noop %}</span> {% endfor %} it only shows New van booking has been made - 8 in all languages. But it's working in view fine. print(gettext('New van booking has been made - %(pk)d') % {'pk': 8}) Does anyone know how can I get translation in template. NOrmal translation is working fine. -
Autocomplete with API not working in Django
I am trying to autocomplete cities in Django and it is not working. I think something is wrong with my form. HTML: <form method="post"> <input id="search_city" name="city" value="{{ request.GET.city }}" type="text" class="form-control input-lg" onkeyup="searchOpen()" placeholder="Los Angeles, CA"/> ..... A bunch more form entries ..... </form> Then we have the javascript, ajax to call the API to do the Autocomplete: function searchOpen() { var search = $("#search_city").val() var data = { search: search }; $.ajax({ url: '/api/get_city_state/', data: data, dataType: 'jsonp', jsonpCallback: 'searchResult' }); function searchResult(data) { $( "#search_city" ).autocomplete ({ source: data }); }; Here is my api function in views.py: def get_city_state(request): if request.is_ajax(): q = request.GET.get('city', '') results = search.find_city(q, best_match=False) data = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');' else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Create or update django redt framework
Hi all I have a drf database and device but device can only read and write I need do when device is doing a post request django checks if it doesnt exist then post it but if it exists update old data.Thanks -
Django dynamically create not equal q objects
I'm working on creating dynamic filters using nested AND / OR logic, and would like to include NOT as an option. This leverages Q objects to create the nested AND / OR logic. The class takes in a json object like so: filters = { 'and': { "url__is": "www.test.com", "name__is": "test" } } This gets compiled down to .filter(Q(url__is='www.test.com') and Q(name__is='test') This works via a recursive function that really just does this on each level of the json tree. return source_queryset.filter(reduce(and_, filter_list)) and_ is from the python operator library and has been working great. I'd like to add NOT as an option as well though, and can't seem to find an equivalent option to reduce a list of Q objects to. Does anyone know a way to use reduce in a way that creates the idea of not equal to a list of q objects? -
Cannot import name 'RadioChoiceInput' from 'django.forms.widgets' (Django 1.19 to 3.2 migration)
I have the following widgets.py file from a Django 1.19 version to upgrade to Djando 3.2 version. I am getting the error: from django.forms.widgets import RadioSelect, RadioChoiceInput ImportError: cannot import name 'RadioChoiceInput' from 'django.forms.widgets' (my_env/lib/python3.9/site-packages/django/forms/widgets.py) This is the code: from django.forms.widgets import RadioFieldRenderer, RadioChoiceInput class RadioChoiceInput2(RadioChoiceInput): def render(self, name=None, value=None, attrs=None, choices=()): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs try: self.choice_label = locale.format("%.2f", float(self.choice_label), grouping=True) except ValueError: pass return format_html( '<label class="radio" {}>{} <i></i> {}</label>', label_for, self.tag(attrs), self.choice_label ) class RadioFieldRenderer2(RadioFieldRenderer): outer_html = '{content}' inner_html = '<section class="col col-2">{choice_value}{sub_widgets}' \ '<i></i></section>' last_inner_html = '<section class="col col-1 last">{choice_value}{sub_widgets}' \ '<i></i></section>' choice_input_class = RadioChoiceInput2 def render(self): id_ = self.attrs.get('id') output = [] cc = len(self.choices) for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if id_: attrs_plus['id'] += '_{}'.format(i) sub_ul_renderer = self.__class__( name=self.name, value=self.value, attrs=attrs_plus, choices=choice_label, ) ih = self.inner_html if i == 2: ih = self.last_inner_html sub_ul_renderer.choice_input_class = self.choice_input_class output.append(format_html(ih, choice_value=choice_value, sub_widgets=sub_ul_renderer.render())) else: ih = self.inner_html if i == cc-1: ih = self.last_inner_html w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i) output.append(ih.format( choice_value=force_text(w), sub_widgets='') ) return format_html(self.outer_html, id_attr=format_html(' id="{}"', id_) … -
DateField shows None in template, but correct date in Django Admin
I have this field in my model cancel_date = models.DateField(null=True, blank=True), but it's acting weirdly. In my admin it shows correctly with the date added, but when returning it in the template as {{model.cancel_date}}, it displays None instead. Is there a reason why that would be? -
Getting data via a glue table in Django
I have a relationship as such: dictionary table dictionary_child_char table dictionary table (same as first table) Here are my models: class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=75) pinyin_marks = models.CharField(max_length=75) translation = models.TextField() level = models.IntegerField() frequency = models.IntegerField() idiom = models.BooleanField() child_char = models.ManyToManyField('Dictionary', through='DictionaryChildChar', null=True) disabled = models.BooleanField() simptradsame = models.BooleanField() class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] class DictionaryChildChar(models.Model): class Meta: db_table = 'dictionary_child_char' from_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="from_dictionary") to_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="to_dictionary") word_order = models.IntegerField() Each dictionary item has a potential many to many relationship to another dictionary item (it's Chinese characters, so each word might be made up of several constituent characters) I am trying to see these relationships, and actually grab the dictionary entry for each: dictionary = Dictionary.objects.filter(Q(simplified=char) | Q(traditional=char)).prefetch_related('child_char__to_dictionary')[:1] item = dictionary[0] item.to_dictionary.all().values() However when I do this: print(item.to_dictionary.all().values()) I get this: <QuerySet [{'id': 92661, 'from_dictionary_id': 37607, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92662, 'from_dictionary_id': 37608, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92663, 'from_dictionary_id': 37634, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92664, 'from_dictionary_id': 37635, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92665, 'from_dictionary_id': 58861, 'to_dictionary_id': 37589, 'word_order': 1}]> How, instead of the to_dictionary_id, do I actually … -
Django Rest Framework - & on method field not working as expected
In my filterset I am doing the below: class ItemFilter(FilterSet): entry_date__gte = DateTimeFilter(field_name='entry_date', method=entry_gte_filter) entry_date__lte = DateTimeFilter(field_name='entry_date', method=entry_lte_filter) class Meta: model = Item fields = ('name', 'qty', 'entry_date__gte', 'entry_date__lte') For some reason I have to use the method field here and cannot give the lookup expr directly My methods look like below: def entry_gte_filter(queryset, name, value): name = f"{name}__gte" queryset = Item.objects.annotate( detail=models.Exists(Detail.objects.filter( **{name: value, 'id': models.OuterRef('id')}))).filter(detail=True) return queryset and def entry_lte_filter(queryset, name, value): name = f"{name}__lte" queryset = Item.objects.annotate( detail=models.Exists(Detail.objects.filter( **{name: value, 'id': models.OuterRef('id')}))).filter(detail=True) return queryset However, when I execute the below API: GET /api/items?entry_date__gte=2021-06-29&entry_date__lte=2021-07-04 I get the responses with below entry dates: 2021-06-30T00:00:00 2021-06-11T00:00:00 2021-07-02T00:00:00 I am unclear why a response with 2021-06-11 is being returned when the API mentions entry_date__gte=2021-06-29 To me it looks django filters is not working as expected when method type is used. Could anyone please help me here why djangorestframework is behaving like this and if there is any way to fix this and get the expected behavior? -
problems logging in with Django custom backend
I have been trying to get my Django custom backend to work and it refuses to accept my credentials, which are correct in the database (I have verified this). It just keeps saying email and password are incorrect. I am lost and don't know where to go from here with this. I really need help at this point. VIEWS.PY class MyLogin(LoginView): template_name = 'employees/login.html' success_url = 'employees:emp-home' authentication_form = LoginForm def get_success_url(self): return super().get_success_url() def form_valid(self, form): user = self.request.POST['username'] password = self.request.POST['password'] authenticate(EmpBackend, self.request, user, password) return HttpResponseRedirect(self.get_success_url()) MODELS.PY class EmpUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password) user.staff = True user.save() return user class Emp(AbstractBaseUser): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=100, default=None, unique=True) first_name = models.CharField(max_length=100, default=None, null=True) last_name = models.CharField(max_length=100, default=None, null=True) username = models.CharField(max_length=100, default=None, null=True) password = models.CharField(max_length=100, default=None) phone = models.CharField(max_length=20, default=None, null=True, blank=True) address1 = models.CharField(max_length=100, default=None, null=True, blank=True) address2 … -
How to to do Mask input in django?
I am working on a little app so I hope you will never mind if I ask some noob questions. I am taking a NIC number from a user but with proper format. Format: xxxxx-xxxxxx-x It means that when a user click in the input field, all the xx should remove and only - will be remains, so if a user types 17301, the - should be appear automatically and then user continue to write 362775 then a - should appear automatically and finally last digit entered by the user 6. This was the complete scenario, I hope I defined it very simple. Input Field Code <div class="col-md-3 mb-3"> <label for="validationCustom10">CNIC</label> <input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="contact" required> </div> -
Django - Adding custom class to label_tag
I am trying to figure out a way to add a class to my tag on my form. I want to accomplish this without something like crispyforms and if possible not having to edit the html. Based on my knowledge and googling I have spent a few hours trying to figure this out but I cannot haha. I basically just want to output a class in the label element like so: <label class='text-muted' for="id_street_address">Street Address:</label> My model is as follows: class CheckoutForm(forms.Form): street_address = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control' } )) apartment = forms.CharField(required=False, widget=forms.TextInput( attrs={ 'class': 'form-control' } )) country = CountryField(blank_label='(select country)') zip_code = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control' } )) same_billing_address = forms.BooleanField(widget=forms.CheckboxInput()) save_info = forms.BooleanField(widget=forms.CheckboxInput()) payment_option = forms.BooleanField(widget=forms.RadioSelect()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['street_address'].label = 'Street Address' self.fields['apartment'].label = 'Address 2 (optional)' self.fields['zip_code'].label = 'Zip Code' I render my form in the template like this: <form> {% csrf_token %} {% for field in form %} <div class="form-group px-3 my-3"> {{ field.label_tag }} {{ field }} {{ field.help_text }} {{ field.errors }} </div> {% endfor %} </form> Is it possible to do this? Any help is greatly appreciated