Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: building a tree from existing model
I have already a list of products, which follow a hierarchy (with their unique product ID): 0000 ; 1000 ; 1100 ; 1110 ; 2000 ; 2100 ; 2110 I want to display these products under a tree. I have installed django-mptt, done the tutorial and read the doc but I have no idea how to implement it to my situation. Should I use mptt to build the tree or should I create the tree directly in a template? -
How to create your own hash sha3 in django?
I can not add my hash(sha3_512) using hashlib in django. My password is hashing 2 times:by me and by django automatically. def hashing(password): password = hashlib.sha3_512(password.encode('utf-8')).hexdigest() return password I want to disable django hashing and use only my function. -
Django - needs to have a value for field "id" before this many-to-many relationship can be used
I have two serializers class CheckItemSerializer(serializers.ModelSerializer): class Meta: model = CheckItem fields = ( 'item_name', 'amount', ) class PaymentActionSerializer(serializers.ModelSerializer): items = CheckItemSerializer(many=True, required=False) class Meta: model = PaymentAction fields = [ 'booking_number', 'date', 'guest_name', 'isRefund', 'lcode', 'payment_type', 'positions', 'total', 'items', 'id' ] def create(self, validated_data): action = PaymentAction.objects.create(**validated_data) action.save() if validated_data.get('items', None) is not None: items = validated_data.pop('items') if items is not None: for item in items: item_name = item['item_name'] amount = item['amount'] new_item = CheckItem.objects.create( item_name=item_name, amount=amount ) new_item.save() action.items.add(new_item) action.save() return action and json {"lcode": 123, "total": 1, "isRefund": false, "booking_number": "333", "guest_name": "me", "positions": "1 night", "date": "2019-07-22 00:00", "payment_type": "nal", "items": [ { "item_name": "glazka", "amount": "100" }, { "item_name": "glazka2", "amount": "150" } ] } and I get error "<PaymentAction: PaymentAction object>" needs to have a value for field "id" before this many-to-many relationship can be used. What am I doing wrong ? -
How to show Balance in html page for each user using django? [duplicate]
This question already has an answer here: How to show the payment which is assigned to user in html page of django? 1 answer I have a very simple question and this is also a duplicate but people who answered didn't understand. I am struggling to show the balance of each user in html page. Whenever a person login, his/her balance should be shown in browser.The result I am getting is just Your Balance is. After that nothing is showing. But people who answered they sum up the balance and I want to show each user his/her own balance which I have stored in database. How to do it? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=1) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py @login_required def balance(request): total_amount = Balance.objects.all() for field in total_amount: field.amount context = { 'total_amount': total_amount } return render(request, 'users/balance.html') Html page <h2>Your Balance is: {{total_amount.amount}}</h2> -
ChoiceAdmin inline not displaying (Django official tutorial part 7)
I'm doing the Django official tutorial and after editing the admin.py file to add and edit choices for poll questions my code is not working as expected. No error messages were displayed. Tried restarting the test server, clearing the DB (sqlite3) and deleting site data in the browser. Contents of admin.py: from django.contrib import admin from .models import Choice from .models import Question class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] admin.site.register(Question, QuestionAdmin) My "Add Question" page: https://imgur.com/m1a49gB Expected result: https://docs.djangoproject.com/en/2.2/intro/tutorial07/#adding-related-objects -
Django formtools with custom template
I have the following custom wizard <div class="container"> <div id="smartwizard"> <ul> <li><a href="#step-1">Engagement Setup<br /><small>Basic info</small></a></li> <li><a href="#step-2">File Upload<br /><small>Upload files</small></a></li> <li><a href="#step-3">Business Rules<br /><small>rules</small></a></li> <li><a href="#step-4">Documentation<br /><small>documentation</small></a></li> </ul> <div> <div id="step-1" class=""> <div id="form-step-0" role="form" data-toggle="validator"> <div class="form-group"> <label for="text">Code <span class="tx-danger">*</span></label> <input type="text" class="form-control" name="code" id="code" placeholder="Write your code" required> <div class="help-block with-errors"></div> </div> </div> <hr /> </div> .... </div> </div> <br /> </div> I have setup the django form as such class PageOne(forms.Form): ibs_code = forms.CharField(max_length=100) engagement_name = forms.CharField(max_length=100) engagement_manager = forms.CharField(max_length=100) engagement_partner = forms.CharField(max_length=100) solution = forms.CharField(label='What solution would you like to use?', widget=forms.Select(choices=FRUIT_CHOICES)) And of course the views.. class TestWizard(SessionWizardView): file_storage = FileSystemStorage( location=os.path.join(settings.MEDIA_ROOT, 'temp_uploads')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_done = False def get_template_names(self): if self.is_done: # return [self.templates['done']] return [TEMPLATES['done']] else: return [TEMPLATES[self.steps.current]] ..... ...... Now I want to use the custom template with the form. Meaning, I want to generate the form fields the way the html/style looks with form-group and such. How can I achieve this? I tried the documentation but they weren't any sources for custom templating -
Showing key error at the backend of django when i am receiving data
I want to record audio and send that audio blob to django backend to do some processing.I am using recorder.js for the recording part but it is showing key error while retrieving that blob i am using xmlhttprequest to send that blob but it is not working Javascript Code: var upload = document.createElement('a'); upload.href="show/"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); var csrftoken = Cookies.get('csrftoken'); fd.append("audio_data",blob, filename); xhr.open("POST","/show/",true); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(fd); }) urls.py : urlpatterns = [ path('admin/', admin.site.urls), path('',views.getmain), path('show/',views.solve) ] views.py" def solve(request): print("post post") file = request.FILES['audio_data'] print(file.size) return render(request,'display.html') -
Post method in django
I had a tutorial in django with forms and I tried to do exactly what is taught , but I found that either my form in not sending the post method or django can't realize that the request sent is a POST request here is my file named "register.html": {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <form role="form" method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %}</code> and here the django side views.py: <code>from django.shortcuts import render , redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages 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('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html' , {'form': form})</code> the result is when I click submit , the POST method is not working , I tried to pass a get request and it worked , so the problem only appears when I try to send the POST request , so where is problem … -
Django: separation of settings for development at production with asgi server
In the process of separating the settings, I encountered a problem on the production server. I implemented a structure with a new folder settings and added 3 files to it: base.py, production.py, development.py. I also changed the manage.py file to run the required configuration on the local machine by adding the following line: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lifeline.settings.development") On production, I use the daphne server to work with channels. The project has an asgi.py file with import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lifeline.settings.production") django.setup() application = get_default_application() Everything works fine on the local machine. The problem is that in production I get 502 errors and in asgi logs I see that the problem is in importing and the sixth line of code with the value django.setup() File "./lifeline/asgi.py", line 6, in <module> django.setup() File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/conf/__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty -
How to correctly send a date input from form to backend
I am trying to update date values in a database. The format they're currently stored in is yyyy-MM-dd. I am picking the date using ng-bootstrap datepicker, and sending it to backend in a PUT request using ngModel. I can see in the network tab that when I choose a new date it tries to send it as Date Sat Aug 03 2019 12:00:00 GMT+0100 (British Summer Time). If I don't change it is sends as End_Date: "2019-08-13". I have tried having it as different types on the model, tried to use [(ngModel)]="project.Start_Date | date:'yyy-MM-dd'". I have also tried to change the type on the Django model I am sending it to as well. HTML: <input type="text" class="form-control" placeholder="{{project.Start_Date}}" name="Start_Date" [(ngModel)]="project.Start_Date" ngbDatepicker #d="ngbDatepicker"> <div class="input-group-append"> <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button"> <span class="oi oi-calendar"></span> </button> </div> Model: export class Project { Start_Date: Date; End_Date: Date; } I want the PUT reques to send it as yyyy-MM-dd so that it can update what it currently stored. But it sends it as the full extended type. -
Allowing only superuser to call template column - Django
I have developed a template column using Django tables but i want that only super users should be able to view that column. MyTables.py class DeviceTable(tables.Table): def view(request): if request.user.is_superuser: edit = tables.TemplateColumn(template_code) class Meta: attrs = {"class": "table table-striped table-hover"} model = Devices fields = ( "name", "location", "phone_number", "ip_address", "created_date", ) The above code is not working. -
Celery can not find periodic tasks after importing libraries
I am trying to create periodic task with celery, which every day download some file from the web. But I run into a problem when I try to import libraries in file where I create the task. I get an error Received unregistered task of type 'download_data_nist.tasks.download_data'. If I delete the imports, the task is executed without errors. I have configured Celery in settings.py: from celery.schedules import crontab CELERY_BROKER_URL = 'amqp://localhost' CELERY_TIMEZONE = 'CET' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'download_data_nist.tasks.download_data', 'schedule': crontab(minute='*/1'), }, } I have created celery.py in root folder of my app: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AplikacijaZaPregledRanljivosti.settings') app = Celery('AplikacijaZaPregledRanljivosti') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I add this code to init.py in root folder: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django … -
Permission denied: '/root/.invoke.yaml' when trying to open a connection with Fabric
Here is my problem : I integrated Fabric for ssh connection, but when I try to open a connection (the connection use ssh key, passed in connection_kwargs), I get a Permission denied: '/root/.invoke.yaml' Here is my code : with ssh_connection(host=settings.JMETER_HOST_IP, user='admin') as conn: # we create a folder for the test conn.run('mkdir ' + remote_scenario_folder, hide=True) print("Uploding : " + jmx_file_path) extract of ssh_connection : ssh_connection(host, user, key_filename=settings.SSH_KEY_FILENAME, connect_timeout=settings.SSH_CONNECT_TIMEOUT, use_bastion=settings.SSH_USE_BASTION, bastion_username=settings.SSH_BASTION_USERNAME): connect_kwargs = {'key_filename': key_filename} try: connection = Connection(host, user=user, connect_timeout=connect_timeout, connect_kwargs=connect_kwargs) And the trace of error : Internal Server Error: /automatic_test/launch_test/ web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response web_1 | response = self.process_exception_by_middleware(e, request) web_1 | File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view web_1 | return view_func(request, *args, **kwargs) web_1 | File "/data/web/automatic_test/views.py", line 23, in launch_test web_1 | run_test(c,s,request.user) web_1 | File "/data/web/automatic_test/views.py", line 52, in run_test web_1 | with ssh_connection(host=settings.JMETER_HOST_IP, user='admin') as conn: web_1 | File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__ web_1 | return next(self.gen) web_1 | File "/data/web/ssh/connection.py", line 46, in … -
How to retrieve data from Elasticsearch query to be used for D3.js histogram?
I want to create a d3 histogram that shows the number of loads per day using the data from my elasticsearch query with the following agggregations: { "size": 0, "aggs": { "group_by_date": { "date_histogram": { "format": "yyyy-MM-dd", "interval" : "day", "field": "date_visited" } } } } Here is a snippet of the result: "aggregations": { "group_by_date": { "buckets": [ { "key_as_string": "2019-07-31", "key": 1564531200000, "doc_count": 8 }, { "key_as_string": "2019-08-01", "key": 1564617600000, "doc_count": 15 }, How exactly do I fetch the data? I have read and tried this but it seems to be outdated and doesn't work. It gives me the "no living connections" error. Most of the answers that I've found were also outdated and doesn't seem to be an elegant solution for me. I was wondering if there was a simpler way of fetching data from elasticsearch, like fetching data from an API. -
why image is not showing in a HTML page in Django framework?
I need to show images in html page but those are not showing. <label for="song{{forloop.counter}}"> {{song.song_title}} {% if song.is_favourite %} <img src="C:\Python Projects\Test_App\website\music\Image\fav.png" /> {% endif %} </label><br> -
Why template recognises object as unexpected identifier?
I am trying to populate multiple markers on google maps, using django. From Django views.py I am passing listing name and coordinates to the template, I receive coordinates and can use it as variable in JavaScript. But for some reason, listing name gets error saying "Uncaught SyntaxError: Unexpected number". I can't figure it out. tried to send it as a string, but still got the same. Template code: var single_listing_coordinates = []; // Function retrieves listing names and coordinates from View Class and stores them inside the single_listing_coordinates list, // inserts list into hotels array and clears the single_listing_coordinates array, so it is empty for next hotel to be stored. {% for coordinate in coordinates %} var a = {{coordinate.listing_lat}}; single_listing_coordinates.push(a); var b = {{coordinate.listing_lng}}; single_listing_coordinates.push(b); var c = {{ coordinate.listing_name }}; single_listing_coordinates.push(c); //Lists of coordinates gets pushed to listings array. listings.push(single_listing_coordinates); single_listing_coordinates = []; {% endfor %} views.py code : class ShowMapView(TemplateView): template_name = 'listing_data/show_maps.html' def test_func(self, user): return (not user.is_anonymous) and ( user.is_superuser or is_user_host(user) or is_user_cohost(user) or is_user_housekeeper(user)) def get_context_data(self, **kwargs): listings_id_parameter = self.request.GET['listings_id'] listing_ids_list = listings_id_parameter.split(",") context = {} listing_ids_list = [int(x) for x in listing_ids_list] all_locations = ABListingData.objects.filter(listing__pk__in=listing_ids_list) coordinates_list = [] for location in all_locations: … -
Django Tempus Dominus Datetimepicker time and date conversion
I've been trying for hours to change the format of my datetimepicker (Tempus DOminus for bootstrap 4) but the format won't change so now I'm trying to find a better way to convert it on the backend when it inserts to my Django model or database. The issue is, the datetimepicker currently puts the user selected date into the input as 10/02/2018 2:15 PM The problem is, I need to insert it into the database like so: 2018-10-02 02:15:00 Is there a better way that I can just auto convert that to fit the djano model timestamp format I need? I'm thinking there would have to be a way for me to look at the AM/PM from the datetimepicker and make it either 02:00:00 or 14:00:00 accordingly. in my model.py from django.db import models class CountryDirectorRequestTable(models.Model): countryDirectorRequestTo = models.CharField(max_length=50,choices=REQUEST_TO, default='accountant',verbose_name="Request To") countryDirectorRequestDetail = models.TextField(max_length=3000,null=False,blank=False, verbose_name="Request Detail",help_text="Content not more than 3000 letters") countryDirectorRequestExpectingDateAndTime = models.DateTimeField(default=timezone.now, verbose_name="Expecting Date and Time") in my form.py from django import forms from Home.models import CountryDirectorRequestTable from tempus_dominus.widgets import DateTimePicker class CountryDirectorRequestForm(forms.ModelForm): countryDirectorRequestExpectingDateAndTime = forms.DateTimeField(widget=DateTimePicker( options={ 'useCurrent': True, 'collapse': False, 'minDate': '2009-01-20', 'maxDate': '2017-01-20', # Calendar and time widget formatting 'time': 'fa fa-clock-o', 'date': 'fa fa-calendar', 'up': … -
Migrating Birthdays from old system to new django db with postgres
I have an old system that sadly accepts birthdate like 0000-01-01. I am migrating that personal data to a new system that is written in Python (Django) and uses the DateTime Model field on the PostgresDB. The old DB saves the birthday as '%Y-%m-%d'. While running the code, i now get the following error: File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 544, in _strptime datetime_date(year, 1, 1).toordinal() + 1 After some googling, i found it this is intended behvior. since Python 3, the minimum datetime value is: 0001-01-01 00:00:00 and the maxium datetime value is: 9999-12-31 23:59:59.999999 My current approach at fixing this is the following is this: When a birthday is between 0001-1-1 and timezone.now(), so not in the future, then accept it, if not, set it to None (yes, the field is nullable) in code, i tried it like this: birthday = item.get("birthday") # Comes from the old system, this gets sent as '0001-01-01', so a string min_datetime = datetime.date.min (the minimum python 3 accepts) current_day = datetime.date.today() (cant be a birthday in the future) if birthday and not isinstance(birthday, datetime.date): birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d') if not birthday or birthday … -
TypeError: 'module' object is not callable after filtering datetime
I want to write a django-orm to filter datetime field and some other fields. then convert it to pandas dataframe. this code works correctly : order_order_df = pd.DataFrame(list(Order.objects.filter(canceled=False, order_time__isnull=False).values())) but this code is not working: order_order_df = pd.DataFrame(list(Order.objects.filter(canceled=False, order_time__isnull=False, order_time__gte=datetime(2018, 10, 1)).values())) why did this happen? how can I filter datetime and convert it to pandas correctly? NOTE: I know it can be filtered properly after converting to pandas but I need it to be done by queryset here. -
django-rest ModelSerializer select fields to display in nested relationship
I'm going to reference the django-rest-framework API example on this. Lets say we have two serializers defined as below. class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Now if i do a GET request and retrieve an Album instance, it will return me a response with a list of Track instances inside it where each instance contains all the fields of Track. Is there a way to return only a selected subset of the fields in the Track model? For example to only return the title and duration field to the client but not the 'order' field. -
How to Access and Control a Document Scanner[ADF Front and Back] like Kodak or Hp from Python and Django
I already tried Pyinsane2 to access the scanner. It communicate with Kodak scanner but it Scan only first page as clear and remaining pages are fully blur. and also pyinsane2 is no more maintainable. and also i don't know how to use Libinsane which is successor of Pyinsane2. I need a help to control and scan from Python Django. def scan_process(request): pyinsane2.init() try: devices = pyinsane2.get_devices() assert (len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) try: pyinsane2.set_scanner_opt(device, "source", "ADF Front") # pyinsane2.set_scanner_opt(device, 'duplex', ['both']) except PyinsaneException: print("No document feeder found") pyinsane2.set_scanner_opt(device, 'mode', ['Color']) pyinsane2.maximize_scan_area(device) source = 'Auto' if (device.options['source'].constraint_type == pyinsane.SaneConstraintType.STRING_LIST): if 'Auto' in device.options['source'].constraint: source = 'Auto' elif 'FlatBed' in device.options['source'].constraint: source = 'FlatBed' else: print("Warning: Unknown constraint type on the source: %d"% device.options['source'].constraint_type) res = 200 colour = 'Color' # set_scanner_opt(device, 'resolution', res) # set_scanner_opt(device, 'source', source) # set_scanner_opt(device, 'mode', colour) set_scanner_opt(device,'quality','maximum') # set_scanner_opt(device,'duplex','both') # pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=True) try: while True: try: scan_session.scan.read() except EOFError: print("Got a page ! (current number of pages read: %d)" % (len(scan_session.images))) except StopIteration: print("Document feeder is now empty. Got %d pages" % len(scan_session.images)) for idx in range(0, len(scan_session.images)): image = scan_session.images[idx] file_name = … -
how to check the string contain AND and OR query params django admin search
Hi I need to make our the query from the query string for filter data from the given model, the Query will be http://127.0.0.1:3007/admin/test/testfilter/?q=user:cadmus@test.com AND age:15, Need to get result in following format from django.models import Q models.objects.filter(Q(user=cadmus@test.com) & Q(age=15)) -
Is it possible to Filter and Sort at the same time with in a single template using Class Based Generic ListView? If yes, how?
I have a template which shows the list of all the products in a template using ListView. I have this link for the sorting using different parameters on my model Product. Below is a snippet from my Template. <th> <span> Product &nbsp; </span> <a class="fa fa-sort-up fa-lg" href="{% url 'admin:product_list' %}?sort_by=name"></a> </th> {% for product in products %} <td><a href="{% url 'admin:product_update' pk=product.pk %}">{{ product.name }}</a></td> and the url that refers to a ListView called "ProductListView" is - path('products/list/', views.ProductListView.as_view(), name='product_list'), and ProductListView is as folllows - class ProductListView(UserPassesTestMixin, ListView): model = Product template_name = 'admin_app/product_list.html' context_object_name = 'products' def get_ordering(self): ordering = self.request.GET.get('sort_by') return ordering def test_func(self): return self.request.user.is_superuser I have a search box like this <form method="get" class="form-inline"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search Products..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"> <i class="fa fa-search"></i> </button> </span> </div> </form> I just want to know the path of how can I use the Search box to show me queries. I can redirect all the queries to a different page but is it possible to implement the queries on the same page? and then apply sorting on these queries. For example if I search example_product, then I want … -
What's the difference between fields outside and Inside the Meta() class?
I'm making a django Blog website. When I defined my user registration form and I'm inheriting from UserCreationForm I give two email fields one inside my Meta() class and one outside it. I read django documentaion but couldn't understand clearly. class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') So why am I giving email field twice in my UserRegistrationForm. Can someone explain it in simple words. -
How to uplaod a file in blob storage using django
I just want to upload some file in blob storage using the Django framework. I have followed this link also Django storage