Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Outputing a created object in javascript to a server side JSON file
I want to create a JSON file filled with an object that the client requests by "post" method. I've tried to assign value to an HTML tag, and access it from my views.py function. HTML file code: var myobj = {}; {% for f in foos %} {% for g in goos %} myobj["{{ g }}_{{ f }}"] = "{{ g.name }} {{ f.name }}" {% endfor %} {% endfor %} document.getElementById('myobj').value = myobj; views.py file code: def out_to_json(request): f = open(r"\main\jsons\first.json",'w+') _obj = request.POST['myobj'] f.write(str(_obj)) f.close() The result in my JSON file is [object Object]. Is running through all keys of my obj is necessary to access each value separately? I except the output of the full object as it is in the console. -
What is the issue that is causing Payload Error in JWT using Django
I want to authorise an API using login token using JWT but when i run the code it gives me invalid payload error.I have already added necessary modules that needed to be added. This is for a project that i am doing for a college purposes my idea is for a social site def post(self, request): token = request.headers['authorization'] data = {'token': token} payload_decoded = jwt.decode(token, settings.SECRET_KEY) try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user_id = valid_data['user'] except ValidationError as v: print("validation error", v) serializer = InstructorDetailsSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i am receiving payload error and want to actually resolve the issue. -
invalid literal for int() with base 10: - django
I am new to Django and trying to pass an author's name to a view and filter out quote objects based on the author's name. here are the codes: models.py class Program(models.Model): class Meta: verbose_name_plural = 'Program' program_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) program_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' program = models.ManyToManyField(Program, blank=False) course_code = models.CharField(max_length=10, default='', unique=True, validators=[MinLengthValidator(1)]) course_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) urls.py: urlpatterns = [ path('',views.programs,name='programs'), path('<slug:program_code_no>/',views.courses,name='courses'), ] views.py def programs(request): obj = Program.objects.all() paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/programs/index.html',context=all_details) def courses(request,program_code_no): obj = Courses.objects.filter(program=program_code_no) paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/courses/index.html',context=all_details) However, I get this error when I try to get http://127.0.0.1:8000/programs/P132/ ('P132' is a program_code object, already created) ValueError at /programs/P132/ invalid literal for int() with base 10: 'P132' Request Method: GET Request URL: http://127.0.0.1:8000/programs/P132/ Django Version: 2.2.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'P132' Exception Location: C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 966 Python Executable: C:\Users\Prabu\Anaconda3\envs\codeforcoder\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Prabu\\Desktop\\Django codeforcoder\\codeforcoder ' 'v1.0.1\\codeforcoder', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\python37.zip', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\DLLs', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\lib', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\lib\\site-packages'] -
How do i use Vue templates in Django?
This is my index page in django {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/MaterialDesign-Webfont/3.8.95/css/materialdesignicons.css"> <meta charset="UTF-8"> <title>My test</title> </head> <body> <div id="app"> <h1>TEST</h1> </div> {% render_bundle 'main' %} </body> </html> And this is a standard Vue navbar. <template> <v-app id="sandbox"> <v-navigation-drawer v-model="primaryDrawer.model" :clipped="primaryDrawer.clipped" :floating="primaryDrawer.floating" :mini-variant="primaryDrawer.mini" :permanent="primaryDrawer.type === 'permanent'" :temporary="primaryDrawer.type === 'temporary'" app overflow ><v-switch v-model="$vuetify.theme.dark" primary label="Dark" ></v-switch></v-navigation-drawer> <v-app-bar :clipped-left="primaryDrawer.clipped" app > <v-app-bar-nav-icon v-if="primaryDrawer.type !== 'permanent'" @click.stop="primaryDrawer.model = !primaryDrawer.model" ></v-app-bar-nav-icon> <v-toolbar-title>Vuetify</v-toolbar-title> </v-app-bar> </v-app> </template> The code is working, and i can see Vue being loaded when i open my Django site. The problem with this is that i don't know how to get them along. For example, i added a <h1>TEST</h1> but it does not appear when i load Vue, since the Vue part covers it. I also don't understand, if i have a conditional on my Django template, such as {% if user.is_authenticated %} i can't use it on Vue, because it won't be loaded by it. For example, i have a navbar. Instead of that navbar i want to use the below Vue navbar but i can't, because the current navbar has some links to parts of my site, and since … -
Open the xx.html file based on drop down menu from Navigation bar, code is written in Django-Python
The code is written in Django-Python. The project is created using the models in Django and shown in navigation as dropdown menu. The drop-down menu is shown using the Django-HTML as shown in following way: This code works well for dropdown menu. but I want to open the different project url based on click. I am not sure exactly how to assign id and use javascript to code do onclick bsed html loading !! I have tried some javascript code, but I am novice.. so If I put here.. it would be more confusing. <div class="dropdown-menu" id="navbarDropdown"> {% if project_records %} {% for p in project_records %} <a href="#" class="dropdown-item"> {{ p.pName }} </a> {% endfor %} {% endif %} </div> I expect that projectB.html will be loaded if click projectB in dropdown menu in navigation bar. -
How to redirect to a newly created object in Django?
I'm trying to redirect to the created object by filling the form below. I've tried the solutions that I found on these posts: How to redirect to a newly created object in Django without a Generic View's post_save_redirect argument and here: Redirection after creating an object, Django Sometimes it just don't redirect and some other times it says property was not initiated. What am I doing wrong here? # views.py def add_property(request): if request.method == 'POST': property_add_form = PropertyAddForm(request.POST, request.FILES) if property_add_form.is_valid(): property = property_add_form.save() # formset = ImageFormset(request.POST or None, request.FILES or None, instance=property) # if formset.is_valid(): print("Sucesso") return HttpResponseRedirect(reverse('property:property_detail', kwargs={'property':property.id})) else: property_add_form = PropertyAddForm() print("Error") context = { 'property_form':property_add_form, 'title':"Add Property", } return render(request, 'properties/add-property.html', context) . #urls.py url(r'^add-property/', views.add_property, name='add_property'), -
uWSGI server sometimes hung up for unknown reasons
Problem I've operated Django + uWSGI apps for a year on AWS, and it was working well until two weeks ago, but I run into the problem that the specific uWSGI process sometimes hung up and rarely recover automatically. Strangely enough, I'm always running three uWSGI servers on the same EC2 instance, but only the specific (most accessed) process always hung up, and the rest two uWSGI processes never hung up and continue to respond to HTTP requests even during the error. Even though they work on the same hardware and network, and are connected to same MySQL/Redis server. uWSGI dumped the following "OSError: write error" message during it was stuck, (but I think the message doesn't seem the useful information...) Sat Aug 17 15:44:30 2019 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during POST /XXXX(172.XXX.XXX) OSError: write error [pid: 2131|app: 0|req: 921/7007] 172.XXX.XXX.XXX () {62 vars in 1416 bytes} [Sat Aug 17 15:44:30 2019] POST /XXXX => generated 0 bytes in 28 msecs (HTTP/1.1 200) 5 headers in 0 bytes (0 switches on core 0) and the Django dumped the following 500 error message. 2019/08/17 15:43:32 [error] 2265#0: *13198 upstream timed out (110: Connection timed out) while reading response … -
Django: QuerySet with ExpressionWrapper
I currently try to get max_total_grossfrom all tickets within an event. That's how far I came but it doesn't work yet. tickets = event.tickets.all().annotate( max_total_gross=Sum(ExpressionWrapper( F('quantity') * F('price_gross'), output_field=IntegerField(), )) ).values( 'max_total_gross' ) Goal: Sum( price_gross_x_quantity_ticket_1 + price_gross_x_quantity_ticket_2 + price_gross_x_quantity_ticket_3 + [...] ) Here my ticket model: class Ticket(TimeStampedModel): event = models.ForeignKey( 'events.Event', on_delete=models.CASCADE, related_name='tickets' ) # CASCADE = delete the ticket if the event is deleted price_gross = models.PositiveIntegerField( verbose_name=_("Price gross"), help_text=_("Includes tax if you set any.") ) quantity = models.PositiveIntegerField( verbose_name=_("Quantity"), validators=[MinValueValidator(1), MaxValueValidator(100_000)], ) # [...] -
Get Object by pk in URL in Django Rest Framework
I want to retrieve objects from the ORM by the "pk" in URL. Here's what I am trying This is my Url: path('api/dispatchhistoryitem/<int:pk>/', views.dispatchhistoryitemsview.as_view(), 'dispatchhistoryitem'), Views.py class dispatchhistoryitemsview(ListAPIView): queryset = ItemBatch.objects.all() serializer_class = holdSerializer def get(self, request, pk, *args, **kwargs): items = get_object_or_404(ItemBatch, id=self.kwargs.get('pk')) serializer = holdSerializer(items) return Response(serializer.data) Serializer.py class holdSerializer(serializers.ModelSerializer): class Meta: model = ItemBatch fields = "__all__" But when I run this it says : ValueError at /api/dispatchhistoryitem/43/ dictionary update sequence element #0 has length 1; 2 is required What is that I am doing wrong here ? Please Help! -
filter data according to dates
I want to filter data according to a given date range picked up in templates by user.I have a list I want that if User enter date and it matches with the date in a list then that data should be shown .But problem in my code is that it doesn't filter actually nothing happens so please help me.And my date is in "%m %dd %yyyy" format.Thank you in advance. javascript $(function() { var oTable = $('#datatable').DataTable({ "oLanguage": { "sSearch": "Filter Data" }, "iDisplayLength": -1, "sPaginationType": "full_numbers", }); $("#datepicker_from").datepicker({ showOn: "button", buttonImageOnly: false, "onSelect": function(date) { minDateFilter = new Date(date).getTime(); oTable.fnDraw(); } }).keyup(function() { minDateFilter = new Date(this.value).getTime(); oTable.fnDraw(); }); $("#datepicker_to").datepicker({ showOn: "button", buttonImageOnly: false, "onSelect": function(date) { maxDateFilter = new Date(date).getTime(); oTable.fnDraw(); } }).keyup(function() { maxDateFilter = new Date(this.value).getTime(); oTable.fnDraw(); }); }); minDateFilter = ""; maxDateFilter = ""; $.fn.dataTableExt.afnFiltering.push( function(oSettings, aData, iDataIndex) { if (typeof aData._date == 'undefined') { aData._date = new Date(aData[2]).getTime(); } if (minDateFilter && !isNaN(minDateFilter)) { if (aData._date < minDateFilter) { return false; } } if (maxDateFilter && !isNaN(maxDateFilter)) { if (aData._date > maxDateFilter) { return false; } } return true; } ); template.html <p id="date_filter"> <span id="date-label-from" class="date-label">From: </span><input class="date_range_filter date" type="date" id="datepicker_from" /> <span … -
How to specify GROUP BY field in Dajngo ORM?
I have the following working SQL statement: SELECT id FROM ops_kpitarget WHERE (site_id = 1 AND validFrom <= "2019-08-28") GROUP BY kpi_id HAVING validFrom = (MAX(validFrom)) But I cannot get this to work inside Django ORM. The best I got was the code below, but then the database is complaining that it is missing a GROUP BY clause to make HAVING work. How can I get the same query with specifying "kpi_id" as the GROUP BY clause using Djangos ORM? Any ideas? KpiTarget.objects .filter(validFrom__lte=fromDate) .values("id", "kpi") .filter(validFrom=Max("validFrom")) ... which translates to: SELECT "ops_kpitarget"."id", "ops_kpitarget"."kpi_id" FROM "ops_kpitarget" WHERE "ops_kpitarget"."validFrom" <= 2019-08-14 HAVING "ops_kpitarget"."validFrom" = (MAX("ops_kpitarget"."validFrom")) I played around with annotate but this is not really giving me what I want... -
How to correct limit values in Django models
Please help to understand how to correct limit for "team" field by "company" team? It's my code : class CustomCompany(models.Model): company_name = models.CharField(max_length=30, default="None", unique=True ) class CustomTeam(models.Model): team_name = models.CharField( max_length=30, default="None" ) company_name = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, related_name='company_name+', to_field='id', ) class CustomUser(AbstractUser): phone = models.CharField(max_length=20, blank=True) company = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, default='None', to_field='company_name', related_name='company' ) team = models.ForeignKey(CustomTeam, on_delete=models.CASCADE, default=1, related_name='team_name+', limit_choices_to={"company_name_id":"company_id"}, ) And problem in last string (limit_choices_to) How to correct do this, limit teams by company? Current error, if it's required the next : invalid literal for int() with base 10: 'company_id' -
How to Retrive previously entered form in django?
I want the user to login and fill the form and when he login again the form must be filled with previously entered data how to make it possible .Thanks in advance I tried accessing with request.user but it didn't work @login_required def surveyform(request): form = SurveyForm(request.POST,request.FILES,instance = request.user) if request.method == "POST": form = SurveyForm(request.POST,request.FILES,instance = request.user) if form.is_valid(): form.save() email = form.cleaned_data.get('email') messages.success(request,f'Thanks for your feedback!') else: form = SurveyForm(instance = request.user) context={ 'form' : form } return render(request,'surveyform/form.html',context) I need the form to be pre occupied with previously entered data if anyone know the solution plzz help me out I am not declaring each html field I used {{ form }} to display the form in html -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 874: '><li><span'. Did you forget to register or load this tag?
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 789 "> < li>< span" Did you forget to register or load this tag? legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for(var i=0;i<datasets.length; i++){%><li><spanstyle="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>' -
How to format json response in django?
I am retrieving data from multiple tables in Django. my current response is : { "status": 0, "message": "Client details retrived successfully...!!!", "results": [ { "id": 11, "client_id": "CL15657917080578748000", "client_name": "Pruthvi Katkar", "client_pan_no": "RGBB004A11", "client_adhar_no": "12312312313", "legal_entity_name": "ABC", "credit_period": "6 months", "client_tin_no": 4564565, "client_email_id": "abc@gmail.com", "head_office_name": "ABC", "office_name": "asd234", "office_email_id": "zxc@gmail.com", "office_contact": "022-27547119", "gst_number": "CGST786876876", "office_country": "India", "office_state": "gujrat", "office_district": "vadodara", "office_taluka": "kachh", "office_city": "vadodara", "office_street": "New rode 21", "office_pincode": 2344445, "contact_person_name": "prasad", "contact_person_designation": "DM", "contact_person_number": "456754655", "contact_person_email": "asd@gmail.com", "contact_person_mobile": "5675545654", "created_at": "2019-08-14T14:08:28.057Z", "created_by": "Prathamseh", "updated_at": "2019-08-14T14:08:28.057Z", "updated_by": "prasad", "is_deleted": false }, { "id": 11, "user_id": "CL15657917080578748000", "bank_details_id": "BL15657917080778611000", "bank_name": "Pruthvi", "branch": "vashi", "ifsc_code": "BOI786988", "account_number": 56756765765765, "account_name": "Pruthvi", "is_deleted": false }, { "id": 10, "document_details_id": "DL15657917080808598000", "user_id": "CL15657917080578748000", "document_type": "Pruthvi ID", "document": "www.sendgrid.com/pan", "is_deleted": false } ] } Expected Response : I am getting the queryset form db in models.py and i am sending it to the views.py and i am iterating over the dict but not getting the expected response. views.py @csrf_exempt def get_client_details(request): try: # Initialising lists for storing results result = [] temp_array = [] # Getting data from request body client_master_dict = json.loads(request.body) # Response from get client data records = ClientDetails.get_client_data(client_master_dict) # Create response … -
using attr in elasticsearch field for indexing
/.models.py lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) @property def type_to_string(self): x1 = Locations.objects.all() return {'lat': self.lat, 'lon': self.lng} ./documents.py loc1 = fields.GeoPointField(attr='type_to_string') fields = [ 'name', 'address', 'provider', ] I want to add loc1 field in fields section so that I can index it and use it in elasticsearch. But when I put loc1 in fields section I get error TypeError: unhashable type: 'GeoPointField' How can I add rectify this error. -
PyInstaller Django compilation <frozen importlib._bootstrap>
I'm trying to compile my django Project With PyInstaller, cuz of be safe in a shared disk driver That every One can review My Code. and when Compile I get this output: (env) D:\__DEV__>pyinstaller Chortke/manage.py --onedir 222 INFO: PyInstaller: 4.0.dev0+46286a1f4 222 INFO: Python: 3.7.4 (conda) 222 INFO: Platform: Windows-10-10.0.16299-SP0 222 INFO: wrote D:\__DEV__\manage.spec 222 INFO: UPX is not available. 239 INFO: Extending PYTHONPATH with paths ['D:\\__DEV__\\Chortke', 'D:\\__DEV__'] 239 INFO: checking Analysis 239 INFO: Building Analysis because Analysis-00.toc is non existent 239 INFO: Initializing module dependency graph... 244 INFO: Caching module graph hooks... 256 INFO: Analyzing base_library.zip ... 6561 INFO: Caching module dependency graph... 6664 INFO: running Analysis Analysis-00.toc 6679 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\users\mab\.conda\envs\env\python.exe 7249 INFO: Analyzing D:\__DEV__\Chortke\manage.py 7307 INFO: Processing pre-find module path hook distutils 7311 INFO: distutils: retargeting to non-venv dir 'c:\\users\\mab\\.conda\\envs\\env\\lib' 8887 INFO: Processing pre-find module path hook site 8887 INFO: site: retargeting to fake-dir 'c:\\users\\mab\\.conda\\envs\\env\\lib\\site-packages\\PyInstaller\\fake-modules' 15264 INFO: Processing module hooks... 15264 INFO: Loading module hook "hook-distutils.py"... 15264 INFO: Loading module hook "hook-django.core.cache.py"... 15439 INFO: Loading module hook "hook-django.core.mail.py"... 15601 INFO: Loading module hook "hook-django.core.management.py"... 15634 INFO: Import to be excluded not found: 'tkinter' 15635 INFO: Import to be excluded … -
New project not finding my reusable app's admin template override which I installed using pip
I had created a django-app which possesses only admin panel, some tables and no front views. Then I created its build with PYPI docs and uploaded it to PYPI. After that I created a new django project and installed my reusable app through pip. The problem is, I override few of admin templates and they were working fine in the project I created this app, but not working when I installed it through pip in the new Project. Note: This is the only app in the new project and the User is a CustomUser. I tried Project not finding my reusable app's admin template override, but nothing happened, then in the new project, I created a templates folder containing admin folder which contains the admin templates (same name files) I override, the folder structure is like: my_new_project/ |_ my_new_project/ |_ __init__.py |_ settings.py |_ urls.py |_ manage.py |_ templates/ |_ admin/ |_login.html and the code of login.html file is: {% extends "myapp: myapp/login.html" %} I got invalid syntax error, then I also tried: {% extends "myapp/admin/login.html" %} still nothing happened. I expected to see the changes I made in the admin templates in my reusable app to reflect in the … -
How to display image in a HTML page the Django Framework?
I have a webpage which will show the logo of an music album and the mark the favorite songs of the album. For that I've added a database field named album_ logo and add the path name of the images folder "C:\Python Projects\Test_App\website\music\static\music\Image" in database. But in the HTML page neither the images are rendering. I've tried loading the static files in the html page and giving the full path. Here is the attached code snippet. <body> {% load static %} <img src = "{{album.album_logo}}"> <h1>{{album.album_title}}</h1> <h3>{{album.artist}} - {{album.genre}}</h3> {% if error_message %} <p>{{error_message}}</p> {% endif %} <form action="{% url 'music:favourite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}" /> <label for="song{{forloop.counter}}"> {{song.song_title}} {% if song.is_favourite %} <img src="{% static 'music/fav.png' %}"> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favourite"> </form> </body> -
Django validate DateTime
I have booking API endpoint and i want to check each time user want booking hall if DateTime and hall that user want booking is available. I try this queryset in validate in Serializer to check if this time and hall is booking or not def validate(self, data): BookingModel.objects.filter(date_time__exact=data['date_time']).get(hall_id__iexact=data['hall']).exists() but it give this Error: BookingModel matching query does not exist. -
What is the difference of form_class and model in django CreateView?
why only "form_class" work but using "model" with "fields" not work error : 'ModelFormOptions' object has no attribute 'private_fields' -
When I send a letter to the mail gives an error 'tuple' object has no attribute 'get'
I do so that after registration to the post office a letter is sent but it gives me an error The letter arrives in the mail, but gives an error and should redirect to another url 'tuple' object has no attribute 'get' my Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\deprecation.py" in call 96. response = self.process_response(request, response) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\middleware\clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /register/ Exception Value: 'tuple' object has no attribute 'get' Settings EMAIL_HOST = 'smtp.mail.ru' EMAIL_PORT = 2525 EMAIL_HOST_USER = "itraptor@mail.ru" EMAIL_HOST_PASSWORD = "labrador75" EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] context = {'form': form, 'username': username, 'password1': password1, 'password2': password2, 'email': email} if form.is_valid(): form.save() return redirect('/loginNow/') , send_mail('Тема', 'Тело письма', settings.EMAIL_HOST_USER, [email]) else: form = RegisterForm() context = {'form': form } return render(request, 'registration/registred.html', context) -
Why is this code failing in a 32-bit enviroment?
I'm moving a very simple django app from my desktop pc to a virtualbox server. I have copied the hole proyect, except for the virtualenv sources folder. Then, i've created a virtualenv and installed dependencies in the same way. When i run manage.py a circular reference error cames in claming The included URLconf 'pmkwebPdf.urls' does not appear to have any patterns in it This is the project dir: PmkwebPdf media pmkwebPdf __init.py settings.py urls.py wsgi.py src migrations ... processor ... __init__.py admin.py apps.py models.py tests.py urls.py views.py templates ... venv ... db.sqlite3 manage.py It's certanly an error with the urlpatterns. So i did this. pmkWebPdf.urls from django.contrib import admin #from django.urls import path, include urlpatterns = [ #path('', include('src.urls')), path('admin/', admin.site.urls), ] In this file, if i remove the path('', include('src.urls')), and its dependecies the error is gone. src/urls.py from django.conf.urls.static import static from django.urls import path from pmkwebPdf import settings #from src.views import index urlpatterns = [ #path('', index, name='index') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) After leaving the pmkWebPdf.urls without the lines commented, i discovered that, in this file, if i leave the urlpatters empty and remove the from src.views import index line. The server runs. I've created the … -
How auto create model in Django?
i has model where i add writes , how at add write auto- create model in other apps with name of this added record? In which I can create entries -
Django forms : how to use Html and css template forms
How can I use (Html+CSS Template forms ) in django ? Hi Guys. I really don't like django forms appearances or even crispy_forms so I downloaded a form Html and Css from this website "colorlib.com" and pasted in my 'signup.html', and 'signup.css' ,form showed up but after filling from and sending it it shows error . I use CBVs .... I'm sure view and url are correct but I think I have to change tags in html to django Tags, Thank you in advance :Btw I use bootstrap , do i need change its href This is form template in django which is very simple and I need more beautiful one : <!-- templates/signup.html --> {% extends 'base.html' %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} Html of form (https://codepen.io/colorlib/pen/aaaoVJ) which i like to use <!-- Author: Colorlib Author URL: https://colorlib.com License: Creative Commons Attribution 3.0 Unported License URL: http://creativecommons.org/licenses/by/3.0/ --> <!DOCTYPE html> <html> <head> <title>Creative Colorlib SignUp Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- Custom Theme files …