Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If AtomicRequest is True in Django Is there a way to do a manual commit?
ATOMIC_REQUESTS is set to True in the DB settings. However, there are cases where you want to perform a commit manually in transaction. When I run it, I get the error "If the atomic block is active, this is forbidden". And I don't know how to solve it. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'ATOMIC_REQUESTS': True } } @transaction.atomic def get(self, request): transaction.set_autocommit(False) try: self.save_book() except Exception: print("rollback") transaction.rollback() finally: transaction.commit() transaction.set_autocommit(True) return Response('success') -
use annotate to get percent give me resulte without comma 7/2 = 3 not 3.5
i want get percent value of : nomberesteda*100/nomberhodor = 0.00 i use this queryset : listilam = MediaSecParnt.objects.filter(date__range=[primary1, primary2]).values( 'withsecondray__name','withdegrey__name','withsecondray_id','withdegrey_id') .annotate(nomberhodor=Sum('nomberhodor'), nomberesteda=Sum('nomberesteda'), percent=((((F('nomberhodor')*100)/(F('nomberesteda')))))) here : percent=((((F('nomberhodor')*100)/(F('nomberesteda')))))) percent value come without comma !! nomberhodor culomn is intiger and same for nomberesteda here is the rusult: <QuerySet [{'nomberhodor': 70, 'nomberesteda': 300, 'percent': 23}, {'nomberhodor': 64, 'nomberesteda': 150, 'percent': 42}, {'nomberhodor': 33, 'nomberesteda': 66, 'percent': 50}, {'nomberhodor': 50, 'nomberesteda': 200, 'percent': 25}, {'nomberhodor': 220, 'nomberesteda': 725, 'percent': 30}, {'nomberhodor': 567, 'nomberesteda': 900, 'percent': 63}, {'nomberhodor': 309, 'nomberesteda': 910, 'percent': 33}]> it should be : <QuerySet [{'nomberhodor': 70, 'nomberesteda': 300, 'percent': 23.33}, {'nomberhodor': 64, 'nomberesteda': 150, 'percent': 42.66}, {'nomberhodor': 33, 'nomberesteda': 66, 'percent': 50.00}, {'nomberhodor': 50, 'nomberesteda': 200, 'percent': 25.00}, {'nomberhodor': 220, 'nomberesteda': 725, 'percent': 30.34}, {'nomberhodor': 567, 'nomberesteda': 900, 'percent': 63.00}, {'nomberhodor': 309, 'nomberesteda': 910, 'percent': 33.95}]> -
Anaconda worker could not start because:
I've just installed Anaconda by using Package Control; and, after installing it, the terminal show me this message: anacondaST3: ERROR - Anaconda worker could not start because: connection to localhost:50462 timed out after 0.2s. tried to connect 7 times during 2.0 seconds check that there is Python process executing the anaconda jsonserver.py script running in your system. If there is, check that you can connect to your localhost writing the following script in your Sublime Text 3 console: import socket; socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("localhost", 50462)) If anaconda works just fine after you received this error and the command above worked you can make anaconda to do not show you this error anymore setting the 'swallow_startup_errors' to 'true' in your configuration file. And, the Anaconda autocompletation just doesn't work, the only reason I installed Anaconda for. What should I do? I'm practically a beginner in all of this programming stuff, so, be nice:( -
Django session key get or create
I have created below model tracking user-session relationships: from django.conf import settings from django.contrib.sessions.models import Session USER_MODEL = settings.AUTH_USER_MODEL class UserSession(models.Model): user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) And to populate entries of this model, registered below user_logged_in handler: from django.contrib.auth import get_user_model from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in from accounts.models import UserSession User = get_user_model() @receiver(user_logged_in, sender=User, dispatch_uid="handle_user_login") def handle_user_login(sender, request, user, **kwargs): if not request.session.session_key: request.session.create() UserSession.objects.get_or_create(user=user, session_id=request.session.session_key) The model and user login handler signal are deployed and working as expected in production. Problem is above mentioned signal sometimes raises database integrity error: insert or update on table "accounts_usersession" violates foreign key constraint "accounts_usersessio_session_id_fee1fd0b_fk_django_se" DETAIL: Key (session_id)=(56aklsn6q00dm7hnszsksokbilj1p444) is not present in table "django_session". The probability (experimental) of above exception is fairly low at about 0.04%. I couldn't reproduce this error in my local development environment. What can be cause for this error and how can I prevent it? -
Indexing on mongodb with django
I am trying to indexing on some of the fields in MongoDB collection and I am making model in django. I made a model, but I don't know how can we use indexing while creating a model Indexing on mongodb with django class USERCHAT(models.Model): _id = models.ObjectIdField() SenderID = models.CharField(max_length=255, db_index=True) ReceiverID = models.CharField(max_length=255, db_index=True) Message = models.CharField(max_length=255) DateTime = models.DateTimeField() objects = models.DjongoManager() guide me for doing indexing. -
how to use ManyToManyField as tags in my blog
i want add tags in my article and when user click on some tag it will show all articles that having that tag , so i create tag model then i add ManyToManyField field in mobile model so what next ? i mean how to use tags when i add some tag in admin panel and how to create html page for every tag ? model.py : # Tag model class Tag(models.Model): PostTagName = models.CharField(max_length=100) slug = models.SlugField(default="",blank=True,unique=True,editable=True) def save(self, *args, **kwargs): if not self.id or not self.slug: super(Tag, self).save(*args, **kwargs) self.slug = slugify(f"{self.PostTagName}") super(Tag, self).save(*args, **kwargs) def __str__(self): return self.PostTagName # mobile model class Mobile(models.Model): title = models.CharField(max_length=100,default="") name = models.CharField(max_length=100,default="") app_contect = RichTextField(blank=True,null=True) app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) post_tag = models.CharField(max_length=50,default="",choices = MOBILE_SECTION) tag = models.ManyToManyField(Tag) NETWORK = models.TextField(max_length=240,default="") LAUNCH = models.TextField(max_length=240,default="") BODY = models.TextField(max_length=240,default="") DISPLAY = models.TextField(max_length=240,default="") PLATFORM = models.TextField(max_length=240,default="") MEMORY = models.TextField(max_length=240,default="") MAIN_CAMERA = models.TextField(max_length=240,default="") SELFIE_CAMERA = models.TextField(max_length=240,default="") SOUND = models.TextField(max_length=240,default="") COMMS = models.TextField(max_length=240,default="") FEATURES = models.TextField(max_length=240,default="") BATTERY = models.TextField(max_length=240,default="") Colors = models.TextField(max_length=240,default="") Price = models.CharField(max_length=240,default="") objects = SearchManager() slug = models.SlugField(default="",blank=True,unique=True,editable=True) def save(self, *args, **kwargs): if not self.id or not self.slug: super(Mobile, self).save(*args, **kwargs) self.slug = slugify(f"{self.title}") super(Mobile, self).save(*args, **kwargs) def … -
Django project. Work with Excel files in Django
How can I generate an Excel file, fill it with data from the database, and save it as downloaded files when the button is clicked ? -
How to resolve NoReverseMatch in django while using reverse with id as argument?
So I've been getting the NoReverseMatch presumably from having passing id value greater than 9. So here's the error message I'm getting : Reverse for 'article-details' with arguments '('2', '9')' not found. 1 pattern(s) tried: ['a/(?P<pk>[0-9]+)$'] here's my code: Models.py class Post( models.Model): title = models.CharField( max_length = 250 ) author = models.ForeignKey( User , on_delete=models.CASCADE ) body = models.TextField() def get_absolute_url(self): print((self.id)) return reverse('article-details' , args= str(self.id)) urls.py urlpatterns = [ path ( 'a/<int:pk>' , ArticleDetailView.as_view() , name='article-details' ) , path('create/' , CreatePost2.as_view() , name='create_post' ) , path ( 'p/<int:pk>' , postDetails , name= 'post-details' ) , ] I think that since i have upward of 10 entries in database whenever reverse is called with id > 9 it interprets it as touple with 2 values. How do i solve this issue ? -
Link added to HTML by JavaScript does nothing when clicked
I'm creating a primitive search engine for the support database on my Django site. I have JavaScript set to listen for any changes to the search field, and then query for suggestions to the server. The script then loops through the JSON result and generate a Bootstrap-styled dropdown below the search box. Everything about it is working flawlessly… except the part where clicking the suggestions actually takes you there. Hovering over the links turns them blue and shows their target in the lower-left corner of my Chromium Edge. But clicking just does nothing. You can inspect the HTML and click the link's target there, and it works. You can even delete the element and recode it back in the inspector and clicking it works there! It must have something to do with JavaScript adding it and not refreshing properly. Here's part of my HTML (a lot of the extra mumbo-jumbo is for Bootstrap; I copied it right from their documentation): <input type="text" class="form-control" placeholder="Search" id="query"> <div class="input-group-append"> <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> </button> <div class="dropdown-menu dropdown-menu-lg-right" id="suggestions"> <p class="p-4 text-muted" id="noresults"> No articles that mach your query were found. Try something else. </p> </div> </div> And … -
May I use the "Software developer" title on my freelancer profile? [closed]
I'm a freelancer! My skill-set is Python, Django, DRF, Javascript, Node, React My question is May I use the "Software developer" or "Freelance Software developer" title as a freelancer? -
Post class does not have objects variable in Django for Beginners
In W S Vincent's "Django for Beginners," on page 71 he creates a simple message board Django project and then creates some testing code. His simple Post class is from django.db import models class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] and then he creates a tests.py class with the following code: from django.test import TestCase from django.urls import reverse #new from .models import Post class PostModelTest(TestCase): def setup(self): Post.objects.create(text='just a test') def test_text_content(self): post = Post.objects.get(id=1) expected_object_name = f'{post.text}' self.assertEqual(expected_object_name, 'just a test') However, as you can see, there is no Posts.objects variable or method, and the test fails. I don't see what he intended to do here, but those with more Django experience may be able to point out what is wrong. -
the necessary modifications between local contact page and in server
hello i want to create a contact page currently it works fine locally and i want to know what changes are needed for what works in the server of course i want if someone sends me a message i get an email views.py from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect from django.core.mail import EmailMessage def Contact(request): if request.method=="POST": subject = request.POST['subject'] message = request.POST['message'] from_email = request.POST['from_email'] send_mail(subject, message, from_email, ['myemail@gmail.com']) return render(request,'contact.html',{}) return render(request,'contact.html',{}) contact.html <!-- Contact Form --> <div class="col-12 col-md-8"> <div class="contact-form"> <form action="{% url 'store:contact' %}" method="post"> {% csrf_token %} <!-- Section Heading --> <div class="section-heading"> <h2>Get In Touch</h2> <div class="line"></div> </div> <!-- Form --> <form action="{% url 'store:contact' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-lg-6"> <input type="text" name="subject" class="form-control mb-30" placeholder="subject"> </div> <div class="col-lg-6"> <input type="email" name="from_email" class="form-control mb-30" placeholder="Your Email"> </div> <div class="col-12"> <textarea name="message" class="form-control mb-30" placeholder="Your Message"></textarea> </div> <div class="col-12"> <button type="submit" class="btn dento-btn">Send Message</button> </div> </div> </form> setting.py EMAIL_HOST = 'smtp.gmail.com' modify by EMAIL_HOST_USER = '' modify by myemail EMAIL_HOST_PASSWORD = ''modify by my password EMAIL_PORT = 1025 modify by 587 EMAIL_USE_SSL=False modify by ?? EMAIL_USE_TLS = False modify by ?? DEFAULT_FROM_EMAIL = 'my name <myeamil>' … -
ModuleNotFoundError: No module named 'onlineMenu/wsgi'
I was going to host it using Heroku. But it does not work because of the problem with the profile. This my Procfile web: gunicorn onlineMenu.wsgi --log-file - my wsgi.py code """ WSGI config for onlineMenu project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onlineMenu.settings') application = get_wsgi_application() this is my Heroku log (not all) 2020-10-23T16:04:08.861587+00:00 app[web.1]: Traceback (most recent call last): 2020-10-23T16:04:08.861588+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-23T16:04:08.861588+00:00 app[web.1]: worker.init_process() 2020-10-23T16:04:08.861589+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-23T16:04:08.861589+00:00 app[web.1]: self.load_wsgi() 2020-10-23T16:04:08.861589+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-23T16:04:08.861590+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-23T16:04:08.861590+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-23T16:04:08.861590+00:00 app[web.1]: self.callable = self.load() 2020-10-23T16:04:08.861591+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-23T16:04:08.861591+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-23T16:04:08.861591+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-23T16:04:08.861592+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-23T16:04:08.861592+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-23T16:04:08.861592+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-23T16:04:08.861593+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/init.py", line 127, in import_module 2020-10-23T16:04:08.861593+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-23T16:04:08.861593+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-23T16:04:08.861594+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-23T16:04:08.861594+00:00 app[web.1]: File … -
Difference between update method in Django Rest Framework?
How to figure out whether to use the update method in serializer class or in view class in Django Rest Framework when updating a user's data? Also, I couldn't find anything related to this in much detail in the Rest Framework Documentation. Can someone please help me understand it better or provide some resources for the same? -
User Password is not Encrypted Django with Rest Framework
When I create a user password remains in plain text. Also Im using signals to create user profiles related to users. Though I use the set_password method passwords are not encrypting. Serializer.py class UserSerializerAPI(serializers.ModelSerializer): class Meta: model = User fields = ['username','email','password','is_teacher'] extra_kwargs = {"password":{"write_only":True}} def create(self,validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username = username, email = email ) user_obj.set_password(password) user_obj.save() return user_obj views.py class createuser(CreateAPIView): serializer_class = UserSerializerAPI queryset = MyUser.objects.all() -
Django Rest Framework read/write ModelSerializer with ChoiceField
I have a few field in my model "OrderItem" that are ChoiceFields or Enums. I want to represent the label of the choice and doing it with serializers.CharField(source='get_service_display'). See also Django Rest Framework with ChoiceField. That works fine, but creating objects is not working anymore with following error message OrderItem() got an unexpected keyword argument 'get_service_display' Here is my model class OrderItem(TimeStampedModel): class Categories(models.IntegerChoices): GRASS = (1, _('grass')) order = models.ForeignKey(Order, related_name='order_items', on_delete=models.CASCADE) unit_price = models.DecimalField(max_digits=6, decimal_places=2) category = models.IntegerField(choices=Categories.choices) and here my serializer class OrderItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) category = serializers.CharField(source='get_category_display') class Meta: model = OrderItem fields = ['id', 'unit_price', 'category'] read_only_fields = ['unit_price'] how can I create a model like this? -
django views force download not open in browser
views.py: I make excel file on demand and its always different with user by user def down_excel(request): response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-Orders.xlsx'.format( date=timezone.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title = request.user.username workbook.save(response) return response urls.py re_path(r'^test/down_excel/$', views.down_excel, name='down_excel'), template.html <a href="{% url "base:down_excel" %}">get_down</a> When I click get_down in template, It opens file on browser(I use chrome) I want to force download file with file name: {date}-Orders.xlsx'.format(date=timezone.now().strftime('%Y-%m-%d') How can I do it? -
How to sync the upload progress bar with upload on s3 bucket using Django Rest Framework
I am working on a REST API (using Django Rest Framework). I am trying to upload a video by sending a post request to the endpoint I made. Issue The video does upload to the s3 bucket, but the upload progress shows 100% within a couple of seconds only however large file I upload. Why is this happening and how can I solve this it? PS: Previously I was uploading on local storage, and the upload progress was working fine. I am using React. -
Updating fields in django table not working
currently i am trying to update some fields in a table with ajax post method, i have given acondition if ajax[data] != 'None' then update one field. it works only if condition has one statement if i pass another one it is updating only that field instead of all metioned in the update quesry. def outwardmailupdateMaker(request): datetime = 'None' if request.is_ajax() and request.method == "POST": out_id = request.POST['out_id'] senders_details = request.POST['senders_details'] mail_particulars = request.POST['mail_particulars'] address = request.POST['address'] sender_remarks = request.POST['remarks'] pod_number = request.POST['pod_number'] if pod_number != 'None': bm_pod_confirmation = 'Updated' else: bm_pod_confirmation = 'Pending' OutwardMailTable.objects.filter(pk=out_id).update(senders_details=senders_details, mail_particulars=mail_particulars, address=address, sender_remarks=sender_remarks, pod_number=pod_number, bm_pod_confirmation=bm_pod_confirmation) return HttpResponse("test") this is updating all the fields in passed to update method, but below one is only updating the pod_uploaded_date field when pod_number!='None' def outwardmailupdateMaker(request): datetime = 'None' if request.is_ajax() and request.method == "POST": out_id = request.POST['out_id'] senders_details = request.POST['senders_details'] mail_particulars = request.POST['mail_particulars'] address = request.POST['address'] sender_remarks = request.POST['remarks'] pod_number = request.POST['pod_number'] if pod_number != 'None': bm_pod_confirmation = 'Updated' pod_uploaded_date = now else: bm_pod_confirmation = 'Pending' OutwardMailTable.objects.filter(pk=out_id).update(senders_details=senders_details, mail_particulars=mail_particulars, address=address, sender_remarks=sender_remarks, pod_number=pod_number, pod_uploaded_date=pod_uploaded_date, bm_pod_confirmation=bm_pod_confirmation) return HttpResponse("test") -
POPULATE DJANGO MODEL BY IMPORTING CSV FILE - IndexError list index out of range
In my Django project i have a list full of client's information: client, name, surname, email, phone This is the code of my Client Model: class Client(models.Model): client = models.CharField(max_length=1500) name = models.CharField(max_length=255, blank=True) surname = models.CharField(max_length=255, blank=True) email = models.EmailField(blank=True) phone = PhoneNumberField(blank=True) def __str__(self): return f"{self.client}" def get_absolute_url(self): return reverse('rubrica-clienti-view') This is the model that represents the CSV FILE that the user will upload: class csvCliente(models.Model): file_name = models.FileField(upload_to='csvs/clienti-csv') uploaded = models.DateTimeField(auto_now_add=True) activated = models.BooleanField(default=False) def __str__(self): return f"File id:{self.id}" def get_absolute_url(self): return reverse('rubrica-clienti-view') This is the form: class csvClienteForm(forms.ModelForm): class Meta: model = csvCliente fields = ('file_name',) I want to give the users the possibility of adding new Clients by importing a CSV FILE, so I implemented this function in the views.py: def import_csv_clients(request): form = csvClientForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = csvClientForm() obj = csvClient.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for row in enumerate(reader): row = "".join(row) row = row.replace(",", " ") row = row.split() cliente = row[1].upper() Client.objects.create( client=cliente, name=row[2], surname=row[3], email=row[4], phone=row[5], ) obj.activated = True obj.save() template = 'csv-importa-clienti.html' context = {'form': form} return render(request, template, context) After i upload the file i get this … -
Django Admin - Populate subcategory based on category
I'm trying to create in django admin interface a subcategory populated based on category previously selected. (same as in the image) django version: django-3.1.2 python version: Python 3.7.7 I followed the following tutorial: https://medium.com/better-programming/optimizing-django-admin-6a1187ddbb09 (which was also mentioned on a previous question here. Unfortunately, the same code doesn't work for me. Bellow is my code: models.py class department(models.Model): name = models.CharField(max_length=60) def __str__(self): return (self.name) class team(models.Model): department=models.ForeignKey(department, on_delete=models.CASCADE) teamName=models.CharField(max_length=150) def __str__(self): return (self.teamName) class employee(models.Model): department = models.ForeignKey(department, on_delete=models.CASCADE) team=models.ForeignKey(team, on_delete=models.CASCADE) employeeName=models.CharField(max_length=150) def __str__(self): return (self.employeeName) admin.py class departmentAdmin(admin.ModelAdmin): list_display = ["name" ] search_fields = ["name"] class Meta: model = department class teamAdmin(admin.ModelAdmin): list_display = ["teamName" ,"department"] search_fields = ["teamName", "department"] class Meta: model = team class employeeAdmin(admin.ModelAdmin): list_display = ["employeeName","team", 'get_name'] search_fields = ["employeeName", "team"] class Meta: model = employee def get_name(self, obj): return obj.team.department get_name.admin_order_field = 'department' get_name.short_description = 'department' views.py def get_subcategory(request): id = request.GET.get('id','') result = list(team.objects.filter(department_id=int(id)).values('id', 'name')) print(result) return HttpResponse(json.dumps(result), content_type="application/json") urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^/getSubcategory/$', views.get_subcategory), url(r'home', views.home) ] change_form.html - Placed on project templates {% extends "admin/change_form.html" %} {% block extrahead %} {{ block.super }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(function(){ // inspect html to check id of category select … -
Define a radio button in django
I am new in Django and I need to provide a simple form in my site. the form looks like this: My form I searched and I couldn't find any tutorial on this. html file: <form id="form" name="form" method="POST"> {% csrf_token %} <b>Is this prediction True?</b> <br> <label>No ! </label> <input type="radio" value="0" name="No" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="No"> <br> <label>Yes!</label> <input type="radio" value="1" name="Yes" data-form-field="Option" class="form-check-input display-7" id="checkbox2" title="Yes"> <br> <label>It is not a proper picture!</label> <input type="radio" value="2" name="Yes" data-form-field="Option" class="form-check-input display-7" id="checkbox3" title="none"> <br> forms.py: class FormYesOrNo(forms.Form): pvs1 = forms.TypedChoiceField(label = 'Was this prediction True?', choices=choices, widget=forms.RadioSelect) I am not sure about the above code and I don't know how to get the value response and use it in my views.py. Can you please help me in this or send me a proper documentation? -
how to show the values of a object without the name of foreign key class in python(django)
the Customer class has a foreign key to User class. i want to return this information but i don't want to show user__ before username and first_name and ... . data = {"customers": list(p.values("id", "user__username", "user__first_name", "user__last_name", "user__email", "phone", "address", "balance"))} how can i get something like that: { "customers": [ { "id": 12, "username": "leon2", "first_name": "lee", "last_name": "michalson", "email": "hamed@example.com", "phone": "042-22334455", "address": "Tehran, No.1", "balance": 20000 } ] } -
I am trying to load new page from my dashboard menu but getting page not found
my dashboardExample: I created a dashboard containing three menu under sidebar menu. On clicking "Tables menu" I receive errors like -->> Page not found Using the URLconf defined in Analyticweb.urls, Django tried these URL patterns, in this order: website/ [name='home'] website/ dd [name='dev'] admin/ The current path, website/static/home2.html, didn't match any of these. My codes are as follows: Analytic.urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('website/', include('website.urls')), path('admin/', admin.site.urls), ] website.urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('dd', views.deb, name='dev'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): # return HttpResponse("<h1>hello world</h1>") return render(request, 'website/home1.html' ) def deb(request): return render(request, 'website/home2.html' ) -
Django bootstrap datepicker plus formset new field does datepicker does not work
Whenever a new field is dynamically added to the form the datepicker does work. If I am saving the form, and then try to update it, the datepicker works on the an additional field. I am using Django-bootstrap-datepicker-plus template.html {% load crispy_forms_tags %} {% load staticfiles %} {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ formset.media }} <table class="col-md-9" style="margin-left: 10px;"> {{ formset.management_form|crispy }} {% for form in formset.forms %} <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field|as_crispy_field }} </td> {% endfor %} </tr> {% endfor %} </table> <br> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src='{% static "jquery.formset.js" %}'></script> <script type="text/javascript"> $('.formset_row-{{ formset.prefix }}').formset({ addText: 'add another', deleteText: 'remove', prefix: '{{ formset.prefix }}', }); </script> forms.py from bootstrap_datepicker_plus import DatePickerInput class DebtForm(forms.ModelForm): class Meta: model = Debt exclude = () widgets = { 'period_start': DatePickerInput(), } Any ideas how to make it work? Thanks Best wishes, Ted