Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
iframe on load function only triggers on certain loads, not all internal clicks
$('iframe').on('load', function () { ... } I have this piece of code, but the iframe can navigate away from it's core page, yet I can't seem to trigger a function from when the navigation has loaded. I want to be able to trigger an ajax call in django for every click's load to update the data over the top of the iframe. -
I have an author CharField, and i want to make it optional, but it gives me an error when i use required=False someone can help me?
i want to unrequire the field author because some times i need it but other times no so Traceback (most recent call last): File"C:\Users\hdPyt\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File"C:\Users\hdPyt\AppData\Local\Programs\Python\Python37\lib\threading.py" line 870, in run self._target(*self._args, **self._kwargs) File "D:\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\venv\lib\sitepackages\django\core\management\commands\runserver.py", line 109, in inner_runautoreload.raise_last_exception() File "D:\venv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\venv\lib\site-packages\django\core\management__init__.py", line337, in execute autoreload.check_errors(django.setup)() File "D:\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\venv\lib\site-packages\django\apps\registry.py", line 114, in populateapp_config.import_models() File "D:\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File"C:\Users\hdPyt\AppData\Local\Programs\Python\Python37\lib\importlib__init__.py", line 127, in import_m return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "D:\firstblog\blog\models.py", line 14, in class Post(TimestampModel): File "D:\firstblog\blog\models.py", line 17, in Post auteur = models.CharField(max_length=80, required=False) File "D:\venv\lib\site-packages\django\db\models\fields__init__.py", line 1037, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'required' -
request.user not working properly and can't be assigned to hidden model field
I am making a little image sharing website which is a lot like a blog. When I try to assign form.author = request.user, it doesn't work and the form on my website returns 'this field is required' error. I tried even other similiar projects on github to check if the error is in the project but it seems not because I get errors there too. But the interesting part is when I try to print the request.user object it prints the object without a problem but when I try to assign it for some reason it returns null. Then I tried twisting the code in every possible scenario but I couldn't debug it. This is my models.py class Meme(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) meme = models.ImageField(upload_to='memes/') This is my view def upload(request): form = MemeUploadForm(request.POST or None) if request.method == 'POST': print(request.user) if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.save() redirect('blog-index') return render(request, 'blog/upload.html', {'form': form}) This is my form class MemeUploadForm(ModelForm): class Meta: model = Meme fields = ['title', 'meme'] When I try to get the view to return the request.user it gives me Attribue error: User' object has no attribute 'get' but when I … -
RUN pip install -r requirements.txt does not install requirements in docker container
I am new to django, docker and scrapy and I am trying to run a django app that also uses scrapy (I basically create a django app that is also a scrapy app and try to call a spider from a django view). Despite specifying this scrapy in requirements.txt and running pip from the Dockerfile, the dependencies are not installed in the container prior to running 1python manage.py runserver 0.0.0.0:8000` and the django app fails during the system checks, resulting in the web container exiting because of the following exception: | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.7/threading.py", line 870, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run web_1 | self.check(display_num_errors=True) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check web_1 | include_deployment_checks=include_deployment_checks, web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks web_1 | return checks.run_checks(**kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks web_1 | new_errors = check(app_configs=app_configs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique web_1 | all_namespaces = _load_all_namespaces(resolver) web_1 | File … -
If I want to create table in django which database will be easier for CSV files and How to insert CSV file in django using pycharm?
I have 4 csv files with me for creating online test i need to make a table containing 1 column for question, 4 columns for 4 options of answer and last column for correct answer and then need to import in django so how to do? -
javascript function should switch between 2 images in a django template but doesn't
I have a js function that should switch between 2 images when a button is clicked. This function worked fine switching images in an html page but when I used it inside a django project fails to change images in the template. The initial situation was like this: the first image is displayed when the page is loaded, when the button is clicked it tries to change to the second images but fails to locate the source and gives a 404 error, a second click also fails to load the first image back; so I fixed the path to the second image, now pressing the button once correctly load the second image but when clicked again fails to load the first image, pressing the button a third time correctly loads the second image tho, a step foward. So I fixed the path to the first image (both images have the same path) and now clicking the button does nothing, the first images stands still. the path is this: ProjectName/AppName/static/AppName/dog1.jpg {%load static%} <img id="avatar" src="{% static 'AppName/dog1.jpg' %}" class="avatar"> <button id="Btn">Click me to change dogs<button> const dogs = [ "dog1.jpg", "/static/AppName/dog2.jpg" ]; const avatar = document.getElementById('avatar'); /*const dogs this way makes … -
how to connect to remote MS SQL Server using pyodbc
I am trying to connect to MS SQL Server 2016 Database using pyodbc with django. i tried on the localhost and it work fine but when i tried to connect to server on the same network it did not work and display the below error : InterfaceError at /connect/ ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I tried to check the ODBC Driver on the server and it display these drivers: ODBC Driver 13 for SQL Server SQL Server and i tried both of them but no success. views.py from django.shortcuts import render import pyodbc # from .models import Artist # Create your views here. def connect(request): conn = pyodbc.connect('Driver={ODBC Driver for SQL Server};' 'Server=AB-INT-SQL;' 'Database=testDB;' 'Trusted_Connection=yes;') cursor = conn.cursor() c = cursor.execute('SELECT * FROM Artist') return render (request,'connect.html',{"c":c}) connect.html {% for row in c %} {{ row }} {% endfor %} -
Save uploaded data to database in django
I do want to save all my excel-file data(that i uploaded) to database. {kindly ignore indentation problem},I also tried to change df to df.column.values but it also doesnt work .I am mainly facing problem in for loop .I am getting full dataframe in df variable but unable to save that in corresponding model. views.py : from django.shortcuts import render import openpyxl import pandas as pd from .models import dataset import csv def index(request): if "GET" == request.method: return render(request, 'myapp/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size xl = pd.ExcelFile(excel_file) names =xl.sheet_names df = xl.parse(names[0]) for row in df: created = dataset.objects.create( CGI=row[0], country=row[1], service_provider=row[2], zone=row[3], town=row[4], site_name=row[5], site_addr=row[6], landmark=row[7], latitude=row[8], longitude=row[9], shared=row[10], azimuth_angle=row[11], status=row[12], status_change_date=row[13],) return render(request, 'myapp/index.html', { }) models.py:: from django.db import models class dataset(models.Model): CGI = models.CharField(max_length=100) country = models.CharField(max_length=100, blank=True) service_provider = models.CharField(max_length=100, blank=True) zone = models.CharField(max_length=100, blank=True) town = models.CharField(max_length=100, blank=True) site_name= models.CharField(max_length=100, blank=True) site_addr= models.CharField(max_length=400, blank=True) landmark= models.CharField(max_length=100, blank=True) latitude= models.CharField(max_length=100, blank=True) longitude=models.CharField(max_length=100, blank=True) shared=models.CharField(max_length=100, blank=True) azimuth_angle=models.CharField(max_length=100, blank=True) status= models.CharField(max_length=100, blank=True) status_change_date= models.CharField(max_length=100, blank=True) I tried this code but its giving row value as country and I am not getting required result,plz help! -
Unable to rebuild elasticsearch indexes when using postgresql as database in Django project
I am playing with a Django project and elasticsearch(using django-elasticsearch-dsl , and till now i had been using sqlite as database for it. Now I thought to also try to use postgresql. The issue is that when I run the project with the sqlite everything is fine and data in elasticsearch are being populated correctly. Though when i make it to use postgresql (following this guide), then when i run python manage.py search_index --rebuild the following error comes up. elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [prettyUrl : {type=text}] [summary : {analyzer=html_strip, fields={raw={type=keyword}}, type=text}] [score : {type=float}] [year : {type=float}] [genres : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}] [id : {type=integer}] [title : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}] [people : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}]') This is the documents.py I am using. INDEX.settings( number_of_shards=1, number_of_replicas=1 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @INDEX.doc_type class MovieDocument(DocType): """Movie Elasticsearch document.""" id = fields.IntegerField(attr='id') prettyUrl = fields.TextField() title = fields.StringField( analyzer=html_strip, fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), } ) summary = fields.StringField( analyzer=html_strip, fields={ 'raw': fields.KeywordField(), } ) people = fields.StringField( attr='people_indexing', analyzer=html_strip, fields={ 'raw': fields.KeywordField(multi=True), 'suggest': fields.CompletionField(multi=True), }, multi=True ) genres = fields.StringField( attr='genres_indexing', analyzer=html_strip, fields={ 'raw': fields.KeywordField(multi=True), 'suggest': fields.CompletionField(multi=True), … -
Is source url case sensitive for html5 video tag?
A video file name with known name '/media/hello.' (case sensitive), but unknown case extension, such as '.mOv', '.MOV' or '.mov' Real file is '/media/hello.MOV'. The following video sometimes work if Django web server running from MacPro, but if running from Ubunto production server, video file name '/media/hellow.mov' does not work (More tests makes me more confused, as it seems Ubutntu production server status is unclear). <video id="video" defaultMuted autoplay playsinline controls> <source src="/media/hello.mov" type="video/mp4"> Your browser does not support the video tag. </video> I want to know if file extension is case sensitive. -
Rendering an image in django-tables2 on basis of value from Model
I am using django-tables2 and I am trying to display badges (css class) in my tables on basis of value being populated in the table. The problem i am facing is that i am only able to get my else badge. Probably, its not able to read and compare Sim.sim_status == 1. If my if is true, then i want that "Administrator" badge should be displayed. class ManageSimTable(tables.Table): status = tables.Column() def render_status(self): if Sim.sim_status == 1: return format_html('<span class="badge badge-danger">Administrator</span>') else: return format_html('<span class="badge badge-success">Operator</span>') -
No User matches the given query. Page Not found 404?
In my blog website I want to open another user's profile on clicking one of the links. But it keeps on showing 404 error saying No user matches the given query. Here's that link in a base.html <a href="{% url 'blogapp:userprofile' username=view.kwargs.username %}">{{ view.kwargs.username }}</a> Here's my url pattern for the function- path('userprofile/<str:username>/',views.userprofile,name='userprofile'), Here's my function view- @login_required def userprofile(request,username): user = get_object_or_404(User,username='username') return render(request,'blogapp/userprofile.html',{'user':user}) here's my template file {% extends 'blogapp/base.html' %} {% block content %} <div class="row"> <img src="{{ user.profile.image.url }}"> <div class="details"> <h2>{{ user.username }}</h2> <p>{{ user.email }}</p> </div> </div> <p style="margin-top: 10px; margin-left: 138px;">{{ user.profile.description }}</p> <hr> {% endblock %} {{ view.kwargs.username }} gives the perfect username that I search for. But problem is somewhere in the userprofile view. It goes to the perfect route http://127.0.0.1:8000/userprofile/username/ but it still shows a 404 error. -
DialogFlow fulfillment for Facebook Messenger Webview
Button to open web view on Facebook Messenger keeps opening a browser, on mobile and desktop I've created Facebook Messenger Bot, created a Test Page and a Test App, currently receiving webhooks from every message on DialogFlow, which respond correctly to the first message, in which i return a DialogFlow card, with a button, this button supposed to open a webview, but keeps opening a browser tab, on mobile and desktop, now, i'm aware for open a webview on desktop the are some modifications to the code that need to be made but mobile should be working by now and that is not the case. I'm following this flow: https://cloud.google.com/dialogflow/docs/images/fulfillment-flow.svg) This the webhook response sent from my Django instance to DialogFlow: "fulfillmentMessages": [ { "card": { "title": "Smoked Turkey Melt", "platform": "facebook", "subtitle": "card text", "imageUri": "https://ucarecdn.com/6a3aae10-368b-418f-8afd-ed91ef15e4a4/Smoked_Turkey_Melt.png", "buttons": [ { "type": "web_url", "text": "Get Recipe", "postback": "https://assistant.google.com/", "webview_height_ratio":"compact", "messenger_extensions": "true" } ] } }],} This is the view for responding to postback button: @csrf_exempt def get_recipe(request): """ """ response = render(request, "recipe_item.html") response['X-Frame-Options'] = 'ALLOW-FROM https://messenger.com/ https://www.facebook.com/ https://l.facebook.com/' response['Content-Type'] = 'text/html' return response And this is the Messenger Extensions SDK been installed on the HTML for the view corresponding to … -
Proper usage fetch js with django
I've got a problem when I am trying to use fetch with django. What I do wrong? # page.html <button id="btn">CLICK</button> <script> let url = '{{ url }}'; # /exp/ $('#btn').on('click', () => { console.log(url); fetch(url).then((data) => { console.log(JSON.stringify(data.json())) # {} }) }) </script> # views.py def page(request): if request.is_ajax(): return JsonResponse({'num': 123}) return render(request, 'exp/page.html', {'url': reverse('exp:page')}) -
How can i change is_staff to true ( is false by default) using django
is_staff is by default false and I want to change it to true. I have tried 4-5 methods but is giving an error. error: ValidationError at /accounts/login ["'false' value must be either True or False."] please help. -
NoReverseMatch - not a registered namespace
Hello, I am new to Django and I was working at my first project, but I got NoReverseMatch with Exception Value: 'hiring_log_app' is not a registered namespace in base.htlm which follows: href="{% url 'hiring_log_app:index' %}" >Hiring Log href="{% url 'hiring_log_app:topics' %}" >Topics I made sure my namespace was correct and I looked at the other topics already opened without figuring out how to solve the issue. I paste urls.py: from django.contrib import admin from django.conf.urls import include, url urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include ('hiring_log_app.urls', namespace='hiring_log_app')), ------ hiring_log_app/urls.py: """Define URL patterns for hiring_log_app""" from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^topics/$', views.topics, name='topics'), ] ----- views.py: from django.shortcuts import render from .models import Topic def index(request): """The home page for hiring_log_app""" return render(request, 'hiring_log_app/index.htlm') def topics(request): """ list of topics""" topics = Topic.objects.raw( "SELECT text FROM HIRING_LOG_APP_TOPIC;") context = {'topics' : topics} return render(request, 'hiring_log_app/topics.htlm', context) ------- Does anyone know where I am making a mistake? Thnaks a lot in advance, any help would be precious. Thanks again. -
Related resources on a nested URL in Django Rest Framework
I have two models, Foo and Bar. Bar has a foreign key to Foo. I have a ModelViewSet for Foo and I want the route /api/foos/<pk>/bars/ to return all the bars related to the given foo. I know this can be done using actions. For example class FooViewSet(viewsets.ModelViewSet): serializer_class = FooSerializer queryset = Foo.objects.all() @action(detail=True, methods=['GET']) def bars(self, request, pk): queryset = Bar.objects.filter(foo=pk) serializer = BarSerializer(queryset, many=True) return Response(serializer.data) @bars.mapping.post def create_bar(self, request, pk): request.data['foo'] = pk serializer = BarSerializer(request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) However, this feels like a lot of unnecessary boilerplate code. Is this possible to do in viewsets in a more convenient way? If not, what is the normal DRF way of doing it? A solution with a different URL is also acceptable for me as long as it minimizes boilerplate code. -
Django - how to add prefix to Mixin attributes (possible?)
There is too much relations and chains of actions in my project so I decided to eliminate some relations and use Mixins instead to keep things DRY. For example: class AddressMixin(BaseModel): address_zip = models.CharField(max_length=6, null=True, blank=True, verbose_name='PSČ') address_lat = models.DecimalField(max_digits=24, decimal_places=20, null=True, blank=True) address_lng = models.DecimalField(max_digits=24, decimal_places=20, null=True, blank=True) ... class Meta: abstract = True def some_method... There are many models using Address where I use this as a Mixin but sometimes, I need two or three types of addresses in one model. class Client(..): home_address = OneToOneField('addresses.OldAddressModel',...) work_address = OneToOneField('addresses.OldAddressModel',...) Here I can't just use AddressMixin like Client(AddressMixin,Model) since I need two different addresses. I would like to use AddressMixin two times with different prefixes, so in final model, there would be home_address_city and work_address_city. Is it possible to do that? I was thinking about some MixinFactory which takes Mixin and prefix and then it prefix all attributes (and maybe methods too but I can live without prefixed methods...). -
Django static files not loading with no error signs
When I run django server and try to load html files, it's not loading css files. I don't see any errors on terminal or the website itself - just loading animation in the background. After I set up static files in settings.py, I ran collectstatic on terminal which generated a new static file in main file area with all the css/js/fonts files. Thank you in advance! ~filepath ├── static/ │ ├── static/ │ │ └── admin/ │ │ └── css/ │ └── fonts/ │ └── images/ │ └── js/ ├── templates/ │ └── base.html/ │ └── _partials/ │ └── footer.html │ └── navbar.html │ └── pages/ │ └── index.html │ └── about.html ~settings.py STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'tvfb/static') ] ~urls.py (project) urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), ] ~urls.py (app) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] ~views.py def index(request): return render(request, 'pages/index.html') def about(request): return render(request, 'pages/about.html') ~base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,400i,700,700i,900,900i" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" … -
Django inlinefomrset delete
Here is a mystery. I cannot get the inlineformset deletion to work property. I have followed the docs to delete forms in my formset processing: # In my forms.py: def clean(self, *args, **kwargs): ''' Custom clean method to handle deletion ''' super(BaseDevelopmentTypeInlineFormSet, self).clean(*args, **kwargs) if any(self.errors): return # Everything beyond this point is clean cd = self.cleaned_data for form in self.forms: the_can_delete = self.can_delete # can_delete returns True the_should_delete = self._should_delete_form(form) # _should_delete returns False! form_fields = [ field for field in form.fields ] if self.can_delete and self._should_delete_form(form): continue form_cd = form.cleaned_data And, here are the relevant sections of the views.py: if development_type_formset.is_valid(): development_types_cd = development_type_formset.cleaned_data forms_marked_for_deletion = development_type_formset.deleted_forms assert False # forms_marked_for_deletion correctly returns the forms that have been marked for deletion the_kwargs = {'development_project': active_development_project } development_type_formset.save(**the_kwargs) assert False # the_development_types = [] is returned return HttpResponseRedirect(reverse('development:add_details', args = (the_id,))) After submitting, the redirection to another url happens successfully. But, when I go back, I still see the forms that should have been deleted. Originally, I thought the problem is with _should_delete, so I commented the part of the code calling _should_delete out. This made no difference. The redirection happened successfully, but deletion failed again. I have searched … -
How to iterate across HTML elements a specific number of times?
I'm having trouble coming up with working logic for the use case of repeating a set of HTML elements across columns. Simplified HTML as an example: {% for day in days %} <div class="container"> <div class="row"> {%for room in day.rooms%} <div class="col-sm-3"> <section class="box"> <h4>{{room.name}}</h4> {%for session in day.sessions%} {%if session.leftpos == room.leftpos %} {%if session.id%} <a href="session/{{session.id}}-{{session.title|slugify}}/">{{session.timeslot}}<br/><b>{{session.title}}</b><br/></a> {%else%} {{session.timeslot}} - <b>{{session.title}}</b> {%endif%} {%for speaker in session.speakers %}{%if loop.first%}{%else%}, {%endif%}<i><a href="speaker/{{speaker.id}}-{{speaker.name|slugify}}/">{{speaker.name}}</a></i>{%endfor%} {%endif%} {%endfor%} </section> </div> {%endfor%} </div> </div> {%endfor%} As this currently works, it looks for rooms depending on the sortkey, and lines up the talks corresponding with what rooms by going off that sortkey (if session.leftpos == room.leftpos). I have another variable (session.cross_schedule) which applies to talks which span across all 3 rooms, meaning that's the featured session. What I need to determine is how best to repeat the session information (everything within for session in day.sessions) across for room in day.rooms, but only if it's session.cross_schedule. Ideally, these cross-scheduled talks would appear at the proper time in the schedule rather than being separated from the rest. Any ideas or guidance would be much appreciated! -
Implement google autocomplete for address fields whilst using django models for forms
I have used django models to create the forms then loaded in the fields using crispy forms. The current implementation uses a standard text field to take in the address straight from the models. I would like to add the auto complete feature so that no incorrect addresses are entered in. I am unable to access the raw code as crispy forms loads everything in straight from the models so I cannot attach the code required for the autocomplete feature. I have tried to add a block in to manually add in the address however, this can only be added at the top or the bottom of the form. This is a problem as I need to add the address after the user entering the title of the listing. forms.py class ListingDevelopmentForm(forms.Form): title = forms.CharField() slug = forms.SlugField() description = forms.CharField(widget=forms.Textarea) first_line_address = forms.CharField() second_line_address = forms.CharField() postcode = forms.CharField() number_of_properties= forms.IntegerField() site_plan = forms.IntegerField() price = forms.DecimalField() rent = forms.DecimalField() ownership = forms.CharField() tenure = forms.CharField() from.html <form method="post" action='.' enctype='multipart/form-data'> {% csrf_token %} {{ form|crispy }} {% block main1 %} <!-- this is where I have added the block which allows me to manually add in the code … -
Is there a better way to display additional information from the Django model in the Django admin
Is there a better way to make the code less repetitive by moving the "CONN" to where is can still be used but where it only need to be written once. So I can still display the same information in the same fields in django admin. When I move "CONN" somewhere else the function stops working. and an error get displayed. Models.py class Host(models.Model): name = models.CharField(max_length=20) hostname = models.CharField(max_length=20) login = models.CharField(max_length=20) password = models.CharField(max_length=14, blank=True, null=True) conntype = models.CharField(max_length=7, choices=CONN_SELECT) def __str__(self): return self.name def status(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) status = conn.host_up() return status def cpu(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) return conn.get_host_info()[0] def memory(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) return conn.get_host_info()[1] def free_memory(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) return conn.get_host_info()[2] admin.py class HostAdmin(admin.ModelAdmin): list_display = ('name', 'hostname', 'conntype', 'status', 'cpu', 'memory', 'free_memory', 'options') -
I do a search on the site but gives an error No Programs matches the given query
I do a search on the site but gives an error " No Programs matches the given query." I want to do a search on the site, but after I enter the search query I get an error views.py def post_searchProgramm(request): queryProgramm = request.GET.get('searchProgramm') if queryProgramm: results = Programs.objects.filter(title__icontains=queryProgramm).order_by('-date') total_results = results.count() return render(request, 'programs/programms.html', { 'results': results, 'queryProgramm': queryProgramm, 'total_results': total_results}) else: messages.info(request, 'no results found for {}', format(queryProgramm)) urls.py path('searchProgramm/', views.post_searchProgramm, name='post_searchProgramm'), html template <form action="{% url 'post_searchProgramm' %}" method="get"> <input style=" height:30px; min-width:10px; width:auto; border: 3px solid #242424; border-radius: 15px ; background-color: #8B8B8B;" type="text" name="searchProgramm" value=""> <input style=" margin-left:30px; height: 30px ; min-width:10px; width:auto; border-radius: 30px ; background-color: #414141 ; border: 3px solid #242424;" type="submit" value="Найти"> </form> forms.py class SearchFormProgramm (forms.Form): queryProgramm = forms.CharField() -
How to configure vue for correct integration with django
I would like to write an application using django for Web-API and vue.js for frontend. I find many tutorials how to do it and decided to follow this one https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a Unfortunately I have a problem whith configuration of WebPack. It is written that I have to change my URL to http://0.0.0.0:8080. But when I did it, my application's page become blank. Expected result: I see Vue.js start page when running django server. How can I fix it?