Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How much should a site cost? [closed]
I have to write a site as a dating site, a backend I'm going to write on django, and a frontend on bootstrap and jss. Among the functionality of the site should be the ability for users to chat with simultaneous translation. So how much can it cost to develop such a site, and how much time can it take? -
how to pass CSRF token in Django Ajax?
I am trying to update my popup form, but it's giving me csrf token issue, please let me know how I can solve this issue. Here is my Ajax code... function exampleModal(id){ $.ajax({ url: $(this).attr("data-url") type: 'POST', dataType: "HTML" success: function(res) { $('.exampleModal').html(res); $("#exampleModal").modal("show"); } }); } here is my form data... <form method="POST" action=""/> {% csrf_token %} <div class="modal-body"> <tr> <td>{{datas.name}}</td> <td>{{datas.price}}</td> <td>{{datas.category}}</td> </tr> </div> </form> I just want to know how i can pass CSRF Token in ajax using POST method... -
Common m2m field name for diffrent models
I'm working on Django(DRF) project and there are two models: Users and Roles. They have m2m relashionship through UserRole model. import uuid from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import UserManager from django.db import models class User(AbstractBaseUser): '''Custom user model''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=150,unique=True, blank=False, null=False) roles = models.ManyToManyField('Role', through='UserRole', related_name='users') created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) deleted_at = models.DateTimeField(null=True, blank=False) USERNAME_FIELD = 'username' objects = UserManager() class Meta: db_table = "Users" def __str__(self): '''String representation of User object''' return self.username class Role(models.Model): '''User role model''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=128, unique=True, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) deleted_at = models.DateTimeField(null=True, blank=False) class Meta: db_table = "Roles" def __str__(self): '''String representation of Role object''' return self.name class UserRole(models.Model): '''Model for many-to-many relationship between User and Role ''' user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id') role = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='role_id') created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) class Meta: db_table = "Users_Roles" The task is not to delete really but only mark an object when a user deleles it(this applies to User and Roles models). Also, when the user deletes the object all object … -
Django Clear Field does not go even after changing widget
I am trying to create a edit_profile page for the CustomUser I created. I am using the UserChangeForm. But I notice that even when I change the widget (as specified here in this question) in the Meta class, the clear field is still displayed. forms.py class UserChangeForm(forms.ModelForm): profile_picture = forms.FileInput() class Meta: model = User fields = ('email', 'password', 'first_name', 'last_name', 'display_name', 'profile_picture', 'is_active', 'is_staff', 'is_superuser') widgets = { 'profile_picture': forms.FileInput(), } views.py class EditProfileView(UpdateView): model = User template_name = 'edit_profile.html' fields = ('email', 'first_name', 'last_name', 'display_name', 'profile_picture') edit_profile.html <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {% for field in form %} {{ field|add_class:"form-control-sm"|as_crispy_field }} {% endfor %} <button class="btn btn-sm btn-primary" type="submit">Update Profile</button> </form> How do I remove the clear field? -
react, I want to put the data I created in the select options
console.log(test) image click The picture shows django's data by using console.log(test) in react. my code <Select placeholder="Select a player" style={{ width:'150px' }}> <Option>{test.name}/Option> </Select> What I want is to put the name of the test data in the select option. How can I get what I want? -
Cannot use ImageField because Pillow is not installed
CommandError: System check identified some issues: ERRORS: estore.Header.img: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "python -m pip install pillow". products.Product.img: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "python -m pip install pillow". I have latest version of Pillow installed (7.2.0) requirement already satisfied pillow in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (7.2.0) I m using python version 3.8.5, visual studio version v16.7.0 and Django 3.1 Please help me! -
Django, deploy to heroku with uvicorn
I have a Django app that is deployed to Heroku with daphne. I would like to replace daphne with uvicorn, so I changed my Procfile to the following: web: bin/start-pgbouncer uvicorn rivendell.asgi:application --limit-max-requests=1200 --port $PORT worker: python manage.py runworker channel_layer -v2 But the server started and crashed almost immediately with the following error: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch -
Django form: Update model values based on user input in one field
I am writing a form to let a user enter a purchase from the template. A couple things need to happen: the purchase goes to populate a row in the replenishment table some fields of the replenishment table get updated based on what the user has input here is what my model look like: class replenishment(models.Model): Id = models.CharField(max_length=100, primary_key=True, verbose_name= 'references') Name = models.CharField(max_length=200) Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) SupplierID = models.CharField(max_length=200) Supplier = models.CharField(max_length=200) SellPrice = models.FloatField(default=0) StockOnOrder = models.FloatField(default=0) StockOnHand = models.FloatField(default=0) def __str__(self): return self.reference and the form: class ProcurementOperationRecord(forms.Form) Id = forms.CharField(required=True) Quantity = forms.FloatField(required=True) NetAmount = forms.FloatField(required=True) Supplier = forms.CharField(required=True) SellPrice = forms.FloatField(required=True) I have no clue how to let the user input the values in form and automatically add Quantity to StockOnOrder as well as automatically recognize the SupplierID based on Supplier. At this point I don't know where to start really. At least, is it possible to achieve what I try to do? -
elements of the django selectfield also generate empty lines
I'm trying to build an html select field with the django tags. Django provides me with a select field and I try to create the individual elements myself. the code looks like this: {% for field in fields %} {% if field.field.widget.input_type == "select" %} <select style="width: 100%; hight: 20%;" size="8"> {% for e in field %} <option>{{ e }}</option> {% endfor %} </select> {% else %} {{ field }} {% endif %} {% endfor %} For example, the code creates a select field that looks like this in the html: <select style="width: 100%; hight: 20%;" size="8"> <option value="1"> bla </option> <option></option> <option value="2"> blub </option> <option></option> <option value="3"> blib </option> <option></option> <option value="4"> bleb </option> <option></option> </select> The question is where the <option></option> come from? I've already tried to intercept this with {% if %}, unfortunately without success. I know that {{field}} creates a select field for me, unfortunately this is not an option because I want to style the select field even more ... -
How to upload local images using django-tinymce4-lite?
I am using django-tinymce4-lite to add content and images in my blog, but I have problem adding local images from my computer. Can anyone help? Thank you -
Migrate from DateField to DateTimeField in Django
I have a model with field date = models.DateField() Now I want to migrate this field to DateTimeField, so it should look like this: date = models.DateTimeField() I know that I should run the commands below to make migrations. python manage.py makemigrations python manage.py migrate I tried to use this command python manage.py schemamigration --auto appname but it's not help me But I want to migrate all of this field with saving the date and only add the time 00:00:00:000000. Could you help me to explain how can I do it? -
AttributeError: 'QuerySet' object has no attribute 'requestedDate'
I just want to filter the CustomerPurchaseOrder(inputdate) to CustomerPurchaseOrderDetail(requestedDate). How do i do that? This is my current views.py record = CustomerPurchaseOrder.objects.filter(profile__in=client.values_list('id')) date = CustomerPurchaseOrder.objects.filter(profile__in=client.values_list('id')) status = CustomerPurchaseOrderDetail.objects.filter(profile__in=client.values_list('id')) \ .filter(customer_Purchase_Order__in=record.values_list('id')).filter(inputdate=date.requestedDate) class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customerdeliveryaddress = models.ForeignKey(CustomerDeliveryAddress, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Delivery Address") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") requestedDate = models.DateField(auto_now_add=True) class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") products = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") customer_Purchase_Order = models.ForeignKey(CustomerPurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerPurchaseOrder") inputdate = models.DateField(auto_now_add=True) This is my full traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\decorators.py" in wrapper_func 42. return view_func(request, *args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in client 116. .filter(customer_Purchase_Order__in=record.values_list('id')).filter(inputdate=records.requestedDate) Exception Type: AttributeError at /client/ Exception Value: 'QuerySet' object has no attribute 'requestedDate' -
Not lazy Queryset calls outside methods
I use Django in work and I'm still learning about some of its features - recently I ran into a problem with a Queryset call in one of my DetailView classes. While the code ran perfectly for me, it broke on the CI pipeline set to initialize a project from scratch. I got the answer that it's because of the non-lazy evaluation of said call - to be precise, it roughly looked like this: class MyListView(ListView): queryset = ( MyModel.objects.all() .exclude(some_type_field__in=[ContentType.objects.get_for_model(MyReferenceModel)]) .distinct() ) template_name = #... In addition, I was told not to write Queryset calls that are not lazily evaluated outside of methods - and that the reason is that the Python interpreter executes code module by module. I don't understand this part, however. How methods has anything to do with it? Why is it an issue if the code above, tries to actually hit the database? To specify my question further, I show what was the solution I got: class MyListView(ListView): model = MyModel def get_queryset(self): return ( super() .get_queryset() .exclude(some_type_field__in=[ContentType.objects.get_for_model(MyReferenceModel)]) .distinct() ) template_name = # ... What's the actual difference between the two? I need to understand this problem better, and Django wiki was no help. -
How can you customize the response message of the post in django?
I am trying to make a membership API using django rest frameworks.I made a code and checked that the function was working properly. In my current code, if the data of the email, password, and username are empty, the message is given as follows. { "email": [ "This field is required." ], "username": [ "This field is required." ], } But after talking about this with my team's client developers, they said it was better to give a unified message as below. { "message": "email field is required." } How can I customize the value like this? Here's my code. class customSignUpView (GenericAPIView) : serializer_class = customRegisterSerializer def post (self, request) : user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user = User.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('emailVerify') absurls = F'http://{current_site}{relativeLink}?token={token}' email_body = F'Hi {user.username} Use link below to verify your email \n{absurls}' data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email'} Util.send_email(data) return Response({'message': 'check your email.'}, status=201) -
Problem appending corresponding data on monthly basis in django
Please i need your help on this, i have made a queryset to get all months and corresponding total amounts for each month made, but the issue i face is that all amounts is only being received by the current month even when the order is created and assigned to a separate month. I am actually thinking of appending corresponding amounts made for each month but i feel there i am making some little error. This is my view queryset2 = PurchaseOrder.objects.values('created_on__month').annotate(sales_sum= Sum('po_amount')).order_by('created_on__month') data = { r['created_on__month']: r['sales_sum'] for r in queryset2 } zero = Decimal(0) data = { datetime.date(1900, m, 1).strftime('%b'): data.get(m, zero) for m in range(1, 13) } This was the queryset i got: {'Jan': Decimal('0'), 'Feb': Decimal('0'), 'Mar': Decimal('0'), 'Apr': Decimal('0'), 'May': Decimal('0'), 'Jun': Decimal('0'), 'Jul': Decimal('0'), 'Aug': Decimal('0'), 'Sep': Decimal('449670'), 'Oct': Decimal('0'), 'Nov': Decimal('0'), 'Dec': Decimal('0')} This is my model class PurchaseOrder(models.Model): created_on = models.DateTimeField(auto_now_add=True) po_amount = models.DecimalField(max_digits=10, decimal_places=2) Kindly help on this Thanks Oyero -
Django 3.1 admin interface styling issue
I just upgraded to Django 3.1 and with the new admin interface, seems like there are lot of styling changes. I have too many filters and now I am unable to see everything..Basically, it got cut after some point. I have read the docs and they are suggesting to manually change css files. Just Curious if there is any permanent fix for this? Note :- Everything was fine in my previous Django version 3.0.1. -
Invalid syntax error in view.py in django
I can't figure out what i've done wrong here. In my views.py. def register(request): if request.method == 'POST' form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) -
Index Already Exists Error in Django Migrations
I deleted the db.sqlite3 and all the migrations/* files in all apps except the initial.py file. After which I tried to run the command python3.8 manage.py makemigrations product After which I ran the command python3.8 manage.py migrate product I am getting this following error: sql SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations" param () self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c374dc0> sql SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations" param () self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c374dc0> Operations to perform: Apply all migrations: product Running migrations: Applying product.0001_initial...sql INSERT INTO "django_migrations" ("app", "name", "applied") VALUES (%s, %s, %s) param ['product', '0001_initial', '2020-09-23 06:05:03.633327'] self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c30ddc0> sql CREATE INDEX "product_product_category_id_0c725779" ON "product_product" ("category_id") param () self.cursor.execute() <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f876c30db80> Traceback (most recent call last): File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: index product_product_category_id_0c725779 already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/arjun-singh/.local/share/virtualenvs/pip_env_test-RsPmIzoy/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) … -
Can you stop Django automatically reverting a manual Migration?
I have a Model file which has a change which isn't being picked up by DJango makemigrations. I created a manual migration following this answer, but if we run makemigrations afterwards Django creates a new auto migration reverting our manual changes. Is there a way to manually make a migration and tell DJango to ignore relevant parts of the code when generating future migrations? -
DRF: how to render relative urls as hyperlinks in the browsable api?
I am exposing my api through an api gateway. So absolute urls is a problem. I want to change it to allow for relative urls, but also want the relative url's to be picked up by the browsable api so when a browser views results - it can click the link. Instead of having to copy the link and add it to the browser url bar. Is there a way to do this with Django Rest Framework? I know that the rest api for AWX does it somehow. -
Model object creation test fails in Django
I have done some testing before to create an object of a model, but this one keeps failing. This is the model I want to test: class Contact(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) subject = models.CharField(max_length=200) message = models.TextField() contact_date = models.DateTimeField(default=datetime.now, blank=True) user_id = models.IntegerField(default=0, blank=True, null=True) and this is the test code: class ContactTest(TestCase): def test_contact_create(self): url = reverse('contacts:contact') user = User.objects.create_user({ 'username': 'asif', 'email': 'asif@mail.com', 'password': 'asif123!!' }) response = self.client.post(url, { "name": "marrydoe", "email": "marrydoe@mail.com", "subject": "Test", "message": "This is a test message", "contact_date": timezone.now(), "user_id": user.id, }) self.assertEqual(response.status_code, 200) self.assertContains(response, 'test') I get this traceback error, I tried to trace the problem but couldn't find where the problem resides. Creating test database for alias 'default'... System check identified no issues (0 silenced). .....................D:\GitHub\Portfolio\lib\site-packages\django\db\models\fields\__init__.py:1367: RuntimeWarning: DateTimeField Contact.contact_date received a naive datetime (2020-09-23 11:38:22.746360) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" [2020-09-23 11:38:22,750] log: ERROR - Internal Server Error: /contact/ Traceback (most recent call last): File "D:\GitHub\Portfolio\lib\site-packages\django\shortcuts.py", line 131, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "D:\GitHub\Portfolio\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "D:\GitHub\Portfolio\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'None' not found. … -
How to make appear date picker for date and time and radio button for gender select?
I want my form to have date picker appear and also the radio button for gender select. How can I make it appear on my form without writing whole HTML code for whole form. I am using the default form provided by django. I dont want to write whole code for just two fields. Is it possible? I want to learn as well. class Passenger(models.Model): book_id = models.OneToOneField(Booking, on_delete = models.CASCADE, primary_key = True) First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateTimeField() Contact_Number = models.CharField(max_length=200, unique=True) Email = models.EmailField(max_length=200, unique=True) CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(label='Gender', widget= forms.RadioSelect(choices=CHOICES)) # Gender = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.First_name This is my bookmessenger view. def bookpassenger(request): # form = AirlinesAddUpdateForm if request.method == 'POST': # obj = Booking.objects.get(id=pk) form = PassengerForm(request.POST or None) if form.is_valid(): form.save() print('we are good') messages.success(request, 'Successfully added') return redirect('booking') This is my default form extracted from django itself. <form action="{% url 'bookpassenger' %}" method="POST"> {% csrf_token %} {{form|crispy}} <input type="submit" class=" btn btn-success " name="Submit"> </form> -
Is it possible to modify default tabbing system for a django template system?
I'm Using Jet https://github.com/geex-arts/django-jet/ for my dashboard but I'm having one issue. On the admin page, when I perform a Save and add another action, the object gets saved and the page reloads. After the reload, the active tab becomes the last tab that I was editing. Is it possible to make it default to the first Tab after the reload and only for the Save and add another button? Every time the page reloads from the Save and Add another button, I want it to default to the Format tab. -
How to display data Today, Yesterday and last 7 Days in Django?
I want to display data of today, yesterday and last 7 days, please let me know how I can do it. I am trying this....but it's displaying me only the last 7 days data, but I want to display data in my HTML file according to today, yesterday and last 7 days datas= Mymodel.objects.filter(created_on_gte=datetime.now()-timedelta(days=7)).count() here is my HTML file, where I am displaying data... <p>{{datas}} today</p> <p>{{datas}} Yesterday</p> <p>{{datas}} Last 7 Days</p> -
How to redirect to other template and submit the form with value passed from the original template in django
I am creating a youtube clone project in Django and I am stuck at one part. I want to implement youtube like functinality where when clicked on #tags it takes that tag as a value to search and renders the searched videos containing tags. I have implemented the search functionality using Haystack. I am able to search videos from home page(like youtube's). What I want now is when I click on tags from video playing page, tag value should come to my homepage(or view) and the search form in home template should accept its value and search it(the tag should be searched exactly like when we search it from home page manually). views.py class HomeView(SearchView): template_name = 'core/home.html' form_class = SearchForm def get_context_data(self, **kwargs): context = {} context['videos'] = Video.objects.all() context.update(kwargs) return super().get_context_data(**context) class VideoView(DetailView, FormView): template_name = 'core/video.html' form_class = React def get_object(self, **kwargs): return Video.objects.get(id=self.kwargs['id']) def get_context_data(self, **kwargs): context = {} if self.object: context['object'] = self.object context['likes'] = self.object.userprofile_set.count() #likes count by ManyToManyField reverse reference context['comments']=self.object.comment_set.all() #comments by ForeignKey reverse reference if self.request.user.is_authenticated: if self.object.userprofile_set.filter(id=self.request.user.userprofile.id).exists(): context['likestatus'] = True else: context['likestatus'] = False context.update(kwargs) return super().get_context_data(**context) def get_success_url(self): return reverse('core:videoview',kwargs={'id':self.kwargs['id']}) def post(self, request, *args, **kwargs): form = self.get_form() if …