Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run django url in background inside windows 10
I'm new to django and trying to develop a system which requires to run a certain script in the background. if i'm using linux i can register this automatically to crontab. but what will be the process if i'm using windows 10? is there any way to automate the registration of tasks in task scheduler? Here are the example of link i'm accessing http://localhost/get/1 http://localhost/get/2 http://localhost/get/3 i want to run the following link asynchronous to each other. Thank you for suggestions and help -
Which plugin for Django autocompletion
I'd like to use autocompletion in my Django project but I don't know which plugin to choose. I have ModelMultipleChoiceField in my form like: tags = forms.ModelMultipleChoiceField( label=_("Etiquettes"), queryset=Tag.objects.all(), to_field_name="name", required=False, widget=forms.SelectMultiple(attrs={'class': "form-control form-custom"}) ) I'd like to change it into autocompletion. I know there is Typeahead and Django-autocomplete-light plugins but I don't know which one is better for my case. I want to create tag if it doesn't exist after typing it. I want a field like tags in StackOverflow question form but creating tags too. Thank you if anybody can help me. Best regards. -
Django Cloudinary - how do I supply the cloud name (except in the settings)?
I am building a django 3.1.1 app with a simple cloudinary setup for storing images. I get a weird error Must supply cloud_name in tag or in configuration although I did everything as stated in the package documentation: CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'your_cloud_name', 'API_KEY': 'your_api_key', 'API_SECRET': 'your_api_secret' } The uploads work fine, the images are present in Cloudinary and I even got them to display on the page. Now this error just pops from time to time and I can't seem to find the reason why. -
Only Django Admin pages visible while rest of Site blank in production
Im trying to host my site on heroku on my localhost my project is fine with no issues , on deploying it all I get are blank pages (I inspected it and elements are shown but nothing is visible on webpage)apart from admin pages I installed all the necessary packages as I was deploying that is to say gunicorn and whitenoise as well as setting STATIC_ROOT and STATICFILES_STORAGE . I at first set DISABLE_COLLECTSTATIC = 1 and later set it to 0 when deploying, I have failed to see any error that might be causing the issue some of my files for context settings STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_dev')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import handler404 urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('user.urls')), path('users/', include('django.contrib.auth.urls')), path('accounts/', include('allauth.urls')), path('', include('pages.urls')), path('store/', include('store.urls')), #path("djangorave/", include("djangorave.urls", namespace="djangorave")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #error handlers handler404 = 'store.views.error_404' #handler500 = 'store.views.my_custom_error_view' -
How can I connect a user model to a custom model in Django?
I have a student model with a one-to-one relationship to the built-in Django User model. My aim is to combine both forms in a single template for registration such that whenever I create a new student, the student object is automatically assigned a user by using Django post_save signals. Below are the code snippets: models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Student(models.Model): CURRENT_CLASS = ( ('1', 'Form 1'), ('2', 'Form 2'), ('3', 'Form 3'), ('4', 'Form 4'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) adm_num = models.IntegerField(null=True) form = models.CharField(max_length=1, choices=CURRENT_CLASS, null=True) def __str__(self): return '%s %s' % (self.first_name, self.last_name) forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Student class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] class StudentForm(ModelForm): class Meta: model = Student fields = '__all__' exclude = ['user'] views.py def signupPage(request): form = CreateUserForm() student_form = StudentForm() if request.method == 'POST': form = CreateUserForm(request.POST) student_form =StudentForm(request.POST) if form.is_valid() and student_form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('student:login') … -
Django Session: TypeError at /order/ Object of type Decimal is not JSON serializable
While trying to delete a session variable it throws a type error. Well I to tried print out the each variable and its type that I am storing in the session. But I didn't find any variable of type decimal. What is the issue here, why ain't it deleting the session variable? def checkout_address(request): form = AddressChoiceForm(request.user, request.POST or None) next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): address_type = request.POST.get('address_type', 'shipping') address = Address.objects.get(id=request.POST.get('address')) print(address.id) request.session[address_type+'_address_id'] = address.id if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect('orders:order') return redirect('orders:order') def order(request): cart = Cart(request) order = None address_form = AddressChoiceForm(request.user) shipping_id = request.session.get('shipping_address_id', None) billing_id = request.session.get('billing_address_id', None) order, created = Order.objects.get_or_create(user=request.user, ordered=False) if shipping_id: shipping_address = Address.objects.get(id=shipping_id) order.shipping_address=shipping_address del request.session['shipping_address_id'] if billing_id: billing_address = Address.objects.get(id=billing_id) order.billing_address=billing_address del request.session['billing_address_id'] if billing_id or shipping_id: order.save() return TemplateResponse( request, "orders/order.html", { 'address_form':address_form, 'order':order, 'cart':cart } ) Traceback Internal Server Error: /order/ Traceback (most recent call last): File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/middleware.py", line 63, in process_response request.session.save() File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 83, in save obj = self.create_model_instance(data) File "/home/duke/.local/share/virtualenvs/empowerment-FJkKHZxq/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 70, … -
ValueError: not enough values to unpack (expected 2, got 1) in Django Framework
I am beginner in django, I just starts learning how to load static files and all about static file. After setting whole code when I run the server I encounter with this error: `C:\Users\Lenovo\Documents\Django project\project3\fees\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Lenovo\anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Lenovo\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 282, in get_finders yield get_finder(finder_path) File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 295, in get_finder return Finder() File "C:\Users\Lenovo\anaconda3\lib\site-packages\django\contrib\staticfiles\finders.py", line 59, in __init__ prefix, root = root ValueError: not enough values to unpack (expected 2, got 1)` please tell me why I am getting this error and how can i solve it. Here is setting.py files """ Django settings for project3 project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see … -
TypeError: Cannot read property'map' of undefined, I want to implement select option using map, but there is a problem
error code : TypeError: Cannot read property 'map' of undefined PatientInfoModal D:/test/pages/patient/PatientInfoModal.js:164 161 | </Form.Item> 162 | 163 | <Form.Item name={['patient', 'hospital']} label="Hospital" rules={[{ required: true }]}> > 164 | <Select placeholder="Select a Hospital" style={{ width:'150px' }}> | ^ 165 | {testplz.map(a => <Option>{a.name}</Option>)} 166 | </Select> 167 | </Form.Item> mycode.js : const doctorplz = { doctor } const [ whats, whatsdata ] = useState("doctor") const testplz = doctorplz[whats] <Select placeholder="Select a Hospital" style={{ width:'150px' }}> {testplz.map(a => <Option>{a.name}</Option>)} </Select> console.log(doctorplz) : {doctor: Array(4)} doctor: Array(4) 0: {d_code: 1, name: "test1", position: "RB", code_id: 1} 1: {d_code: 2, name: "test2", position: "LB", code_id: 2} 2: {d_code: 3, name: "test3", position: "ST", code_id: 2} 3: {d_code: 4, name: "test4", position: "RW", code_id: 1} length: 4 __proto__: Array(0) __proto__: Object I got the error despite entering the code correctly. I don't know what the hell is wrong. Also, the code below works fine. mycode2.js (Code that works) const namelist = { "01": [ { d_code: '1', name: 'test1' }, { d_code: '2', name: 'test2' }, { d_code: '3', name: 'test3' } ] } const [ data, setData ] = useState("01"); const Options = namelist[data]; <Select placeholder="Select a Doctor" style={{ width:'150px' }} > … -
Convert ReturnDict/Serializer.data to normal dictionary in django
In my django application I want to work on serializer.data thus there is a need to convert ReturnDict or OrderDict to normal dictionary. How can I do that ? For e.g. Here's the example data {'id': 75, 'kits': [OrderedDict([('id', 109), ('items', [OrderedDict([('id', 505), ('quantity', 6), ('product', 3)]), OrderedDict([('id', 504), ('quantity', 4), ('product', 1)]), OrderedDict([(' id', 503), ('quantity', 2), ('product', 6)]), OrderedDict([('id', 502), ('quantity', 2), ('product', 5)]), OrderedDict([('id', 501), ('quantity', 2), ('product', 4)])]), ('quantity', 2), ('kit', 10)]), OrderedD ict([('id', 110), ('items', [OrderedDict([('id', 510), ('quantity', 12), ('product', 3)]), OrderedDict([('id', 509), ('quantity', 8), ('product', 1)]), OrderedDict([('id', 508), ('quantity', 4), ('product', 6)] ), OrderedDict([('id', 507), ('quantity', 4), ('product', 5)]), OrderedDict([('id', 506), ('quantity', 4), ('product', 4)])]), ('quantity', 4), ('kit', 1)])], 'transaction_type': 'Return', 'transaction_date': ' 2020-09-24T06:16:02.615000Z', 'transaction_no': 1195, 'is_delivered': False, 'driver_name': '__________', 'driver_number': '__________', 'lr_number': 0, 'vehicle_number': '__________', 'freight_charges': 0, 've hicle_type': 'Part Load', 'remarks': 'to be deleted', 'flow': 1, 'warehouse': 1, 'receiver_client': 3, 'transport_by': 4, 'owner': 2} -
Django REST Framework: HyperlinkedModelSerializer: ImproperlyConfigured error
I am trying to serialize my Django models using the HyperlinkedModelSerializer class from Django REST Framework. My application is a dictionary application. I defined the serializer class for a Definition model, DefinitionSerializer, as follows: class DefinitionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Definition fields = ["id", "definition", "expression"] The Definition model is defined as follows: class Definition(models.Model): definition = models.CharField(max_length=256) I am trying to return the serialized data in my IndexView as follows: class IndexView(APIView): definitions = Definition.objects.all() serializer = DefinitionSerializer(definitions, context={"request": request}, many=True) return Response(serializer.data) Accessing that view, however, returns the following ImproperlyConfigured error: Could not resolve URL for hyperlinked relationship using view name "expression-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Does this error have to do with the fact that I am including slugs instead of primary keys in my URLs? For example, the URL associated with the "expression" field in the DefinitionSerializer is: app_name = "dictionary" path("define/<slug:slug>", views.ExpressionView.as_view(), name="expression") How can I make this work? -
Integrating normal HTML form with Django form
What I am trying to do is have a form that has this HTML: <form method="post" action=""> {% csrf_token %} <label>Pick a class:</label> <select id="schedClass" name="schedClass" > <option>Select one</option> {% for i in classes %} <option value="{{ i.id }}">{{ i.name }}</option> {% endfor %} </select> </select> {{ form }} <input type="submit" value="reload"> </form> The problem is that for some reason when I submit, the select schedClass doesn't appear in the link. I think it comes from the fact that it's integrated with a django form, but I have no idea. For clarification, what I am trying to do is have a form that creates an instance of a specific model, and one of the categories is schedClass which is a ManyToManyField, but I can't use a ModelForm since I need the items in the selections to be only ones that are also linked to the user with another ManyToMany. Is there anything to do? -
RecursionError at : maximum recursion depth exceeded while calling a Python object
I can't seem to find the problem in header.html which is leading to "RecursionError: maximum recursion depth exceeded while calling a Python object". base.html: {% load static %} <!DOCTYPE html> <html> <body> {% include 'header.html' %} {% include 'navbar.html' %} {% include 'dashboard.html' %} <div class="container-fluid"> {% block content %} {% endblock %} </div> {% include 'footer.html' %} </body> <!-- Bootstrap core JavaScript--> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Core plugin JavaScript--> <script src="{% static 'vendor/jquery-easing/jquery.easing.min.js' %}"></script> <!-- Custom scripts for all pages--> <script src="{% static 'js/sb-admin-2.min.js' %}"></script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script> </html> dashboard.html: {% load static %} {% extends 'base.html' %} <head> <title>:: Welcome to CrmNXT ::</title> <!-- Custom fonts for this template--> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="#"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-address-card"></i> </div> <div class="sidebar-brand-text mx-3">Welcome to NexCRM</div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> … -
Django keeps applying migrations
This is making me go insane: when I migrate, my django (3.1.1) completes the task, but seems to forgets about it. If I migrate again it will stop because it's trying to reapply the migrations. Example of the situation: I drop db.sqlite3 I drop everything inside app/migrations (excluded init) I run makemigrations: no problems. I run migrate: no problems. I run migrate again: fails (django.db.utils.OperationalError: table "django_content_type" already exists) Just to make sure I've executed "migrate --plan", confirming that it intends to apply the migrations it just performed. What am I missing here? Planned operations: contenttypes.0001_initial Create model ContentType Alter unique_together for contenttype (1 constraint(s)) auth.0001_initial Create model Permission Create model Group Create model User admin.0001_initial Create model LogEntry admin.0002_logentry_remove_auto_add Alter field action_time on logentry admin.0003_logentry_add_action_flag_choices Alter field action_flag on logentry contenttypes.0002_remove_content_type_name Change Meta options on contenttype Alter field name on contenttype Raw Python operation Remove field name from contenttype auth.0002_alter_permission_name_max_length Alter field name on permission auth.0003_alter_user_email_max_length Alter field email on user auth.0004_alter_user_username_opts Alter field username on user auth.0005_alter_user_last_login_null Alter field last_login on user auth.0006_require_contenttypes_0002 auth.0007_alter_validators_add_error_messages Alter field username on user auth.0008_alter_user_username_max_length Alter field username on user auth.0009_alter_user_last_name_max_length Alter field last_name on user auth.0010_alter_group_name_max_length Alter field name on group auth.0011_update_proxy_permissions … -
How to get date input from table created using for loop in django?
So I have passed a context from views.py to my html template. I have created a html table using 'For Loop' in the following way and also added a column with input date field. <table class="table"> <thead style="background-color:DodgerBlue;color:White;"> <tr> <th scope="col">Barcode</th> <th scope="col">Owner</th> <th scope="col">Mobile</th> <th scope="col">Address</th> <th scope="col">Asset Type</th> <th scope="col">Schhedule Date</th> <th scope="col">Approve Asset Request</th> </tr> </thead> <tbody> {% for i in deliverylist %} <tr> <td class="barcode">{{i.barcode}}</td> <td class="owner">{{i.owner}}</td> <td class="mobile">{{i.mobile}}</td> <td class="address">{{i.address}}</td> <td class="atype">{{i.atype}}</td> <td class="deliverydate"><input type="date"></td> <td><button id="schedulebutton" onclick="schedule({{forloop.counter0}})" style="background-color:#288233; color:white;" class="btn btn-indigo btn-sm m-0">Schedule Date</button></td> </tr> {% endfor %} </tbody> Now I would like to get that date element value in javascript, but its proving difficult since I am assigning a class instead of id(as multiple elements cant have same id). I tried in the following way but its not working. The console log shows no value in that variable. <script> //i is the iteration number passed in function call using forloop.counter0 function schedule(i){ var deldate = document.getElementsByClassName("deliverydate"); deldate2 = deldate[i].innerText; console.log(deldate2); //log shows no value/empty console.log(i); //log shows iteration number </script> -
How do I get all the input from the same form field in django? (The form field is in a loop in the HTML thus shows more than once)
I'm trying to get all the input from the same form field which displayed in the HTML twice since it's in a loop (as in this example). Is there a way I can do it? Below are the codes: HTML def home(request): nums = [[3, "", 2, 7, 5, 6, 1, 4, 9], [1, 4, 5, 2, 3, 9, 6, 7, 8], [6, 7, 9, 1, 4, 8, 2, 3, 5], [2, 1, 3, 4, 6, 5, 8, 9, 7], [4, 5, 6, 8, 9, 7, 3, 1, 2], [7, 9, 8, 3, 1, "", 4, 5, 6], [5, 2, 1, 6, 7, 3, 9, 8, 4], [8, 3, 7, 9, 2, 4, 5, 6, 1], [9, 6, 4, 5, 8, 1, 7, 2, 3]] context = {'nums': nums} if request.method == "POST": form = SForm(request.POST) context['form'] = form if form.is_valid(): num = form.cleaned_data.get('num') else: form = SForm() context['form'] = form context['range'] = range(9) return render(request, 's/home.html', context) Forms.py class SForm(forms.Form): num = forms.IntegerField(min_value=0, max_value=9, label=False) HTML.py {% block content %} <form method="POST" name="s_form"> {% csrf_token %} {% for row in nums %} <tr> {% for col in row %} {% if forloop.counter0|divisibleby:"9" %} <br> {% endif %} {% if … -
Error While using Qtest custom apis to create a test case
Hi I am working on of the product development where in I want to upload test cases remotely to the qtest tool with the help of the custom apis provided by the tool, I am able to login to the tool generate the authorization code, but when I call the api for uploading/creating a test case its not allowing me upload the test case I am following their official apis website to take the sample data and upload the same through postman by calling there apis but getting the below error My Post man body { "name":"An automation Test Case created via API", "properties":[ { "field_id":1695364, "field_value":710 }, { "field_id":1695363, "field_value":711 } ], "test_steps":[ { "description":"Open browser", "expected":"" }, { "description":"Access gmail.com", "expected":"Page is successfully loaded" }, { "description":"call another test case", "expected":"log in successfully", "called_test_case": { "id": 7372896, "approved": true } } ] } error in postman { "message":"null" } If Some one can please help me out with the problem -
What is the difference between request.GET.get('key', '') and request.GET.get('key)?
What is the difference between request.GET.get('key', '') and request.GET.get('key')? I thought dict.get() method's default option is None when it has not described. Then None and '' is different in Python grammar? -
category field it there in model as a foreignkey but then also it giving me this error
AttributeError: Got AttributeError when attempting to get a value for field category on serializer HelpTopicSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'category'. class HelpTopicCategorySerializer(serializers.ModelSerializer): class Meta: model = HelpCategory fields = ('category', 'parent') class HelpTopicSerializer(serializers.ModelSerializer): category = HelpTopicCategorySerializer() #here category is foreignkey class Meta: model = HelpTopic fields = ('category', 'view_or_read', 'popular_topic', 'question', 'answer') @api_view(['GET']) @permission_classes((IsAuthenticated,)) @authentication_classes((TokenAuthentication,BasicAuthentication,SessionAuthentication)) def help_topic_list(request): help_topic = HelpTopic.objects.all() for i in help_topic: print(i.category) # try: # help_topic = HelpTopic.objects.all() # except HelpTopic.DoesNotExist: # return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': print(help_topic, "ggggggggggggggggg") serializer = HelpTopicSerializer(help_topic) return Response(serializer.data) -
drf-yasg - How to customize persistent auth token?
I am using drf-yasg to generate open API, what I want is once I have added the token for authentication it should be persistent and should not expire when user refreshes the page. Currently if user refreshes the page the token gets lost and user again needs to enter the token again and again after any single change. -
How to get a testing http request in django testcase?
I'm working in a solution with only an GraphQL API, so all my logic are in forms. The save method of one of my forms receives the http request. I use the request to get some data for mailing. So, I'm trying to make a test case of this form but I don't know how to pass the request object. class SignUpForm(forms.ModelForm): ... def save(self, request, *args, **kwargs): ... How can I pass the request object to form in a test case? -
Best way to use image files with database data in Django?
I'm new to programming and to Django so forgive me if this is an easily-answerable question but I haven't managed to find any solid answers. I'm currently working on a tour booking website. I want to add several images to a tour in the Tour class, so that on the tour detail page the user can scroll through the photos. I'm referencing this page https://medium.com/ibisdev/upload-multiple-images-to-a-model-with-django-fd00d8551a1c for how to write the model, but this method is for users uploading files, so it doesn't explain how to use ones that I already have. How should I deal with these files? As the link explains, I'm hoping to use an image album class and then use that album in the Tour class, so that I can use several photos for each tour rather than just one image field. I've seen that you can put images in the database directly, but it seems like it's not the best solution. Should they be stored in the static folder? If so, how can they be associated with the correct tour in the Tour class? If they should be stored in the database, how can I call those images from the database and have them displayed in … -
I'm struggling with making search function with multi condition using django queryset
def influencer_board(request): user_input = [] index_list = [] influencer = Influencer_DB.objects.all() if request.method == 'GET': sns_type = request.GET.get('sns_type') #0 follower_num_min = request.GET.get('follower_num_min') #1 follower_num_max = request.GET.get('follower_num_max') #2 name = request.GET.get('name')#3 gender = request.GET.get('gender')#4 sns_id = request.GET.get('sns_id')#5 keyword = request.GET.get('keyword')#6 user_input.append(sns_type) user_input.append(follower_num_min) user_input.append(follower_num_max) user_input.append(name) user_input.append(gender) user_input.append(sns_id) user_input.append(keyword) for col in user_input: if col != "": index = user_input.index(col) index_list.append(index) influencer = Influencer_DB.objects for index in index_list: if index == 0: influencer = influencer.filter(sns_type=sns_type) if index == 1: influencer = influencer.filter(follower_num__gte = follower_num_min) if index == 2: influencer = influencer.filter(follower_num__lte = follower_num_max) if index == 3: influencer = influencer.filter(name=name) if index == 4: influencer = influencer.filter(gender = gender) if index == 5: influencer = influencer.filter(sns_id=sns_id) if index == 6: influencer = influencer.filter(keyword__icontains = keyword) return render(request,"influencer_board.html",{'influencer':influencer,"sns_type":sns_type,'follower_num_max':follower_num_max, 'followever':follower_num_min,'name':name, 'gender':gender,'sns_id':sns_id,'keyword':keyword}) return render(request,"influencer_board.html",{'influencer':influencer}) Like the code above, I get 7 search condition from user. Also if user inputs less than 7 conditions, still I want to filter Database with those conditions. However, it keep making enter image description here this error. the function seems to work properly because url "http://127.0.0.1:8000/influencer_board/GET?sns_type=%EC%9D%B8%EC%8A%A4%ED%83%80%EA%B7%B8%EB%9E%A8&follower_num_min=18000&follower_num_max=&name=&gender=&sns_id=&keyword= containing condition what I submitted but making 404 error. How can I solve this problem -
Why I can't pass the widget attr to form constructor in UserChangeForm in Django?
I have a form which inherited from UserChangeForm. I have given the form field a bootstrap class but why when i rendered it out there was not bootstrap class inside that field? # my model class CustomUser(AbstractUser): teacher_type = models.ForeignKey(Type, on_delete=models.CASCADE, blank=True) # my form class EditUserForm(UserChangeForm): class Meta: model = CustomUser fields = ['teacher_type',...] def __init__(self, *args, **kwargs): super(EditUserForm, self).__init__(*args, **kwargs) self.fields['teacher_type'].widget.attrs.update({'class': 'form-control'}) # view def home(request): template_name = "app/home.html" eForm = acc_forms.EditUserForm(instance=request.user) return render(request, template_name, {'eForm': eForm}) # template {{eForm.teacher_type}} When I inspected in browser I saw like this <select name="teacher_type" id="id_teacher_type"> <option value="1">Full</option> <option value="2">Time</option> </select> it supposed to has class="form-control" inside the select tag but why it doesn't? -
How to redirect to the ?next=url instead of the success_url in a generic class based view in django?
I'd like to know how to redirect to the ?next=url instead of the success_url in a generic class based view in django. the view class CategoryUpdateView(UpdateView): model = Category template_name = "categories/category_edit.html" fields = ('name', 'description', 'image') success_url = 'category_list' in the template <a href="{% url 'category_edit' category.id %}?next={% url 'another_url' %}">Add</a> After updating the category, I want to be redirected to the nex value in the link instead of the success_url. How can I do that? Thanks. -
How many spiders can we run in a scrapy?
I want to run many spiders with my scrapy. Does that make the crawling process slower or is there any limit for spiders to run? Is running many unlimited spiders makes the process slow ? Is there anyone who is experienced with Scrapy?