Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VSCode / Django Unit Tests fail when run together, but succeed when run individually
I have the following two tests within my testcase: from rest_framework.test import APITestCase, APIClient class ProductListTest(APITestCase): def test_one(self): client = APIClient() response = client.get('/api/products/') self.assertEqual(True, True) def test_two(self): # mock exceptions mock_products = MockSet() mock_products.add(MockModel( product={'id':1, 'name':'product1'}, )) # hit the API endpoint client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get('/api/products/') # expected result serialized = ProductSerializer([{'product': {'id': 1, 'name':'product1'}}], many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serialized.data) When I run them individually, they both pass. If I run them at the same time using a visual studio code extension and "run all", only the first one passes, and the second test fails, because response.data is empty. The status code is 200 though. The view is as simple as it can get: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer -
How to send password reset email with dynamic email backend
I am not configuring my email setting in my project settings.py file.I have made it dynamic so that i got confused how can i send the password reset email here ? path('password-reset/', auth_views.PasswordResetView.as_view(template_name='password_reset.html', html_email_template_name='password_reset_email.html', success_url=reverse_lazy('password_reset_done', ), #normally i used to do -->from_email=settings.EMAIL_HOST_USER, form_class=EmailValidationOnForgotPassword ),name='password_reset'), In other cases i am sending email like this config = EmailConfig.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) if form.is_valid(): sub = form.cleaned_data['sub'] msg = form.cleaned_data['msg'] email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[user.email], connection=backend) email.send() How can i use this in my urls.py from_email argument -
Change model object url in django admin list using template overriding
Suppose I have a model of Category, and it has been declared in admin.py. There are two things that I want to do using Django template overriding. Add a button on the right near "Add Category +" which is visible only on the Category List page and takes me to another URL. Overriding URLs of Category object so that clicking on each individual category on the list takes to the respective URLs # models.py class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=False) LANGUAGE_ENGLISH = 'en' LANGUAGE_FRENCH = 'fr' LANGUAGES = ((LANGUAGE_ENGLISH, 'English'),(LANGUAGE_FRENCH, 'French'),) language = models.CharField(max_length=12, default=LANGUAGE_ENGLISH, choices=LANGUAGES, blank=False) created_at = models.DateTimeField(auto_now_add=True) # admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'language', 'created_at') list_filter = ('created_at', 'language') search_fields = ('name',) date_hierarchy = 'created_at' ordering = ['-created_at'] Category in the admin panel -
Django causing noReverseMatch even with correct namespacing
I have the below urlpatterns in the root's url.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('api.urls'), name="api_app"), ] where api app contains: app_name="api_app" urlpatterns = [ url(r'^users/', views.UserList.as_view()), url(r'^users/(?P<user_type>[a-zA-Z_]+)$', views.UserList.as_view(), name="filter_type"), ..., ] the first url displays a list of users and the second url accepts a user type and filters the user list with the user_type These both work fine when I put the urls in a browser's address bar. However when I try to reference the second url from a django template like so: <form action="{% url "api_app:filter_type" user_type %}" method="GET"></form> The below error occurs: NoReverseMatch at /api/users/ Reverse for 'filter_type' with arguments '('',)' not found. 1 pattern(s) tried: ['api/users/(?P<user_type>[a-zA-Z_]+)$'] why is that? aren't the namespaces configured correctly? -
How to add custom on fly ordering for a django TabularInline?
I have a list of TabularInline objects for Model in django admin. I want to make their ordering customizable, e.x. drag & drop to rearrange Inline objects. To achieve it I plan: Use JS for drag & drop On drop event - call api endpoint with the ids of items I want to switch On back-end side execute something like: one = Model.objects.get(id=1) two = Model.objects.get(id=2) one.id, two.id = two.id, one.id one.save() two.save() Which does the trick, but I'm not sure if it's safe to swap DB ids like so and maybe there is a better (easier, safer) way to achieve this -
Filed is required on foreign key error Django rest Framework
I am in a issue in which my api is creating a duplicate data as I am just passing ingredient name and its restaurant not Pk etc. So to prevent this thing I made a class Meta: unique_together = ('restaurant' ,'name') constraint in my model . Before this everything was fine just duplicate entries were creating. Now after adding this constraint its saying 'Restaurant field is required' and my serializer is not valid. My Ingredient model is like this class Ingredient(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE ) name = models.CharField(max_length=255 ,) class Meta: unique_together = ('restaurant' ,'name') def __str__(self): return str(self.name) and my Ingredient Serializer is like class IngredientsSerializer(serializers.ModelSerializer): restaurant = RestaurantSerializer(required=False) class Meta: model = Ingredient fields = '__all__' def create(self, validated_data): restaurant = validated_data.get('restaurant') name = validated_data.get('name', None) ingredient = Ingredient.objects.create(restaurant=restaurant, name=name) return ingredient And my view.py for serialize is like @permission_classes([AllowAny]) class CreateIngredients(APIView): def post(self, request): serializer = IngredientsSerializer(data=request.data) if serializer.is_valid(): restaurant=Restaurant.objects.get(id=request.POST['restaurant']) obj_article = serializer.save(restaurant=restaurant) return Response(success_response(data='none', msg='Ingredient added'), status=status.HTTP_200_OK) -
How to store user details without asking the user?
I am trying to store user details with the PhoneBook and Contacts he creates so that I will be able to show the PhoneBook and Contacts that have been created by them. I don't want the user to explicitly add the details himself. It should be handled by the backend. I am successfully able to store the user details with the PhoneBook he created, but when I try to do the same thing with contacts, I am getting an attribute error. models.py class PhoneBook(models.Model): name = models.CharField(max_length=10, blank=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Contact(models.Model): first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=13, blank=False, unique=True) phone_book = models.ManyToManyField(PhoneBook, related_name='phone_book') user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.phone_number views.py @login_required def create_phone_book(request): form = CreatePhoneBookForm(request.POST or None) form.instance.user = request.user if form.is_valid(): form.save() form = CreatePhoneBookForm() context = {'form': form} return render(request, 'CallCenter/create_phone_book.html', context) @login_required def add_to_phone_book(request): form = AddToPhoneBookForm(request.POST or None) form.instance.user = request.user if form.is_valid(): form.save() form = AddToPhoneBookForm() context = {'form': form} return render(request, 'CallCenter/add_to_phone_book.html', context) forms.py class AddToPhoneBookForm(forms.Form): class Meta: model = Contact fields = ['first_name', 'last_name', 'phone_number', 'phone_book'] class CreatePhoneBookForm(forms.Form): class Meta: model = PhoneBook fields = ['name'] … -
Need help to build the pattern for print the number serially like given example
I have to print some digits like the given example. Can anyone give a pattern for this? Suppose I have 60 digits. On a page, I can print 21 digits. So the total page will be 3 but when I want to print the digits like the given example but I can set the pattern for this. Example: page 1: page 2: page 3: 1 22 43 2 23 44 3 24 45 4 25 46 5 26 47 6 27 48 7 28 49 8 29 50 9 30 51 -
Show modified foreignkey in django form dropdown
Models.py class Receiver_client(models.Model): name = models.CharField(max_length=255, default=0) city = models.CharField(max_length=255, default=0) address = models.CharField(max_length=255, default=0) partner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client') def __str__ (self): return self.name class OutwardDocket(models.Model): transaction_date = models.DateField(default=datetime.now) dispatch_date = models.DateField(default=datetime.now) sending_location = models.ForeignKey(Receiver_client, on_delete=models.CASCADE, related_name='receiver_location') Views.py @method_decorator([login_required, employee_required], name='dispatch') class OutwardDocketFormView(CreateView): model = OutwardDocket form_class = OutwardDocketForm template_name = 'packsapp/employee/OutwardDocketForm.html' def form_valid (self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The OutwardDocket was created with success!') return redirect('employee:outward_table') Forms.py class OutwardDocketForm(forms.ModelForm): class Meta: model = OutwardDocket fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['sending_location'].queryset = Receiver_client.objects.all() I am able to show the list of Reciever_client in my OutwardDocket Form but how can I modify it in a way such that it shows the name as well as the city of reciever client ? I don't want to change the str in the reciever client model as it is used in multiple places -
Set up a local version of Travis CI
I am trying to set up some continuous integration utility for a Django python project. The project will use Travis CI, but I also want to be able to do CI locally, for some reason. My plan is to configure a local Travis. But all resources I can find on the web were written a few years ago, such as this question on StackOverflow. Basically, all posts or discussions tell me I should use a Docker image. However, unfortunately, the official Travis image for python on Docker Hub is 3 years old. I don't think it is still being maintained. Is it because there is a new trend, and I am doing the opposite? I don't know what step to take next. -
Row level permissioning for admin page in DRF
In my project i am having few stores and for each store there is one particular owner as well. I wanted to assign stores to particular store owner that he can update the status of the order placed etc. One owner one store in the sense. Other cannot get into stores which is not assigned to him. -
How to generate current date and time on local server using DJango
I know how to print out current date and time in the console, but I am trying to add the date/time as a feature on my daily task python website. I have tried adding it as a function in my views.py file and then inserting the function in the html file of the page i want it to be on, but everything I have tried has not worked. Here is the function I created at first in views.py: def today(): """Shows todays current time and date.""" today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") return today Then I began playing around and tried this: def today(request): """Shows todays current time and date.""" today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") context = {'today': today} return render(request, context) And this is what I tried adding to the html file: <h4>{{ today }}</h4> -
Stripe Payment Intents With Django And Stripe.js
Problems: 1) Submitting the Stripe.js form with a card that requires authentication (such as 4000002760003184 or pm_card_authenticationRequired) causes the 3D secure popup to appear but the the customer cannot do anything because the page refreshes automatically after clicking submit meaning the customer cannot properly authenticate in time. Need some way to slow this process down by having the customer finish authenticating first. 2) Not sure how to replace "pm_card_visa" with the card number that the user types into the Stripe.js form. 3) What should the form action be? Is {{checkout}} correct? 4) The except statement error message runs each time I try to submit a successful payment which is not desirable. There is also no code for showing the payment was successful. 5) Submitting the Stripe.js form does not store data in the Django database like the older Stripe tokens code does. Note: Creating a subscription and a payment intent causes a successful charge for the subscription as well as the payment intent resulting in a customer getting double charged. I updated the code so that the subscription will be in trial thus avoiding the double charge. Working Older Token Code: https://github.com/justdjango/video-membership/blob/master/memberships/templates/memberships/membership_payment.html https://github.com/justdjango/video-membership/blob/master/memberships/views.py https://github.com/justdjango/video-membership/blob/master/static/js/checkout.js Older Token Code Explanation: https://www.youtube.com/watch?v=zu2PBUHMEew Payment … -
Is it possible to filter out some database rows in the middleware?
Sorry for the length of this question, I could not make it shorter and still meaningful. We have a very simple application with two simple models Company and Building, with a many-to-many relationship between them. Each has a restricted attribute. User is a regular Django User class, except we add a show attribute. # models.py class User(AbstractUser): show = models.BooleanField(default=True) class Company(models.Model): name = models.CharField(max_length=100) restricted = models.BooleanField(default=False) class Building(models.Model): name = models.CharField(max_length=100) restricted = models.BooleanField(default=False) companies = models.ManyToManyField(Company, related_name='buildings') The views are regular Django REST Framework view sets, and the serializers are as simple as possible: # views.py class CompanyViewSet(ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer class BuildingViewSet(ModelViewSet): queryset = Building.objects.all() serializer_class = BuildingSerializer # serializers.py class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' class BuildingSerializer(serializers.ModelSerializer): class Meta: model = Building fields = '__all__' Now we want to implement this behavior: if user.show is False, the user must not be able to see (in the views) the restricted Company and Building. In other words, if john is an User and john.show is False, john can see (in the views) normal_company and normal_building, but not restricted_company or restricted_building. To achieve this, we don't want to edit the views … -
How to delete model objects using an inline formset in Django
In Django I am trying to use an inline formset factory so a user can edit and delete instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying allow me to edit the objects, but when I click the delete checkbox the object doesn't delete. It is not showing me any error messages either, even when I use formset.errors or formset.non_form_errors. Models: class ExerciseName(models.Model): muscle_group = models.ForeignKey(MuscleGroup, on_delete = models.CASCADE) name_of_exercise = models.CharField(max_length=100, default = 'Exercise name', unique=True) def __str__(self): return self.name_of_exercise class SetLogger(models.Model): weight = models.IntegerField(default=0) reps = models.IntegerField(default=0) date = models.DateField(default=datetime.date.today) exercisegroup = models.ForeignKey(ExerciseName, on_delete = models.CASCADE) Content within the view I am using (not including render): exercisename = ExerciseName.objects.get(pk=exercisegroup_id) SetsFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',), can_delete=True) formset = SetsFormSet(instance=exercisename) sets = SetLogger.objects.filter(exercisegroup=exercisename) if request.method == 'POST': formset = SetsFormSet(request.POST, instance=exercisename) for form in formset: if form.is_valid(): form = form.save(commit=True) else: formset = SetsFormSet(instance=exercisename) And I am displaying the forms in my formset like this: <form method="post">{% csrf_token %} {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <button type="submit" class="save btn btn-default">Save set</button> </form> This code shows a delete checkbox … -
How Can Static Variables Within a Python Class Be Used in an Instance of the Class
In other languages, static variable are only accessible through the class name, and do not relate at all to an instance of that class. I've been following the Django Polls App Tutorial. It seems that when a model is declared, the fields of that model are static variables: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') However, the tutorial then demonstrates how the Django shell can be used: >>> from polls.models import Question >>> q = Question(question_text="What's new?", pub_date=timezone.now()) This is really confusing to me, as it seems that we are constructing, q, an object that is of type Question, but that somehow is capable of holding information (question_test and pub_date) that I thought was only related to the class, not the instance (static variables). Can someone explain to me what is going on? How is it possible that these bits of data are able to be assigned to an instance of the class? Is this a Python or Django related thing? If so, what does q even represent? Does it represent just a row in the table? This is pretty bizarre come from C++ where a static variable can't ever be related to an object of the class. -
Annotate returning null on non-existent values and I want to convert this to null into empty string
I have two models , Customer and Purchase. I want to return the last store that the customer purchased from and order on this. I can successfully show this list, showing last store the Customer purchased from, and being able to order on store name, using the following models, query/subquery. # models class Customer(models.Model): name = models.CharField(max_length=30) class Purchase(models.Model): store = models.CharField(max_length=30) amount = models.DecimalField(decimal_places=2,max_digits=6) customerID = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='purchases',null=False,blank=True) order_date = models.DateField() #viewset #subquery purchase_qs = Purchase.objects.filter(customerID=OuterRef("pk")).order_by("-order_date") queryset = Customer.objects.all().annotate(last_purchase=Subquery(purchase_qs.values('store')[:1])) ordering_fields = ['last_purchase'] My Current Output for Customers who have zero Purchases is. "last_purchase":null I want to have "last_purchase":"" -
Want to allow user to to pick datetime using the django model and forms
I have a Django model that records the DateTime of reservation. and I'm not able to create a date and time picker! I have created a model and form which allows picking a date but not time. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Reservation(models.Model): LastName = models.CharField(max_length=100) FirstName = models.CharField(max_length=100) ReserveDate = models.DateTimeField() form.py from django import forms from .models import Reservation class DateInput(forms.DateInput): input_type = 'date' class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = ['LastName', 'FirstName', 'ReserveDate'] widgets = { 'ReserveDate':DateInput(), } Reservation.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <style> .asteriskField { display: none; } </style> <div class="row justify-content-center"> <div class="col-6"> <div class="card"> <div class="card-body"> <h2> Contact </h2> <form action="" method="post" novalidate> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-secondary" value="Create" /> </form> </div> </div> </div> </div> {% endblock %} I want to see the date and time on the DateTime picker filed -
How can I start django unittest in VSCode?
I'm trying to run django unittest using VSCode, not terminal. my project tree looks like this: ├── db.sqlite3 ├── hero │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── apps.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── tests.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_hero_age.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-37.pyc │ │ ├── 0002_hero_age.cpython-37.pyc │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── toh ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── settings.cpython-37.pyc │ ├── urls.cpython-37.pyc │ └── wsgi.cpython-37.pyc ├── settings.py ├── urls.py └── wsgi.py I made tests.py file inside hero directory. My tests.py code looks like this: from django.test import TestCase, Client from .models import Hero # Create your tests here. class HeroTestCase(TestCase): def setUp(self): Hero.objects.create(name='Superman', age=10) Hero.objects.create(name='Batman', age=1) Hero.objects.create(name='Ironman', age=30) def test_hero_count(self): self.assertEqual(Hero.objects.all().count(), 3) def test_hero_id(self): client=Client() response=client.get('/hero/1/') self.assertEqual(response.status_code, 200) self.assertIn('1', response.content.decode()) def test_hero_visit_count(self): client = Client() response = client.get('/hero/hello') self.assertEqual(response.status_code, 200) self.assertIn('1', response.content.decode()) response = client.get('/hero/hello') self.assertEqual(response.status_code, 200) self.assertIn('2', response.content.decode()) And my .vscode/settings.json … -
ImageField won't validate upon invalid image type
Upon testing a form with an ImageField, a SimpleUploadedField is being utilized to mock an user uploaded image. When the form is instantiated with an invalid file type extension passed to SimpleUploadedField's name attribute, the submission silently passes. Nothing is being passed to the field as a result: <p><label for="id_avatar">Avatar:</label> <input id="id_avatar" name="avatar" type="file" /></p> The version of Django being used here is 1.9. #tests.py class SubmitProfileForm(TestCase): TEST_DIR = dirname(__file__) @classmethod def setUpTestData(cls): cls.image_path = join(cls.TEST_DIR, 'images/test_image.jpg') cls.test_data = { 'email': 'test@email.com', 'birth':'2019-01-01', 'coding_level': 'Hobbyist', 'bio': 'About me...', 'github': 'http://www.github.com', } cls.test_file = {'avatar': SimpleUploadedFile( name='test_image.txt', content=open(cls.image_path, 'rb').read(), content_type='image/jpeg' )} def test_invalid_file_uploaded(self): form = ProfileForm(self.test_data, self.test_file) self.assertTrue(form.errors) # forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ( 'email', 'birth', 'coding_level', 'bio', 'github', 'avatar' ) # models.py class Profile(models.Model): hobby = "Hobbyist" develop = "Developer" coding_level = ( (hobby, hobby), (develop, develop) ) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) email = models.EmailField() birth = models.DateField(verbose_name="Date Of Birth") coding_level = models.CharField( verbose_name="Experience", max_length=20, choices=coding_level, default=hobby, blank=False ) bio = models.TextField( verbose_name="User Bio", validators=[MinLengthValidator(10, message="Add more to your bio!")] ) github = models.URLField( verbose_name="GitHub link", validators=[check_submitted_link], unique=True ) avatar = models.ImageField(upload_to="images/%Y/%m/%d/") Expected result: form = ProfileForm(self.test_data, self.test_file) self.assertTrue(form.errors) Actual result: self.assertTrue(form.errors) … -
How do you get the auth parameters from a POST request?
I am sending a POST request to myself: requests.post("http://localhost:8000/api/", json=data, auth=('myuser', 'mypwd')) I am using Django to receive the POST request. I want to authenticate that the username and password matches what I have. def myAPI(request) if request.method == 'POST': # obtain username and password here How can I get the username and password in plain text? I've tried request.body.decode(), request.POST.items(), request.META -- just can't find it! I could send the credentials over in data and it would be easy. Alternatively, I can use an API key instead of both username and password, but I wouldn't know how to access that either. -
"StudentsSubmittedDocument.Students_Enrollment_Records" must be a "StudentsEnrollmentRecord" instance
\views def newEnroll(request): id = request.POST.get('ids') educlevel = request.POST.get('gradelevel') studentname = StudentProfile(id=id) educationlevel = EducationLevel(id=educlevel) # payment = request.POST['paymentID'] id = request.POST.get('payments') payment = PaymentType(id=id) sc = request.POST.get('schoolyear') schoolyear = SchoolYear(id=sc) myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) student = StudentsEnrollmentRecord.Student_Users V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = studentname, Document = myfile ) insert_doc.save() return render(request, 'Homepage/pending.html') \models class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files',null=True,blank=True) Remarks = models.CharField(max_length=500,blank=True,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) \html <form method="post" action="/newEnroll/" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table style="display:table-row-group;vertical-align: middle;border-color: inherit; width: 100%" class="w3-table-all w3-card-4" > <tr> <th style="text-align:center" colspan="2" cellpadding:20px> <br><br> <img src="{% static 'logo.jpg' %}" width="150px" height="150px" /> <h1 class="w3-wide">St. Anne de Beaupre</h1> <label><p style="font-weight: bold;">Enrollment Form</p></label> </th> </tr> {% for da in students %} <tr> <td style="text-align: center;"> … -
ValueError: could not convert string to float: '1.299.00' Django
I have a Django views.py file, where I both render a page and create objects based on a model. The data for creating these objects come from a function from a python file (price.py) which I imported. For some reason, when I run the script by itself, I am able to convert a string to a float (the value would be something like '4124.3123'). However, running this exact code as an import results in a value error. So my file structure looks something like this: app views.py price.py models.py urls.py Error: File "/home/joe/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joe/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/joe/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joe/Documents/pcbuilder/cpu/views.py", line 40, in homepage itemlist = canada('https://www.canadacomputers.com/index.php?cPath=4_64') File "/home/joe/Documents/pcbuilder/cpu/price.py", line 57, in canada PRICES = [float(str(i).split('>')[-3].strip('<strong/>').replace('*','').replace(',','.')[1:]) for i in PRICE] File "/home/joe/Documents/pcbuilder/cpu/price.py", line 57, in <listcomp> PRICES = [float(str(i).split('>')[-3].strip('<strong/>').replace('*','').replace(',','.')[1:]) for i in PRICE] ValueError: could not convert string to float: '1.299.00' Here is the bothersome list comprehension from my price.py: def canada(): # some code PRICES = [float(str(i).split('>')[-3].strip('<strong/>').replace('*','').replace(',','.')[1:]) for i in PRICE] #some code #return type: dictionary And here is my views.py: from django.shortcuts import render from … -
Django: How to submit the current user's username through a form without the user having to enter it
I'm looking for a simple way to have a django form submit the currently logged-in user's username behind the scenes when the user submits a form. I'd like this to happen automatically. I've seen examples in other stackoverflow entries where the init function is called. However, I find this way to be very messy and verbose. I'm using Django 2.2. -
TemplateDoesNotExist in Django and React
when i run python manage.py runserver In Backend, it show template does not exist In Front-end, it show 500 error message In my settings.py, I have specified: import os BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj' DEBUG = True ALLOWED_HOSTS = [] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In ProductList.js componentDidMount() { this.setState({ loading: true }); axios .get(productListURL) .then(res => { console.log(res.data); this.setState({ data: res.data, loading: false }); }) .catch(err => { this.setState({ error: err, loading: false }); }); }