Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the background color of the top menu dynamically?
I am developing the website on python(Django). I am getting some difficulties to change the background color of the top menu on every page. What I am doing is, I have an index.html page and templates which are aboutus, contactus and service. When I am on the home page then I am getting the gray background of the menu which is correct. Now I am on aboutus and I have to change the menu color from gray to black but I am getting the only gray. So I want to know how do I change the class or override the CSS? Should I need to add the class to the body and then override the menu BG? How do I added the class to the body on each page dynamically? index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title%}Home{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'css/style.css'%}" type="text/css"> </head> <body> <div class="Wrpper"> <header class="bg_gray"><!--top menu code--></header> {% block content %} <!-- template code --> {% endblock %} <footer><!--footer code--></footer> </div> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> </body> </html> style.css .bg_gray{background-color: #ccc;} .bg_black{background-color: #000;} aboutus.html … -
Request method mapping is happening after permission check
So, this issue(may not be as issue and error from my side) is something that i faced while testing of my class based views. I had a view that creates and updates user as shown below. class UserViewSet(ViewSet): def check_permissions(self, request): print("Action = ", self.action) if self.action == 'create_user': return True return super().check_permissions(request) def create_user(self, request): # user creation code def update(self, request): #user update code And create_user was mapped with POST method and update was mapped with PUT method. So, my need was that for create_user action no permission is required and for update, user should be authenticated. Overriding check_permssion did the job. Now, when i was testing the create_user end point. I wrote a test that tries to create user using some method other than POST. I expected that the response should be HTTP_405_METHOD_NOT_ALLOWED. def test_create_user_with_invalid_method(self): data = self.user_data response = self.client.put(self.url, data) self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) But the response was HTTP_401_UNAUTHORIZED. And the action variable was set as None. My url mapping is like this: url(r'^account/register/$', UserViewSet.as_view({"post": "create_user"}),name="account_register_view"), url(r'^account/update/$', UserViewSet.as_view({"put": "update"}), name="account_update_vew"), So looking at this, i thought djago is either doing the mapping of request(method, url) to action either after checking permission or doing it before but setting … -
Converting relative url path to absoliute url for xhtml2pdf
I am very inexperienced in this so I have problem understanding documentation provided for xhtml2pdf since it is very vague in details. Please tell me what I am doing wrong. According to documentation to convert relative url path to absolute I need to use provided function: def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path I added exact same function to my views.py and using this function for generating pdf (also in views.py, almost directly taken form docs): def PGP_result(request): data = request.session['form_data'] lietuvosPgp = data['LtPGP'] valstybe = data['pVal'] kastai = data['iKastai'] rezultatas = data['result'] today = timezone.now() params = { 'LtPgp': lietuvosPgp, 'Valstybe': valstybe, 'Kastai': kastai, … -
Deploying django project on digital ocean with apache and mod_wsgi
Deploying django project on DigitalOcean with apache and mod_wsgi I'm using Ubuntu 16.04 apache 2.4 python3.5.2 django==1.11 Firebase Installed Apache : https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-server-on-ubuntu-16-04 sudo apt-get install build-essential libssl-dev libffi-dev python3-dev sudo apt-get install libapache2-mod-wsgi-py3 sudo apt-get install aptitude sudo aptitude install apache-dev pip3 install mod-wsgi Installed all pip3 modules And apache is running gave permission to www folder as sudo chown -R www-data:www-data www/ My wsgi.py file as import os import sys sys.path.append('/var/www/myproject') sys.path.append('/usr/local/lib/python3.5/dist-packages') os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") #also tried from django.core.wsgi import get_wsgi_application application = get_wsgi_application() apache config file 000-default.conf <VirtualHost *:80> ServerName www.mysite.in ServerAlias mysite.in ServerAdmin myemail@abc.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.in python-path=/var/www/myproject python-home=/usr/local/lib/python3.5/dist-packages WSGIProcessGroup mysite.in WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py </VirtualHost> Ran command after modifying 000-default.conf file sudo service apache2 reload sudo a2ensite 000-default.conf sudo service apache2 reload sudo systemctl restart apache2.service My project folder structure is . ├── __pycache__ │ └── config.cpython-35.pyc ├── myproject │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ └── settings.cpython-35.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myprojectapp │ ├── admin.py │ ├── __init__.py │ ├── mail_html.py │ ├── migrations │ │ └── __init__.py … -
Issue for mysql python on installing
I am trying to run a python django project as required version of 2.7 of python , django of 1.8 and mysql 5.7, so while installing the MySQL-python of 1.2.5, buidling the wheel its breaking and getting the below error Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: error: command 'cc' failed with exit status 1 i link the mysql@5.7, so when i check which mysql_config i am getting /usr/local/opt/mysql@5.7/bin/mysql_config. i have tried most of the solutions, i have installed mysql through brew. tried installing mysqlclient in virutal env before django gets installed , but when i tried installing mysqlclient in venv i am getting the same error Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: error: command 'cc' failed with exit status 1 i am not able to figure whats the issue, and i am new to python. any help will be appreciated. -
Not able to establish self join in Django App
//I want to dislay name of the sponsors which are also customers. We can under stand this from the data model. In the view page i want to show name of the sponors but i am not able to establish the join between sponsor and its name. Model.py ----------- class customer(models.Model): company = models.CharField(max_length=3) mobile = models.CharField(max_length=10) name = models.CharField(max_length=100) sponsor = models.CharField(max_length=10) # Sponsor is also a customer like employee and manager address1 = models.CharField(max_length=200) country = models.CharField(max_length=101) state = models.CharField(max_length=100) city = models.CharField(max_length=100) zip = models.CharField(max_length=6) email = models.EmailField(max_length=100) status = models.CharField(max_length=1) creator = models.CharField(max_length=20) cretime = models.DateTimeField(default=datetime.now) updator = models.CharField(max_length=20) updtime = models.DateTimeField(default=datetime.now, blank = True ) views.py -------- from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect import datetime from .models import customer from django.db import transaction from django.contrib import messages import re def customer_view(request): name1 = str(request.GET.get('nam')) mobile1 = str(request.GET.get('mob')) if (name1 == 'None' and mobile1 == 'None'): customers_list = customer.objects.all().order_by('-cretime') elif (name1 == '' and mobile1 == ''): customers_list = customer.objects.all().order_by('-cretime') elif (name1 != '' and mobile1 == ''): customers_list = customer.objects.filter(name=name1).order_by('-cretime') elif (name1 == '' and mobile1 != ''): customers_list = customer.objects.filter(mobile=mobile1).order_by('-cretime') else: customers_list = customer.objects.filter(mobile=mobile1) & customer.objects.filter(name=name1).order_by('-cretime') sponsors = customer.objects.all().distinct('mobile') ctx … -
Production ready Python apps on Kubernetes
I have been deploying apps to kubernetes from last 2 years. And in my org all our apps(especially stateless) are running in kubernetes. I still have a fundamental question, just because very recently we found some issues with respect to our few python apps. Initially when we deployed, our python apps(Written in Flask and Django), we ran it using python app.py. Its known that, because of GIL, python really doesn't have support for system threads, and it will only can serve one request at a time, but in case the one request is CPU heavy, it will not be able to process further requests. This is causing sometimes the health API to not work. We have observed that, at this moment, if there is a single request which is not IO and doing some operation, will hold the CPU and cannot really process another request in parallel. And since its only doing less operations, we have observed there are no increase in the CPU utilization also. This has an impact on how HorizontalPodAutoscaler works, its unable to scale the pods. Because of this we started using uWSGI in our pods. So basically uWSGI can run multiple pods under the hood … -
django auto check if i save it to database
here is my html <input type="checkbox" value="1" name="Visual" id="visual"> <input type="checkbox" value="1" name="Tuberculosis" id="Tuberculosis"> <input type="checkbox" value="1" name="Skin" id="Skin"> <script type="text/javascript"> $('#checkbox-value').text($('#checkbox1').val()); $("#checkbox1").on('change', function() { if ($(this).is(':checked')) { $(this).attr('value', 'true'); } else { $(this).attr('value', 'false'); } $('#checkbox-value').text($('#checkbox1').val()); }); </script> this is my views Visual= request.POST['Visual'] Tuberculosis= request.POST['Tuberculosis'] Skin= request.POST['Skin'] V_insert_data = StudentUserMedicalRecord( Visual=Visual, Tuberculosis=Tuberculosis,Skin=Skin ) V_insert_data.save() why is it everytime i save the data on my database, the visual,Tuberculosis,Skin are automatically checked eventhough i didnt check it when i was saving it. or i think my javascript is wrong? -
Not able to save custom profile data on to django model
I have a custom userprofile model and edit profile form. But when I try to save the data into the Profile model using edit profile form. it is not saving into the Profile model. But, as I'm using Django user model, it is saving first_name, last_name, email into the Django user model after saving from EditProfile view I have already created a view function to save the data models.py class Profile(models.Model): user_name = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=100, verbose_name='first_name',blank=True,null=True) last_name = models.CharField(max_length=100,blank=True, null=True) email = models.EmailField(blank=True, null=True, default='name@name.com') date_of_birth = models.DateTimeField(auto_now=False) phone_number = PhoneField(blank=True, help_text='Contact phone number') def __str__(self): return '{} {} {} {} {} {}'.format(self.user_name,self.first_name, self.last_name, self.email, self.date_of_birth, self.phone_number) forms.py class DateInput(forms.DateInput): input_type = 'date' class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'first_name', 'last_name', 'email', 'date_of_birth', 'phone_number', ) widgets = { 'date_of_birth':DateInput(), } views.py @login_required def EditProfile(request): if request.method == "POST": form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('view_profile') else: form = EditProfileForm(instance=request.user) args ={'form':form} return render(request, 'home/editprofile.html', args) editprofile.html {% extends 'home/base.html' %} {% load crispy_forms_tags %} {% block body %} <div class="row justify-content-center"> <div class="col-6"> <div class="card"> <div class="card-body"> <h3>Edit profile</h3> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Save</button> </form> … -
How to get today week no of year in django
i trying to get today week no of year from datetime import datetime import datetime from time import strftime from dateutil import parser today_date = strftime("%V") today_week = parser.parse(today_date) today_week = today_week.weekday() -
Django is sending me an email about "Invalid HTTP_HOST header"
I have website that using django on DigitialOcean. Django is sending me an email with title Invalid HTTP_HOST header: 'url.ml'. You may need to add 'url' to ALLOWED_HOSTS. But I don't want to add this, I added my own domains and ip address. I have list of questions Why is django sending me this email? Bots are attacking to my site? If so how they do that? How can I prevent this? -
Django Hide Posts in UI per User without affecting database
I have an app that display all newsitems having model like: class NewsItem(models.Model): url = models.CharField(max_length=500, default="",unique=True) title = models.CharField(max_length=500, default="") hacker_news_url = models.CharField(max_length=500, default="") posted_on = models.DateTimeField(default=datetime.now) # posted_on = models.CharField(max_length=100,default="") upvote_count = models.IntegerField(default=0) comment_count = models.IntegerField(default=0) contents=models.TextField(default="") UI: I had already setup the default django authentication to view this page. The ui has hide button for each post. So the problem is if the logged in user hides the post, it must be hidden for that user only (even after page refresh) without deleting from database. How to do that? Help Please! This is my views.py: @login_required(login_url='/accounts/login') def index(request): context={'news_items':NewsItem.objects.all().order_by('posted_on')} return render(request, "hello.html", context) -
Can I use 'boto3' library along with the S3Boto3Storage backend from 'django-storages' library?
I'm using S3Boto3Storage to direct my media storage to AWS S3 by installing pip library django-storages. And I want to add a view for putting rows of DynamoDB and I found that I should install boto3 library. Are these libraries compatible? -
django: how to display image in html_email
this is my html <!DOCTYPE html> {% load static %} <html > <head> <title>Email</title> </head> <body> <br><br><br> <img src="{% static 'logo.png' %}" title="" style="height: 6.1rem;">School Collebes <br><br> <p>To: {{ email }}</p> <p>Your Registration has been approved. Please use this {{ email }} as your username and {{ password }} as your password. You may now start enrolling your student using this link https://....</p> <br><br><br> <h2>REGISTRAR</h2> </body> </html> and this is my admin.py @admin.register(ParentsProfile) class ParentsProfile(admin.ModelAdmin): list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request') ordering = ('Request',) search_fields = ('Request',) actions = ['Send_Email','Send_Email_Disapproved'] def Send_Email(self, request, queryset): for profile in queryset: context = { 'email': profile.Father_Email, 'password': profile.Parent_Password, } html_message = render_to_string('Homepage/email.html',context=context) send_mail(subject="Invite", message='',html_message=html_message, from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) i just want to display what i desire image in my email_html, but i dont know the reason why i cant display an image. did i something wrong with my code? im pretty sure that the image i declare in my email_html are in correct path. -
form data getting displayed in url despite using http method post
i am learning django app development and have written a simple code to add two numbers. the form data is geting displayed in the url despite using http request method post. i dont want form data to be displayed in the url. Kindly help. views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html',{'name':'pavan sunder'}) def add(request): val1 = int(request.POST["num1"]) val2 = int(request.POST["num2"]) res = val1 + val2 return render(request, 'result.html',{'result':res}) home.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="add" method='POST'> {% csrf_token %} Enter 1st number:<input type="text" name="num1"><br> Enter 2nd number:<input type="text" name="num2"><br> <input type="Submit"> </form> {% endblock %} </body> </html> results.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} Result:{{result}} {% endblock %} </body> </html> ```[![formdata in url][1]][1] [1]: https://i.stack.imgur.com/YWQcD.png -
Displaying JSON Data from API in Django
I am looking for a simple way to display JSON values coming from an API in a Django project. I've got everything working to read the JSON data into an object and store as variables, etc. but I am wondering how to make a dynamic way to display the values from the JSON Object. Say for example the JSON looks like this { "status":"OK", "copyright":"Copyright (c) 2017 Pro Publica Inc. All Rights Reserved.", "results":[ { "num_results": 10, "offset": 0, "bills": [ { "bill_id": "hr2739-113", "bill_type": "hr", "number": "H.R.2739", "bill_uri": "https://api.propublica.org/congress/v1/113/bills/hr2739.json", "title": "Efficient Use of Government Spectrum Act of 2013", "sponsor_title": "Rep.", "sponsor_id": "M001163", "sponsor_name": "Doris Matsui", "sponsor_state": "CA", "sponsor_party": "D", "sponsor_uri": "https://api.propublica.org/congress/v1/members/M001163.json", "gpo_pdf_uri": "http://www.gpo.gov/fdsys/pkg/BILLS-113hr2739ih/pdf/BILLS-113hr2739ih.pdf", "congressdotgov_url": "https://www.congress.gov/bill/113th-congress/house-bill/2739", "govtrack_url": "https://www.govtrack.us/congress/bills/113/hr2739", "introduced_date": "2013-07-18", "committees": "House Armed Services Committee", "committee_codes": ["HSAS","HSIF"], "subcommittee_codes": ["HSAS26","HSIF16"], "primary_subject": "Science, Technology, Communications", "summary_short": "Efficient Use of Government Spectrum Act of 2013 - Directs the Federal Communications Commission (FCC), within three years after enactment of the Middle Class Tax Relief and Job Creation Act of 2012, to: (1) reallocate electromagnetic spectrum between the frequencies from 1755 to 1780 megahertz (currently, such frequencies are occupied by the Department of Defense [DOD] and other federal agencies); and (2) as part of the … -
Django admin : extending the existing user model. doesn't show in admin site
I'm a very beginner to Django. Using: Django 2.2.6 with python 3.6.3 Here is my problems with extending the existing user model. I've read this https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#extending-the-existing-user-model what I wanted to do is to use default auth. extends user model. see/manage the model I've extended in /admin However I cannot see what I extended in /admin. I've done the following: user.models.py: from django.db import models from django.contrib.auth.models import User class UserInfo(models.Model): user = models.OneToOneField(User, unique = True, verbose_name = '學號', on_delete = models.CASCADE) sNickName = models.CharField(max_length = 16, verbose_name = "暱稱") iArticleNumber = models.PositiveIntegerField(verbose_name = "文章數") # from 0 to 2,147,483,647 sShortIntroduction = models.TextField(verbose_name = "短自介") create an one to one model refer to User user.admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from user.models import UserInfo class UserInfoInline(admin.StackedInline): model = UserInfo can_delete = False verbose_name_plural = 'UserInfo' class UserAdmin(BaseUserAdmin): inline = [UserInfoInline, ] admin.site.unregister(User) admin.site.register(User, UserAdmin) add UserInfo in User And my /admin show like this: This page is the same as I did not add changes in user.admin.py. cannot find 'UserInfo' here. What I expect is when I click specific user, like '410431135' in picture, I can see and manage the 'UserInfo', … -
Customize a view handle POST and DELETE method in django rest framework
I created a View that can handle POST and DELETE method class MyView(APIView): def valid_method(self,data): method = self.request.method if method == 'POST': ser = self.PostSerializer(data=data) elif method == 'DELETE': ser = self.DeleteSerializer(data=data) else: raise MethodValidationError(errormessage) return ser def post(self, request): ser = self.valid_method(dara = request.data) other code def delete(self, request): ser = self.valid_method(dara = request.data) other code Is there any better way to implement MyView? Should I create a new base view? Or is there any simple way to define the legal HTTP method in APIView? -
AH01630: client denied by server configuration: /djangoDeployments
I am deploying a django application but I am having problems with the apache2 configuration. It gives me the error: AH01630: client denied by server configuration: /djangoDeployments I already folllowed some tutorials and tried implementing various ways that the documentation talks about Here is my conf file ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /djangoDeployments/tracker/printertracker> <Files wsgi.py> Require all granted </Files> </Directory> ServerName tracker.domain.com ServerAlias www.tracker.domain.com WSGIScriptAlias / /djangoDeployments/tracker/printertracker/wsgi.py WSGIDaemonProcess tracker python-home=/djangoDeployments/tracker/venv python-path=/djangoDeployments/tracker WSGIProcessGroup tracker I want to see it in the subdomain but when I am entering I get a 403 Forbidden access. -
How to have a stopwatch in django template?
I have a bunch of patients visiting a doctor in my WebApp. I want to have a timer that shows the time they have spent waiting. I should be able to pause and continue the timer and stop it and reset it. How do I implement this thing in my Django webapp? Do I use javascript? -
Saving new django model object gives duplicate key
Django 2.2.3 on Python 3.7, with Amazon RDS Postgres Database. Saving a new object doesn't work for this Company model: class Company(models.Model): name = models.CharField(max_length=255, unique=True) comp = Company(name='test') comp.save() Gives UniqueViolation: duplicate key value violates unique constraint "appname_company_pkey" DETAIL: Key (id)=(29) already exists I can confirm that yes, there is an entry with id=29 in the table. Why is Django trying to use that as the ID, and how do I stop it? -
How to pass a function from view.py to html
views.py def detect_full_text(tweet): if 'retweeted_status' in tweet.*_json*: analysis_tweet = tweet._json['retweeted_status']['full_text'] else: analysis_tweet = tweet.full_text return (analysis_tweet) public_tweet.html {% for analyze in analysis %} <tr> <td> {{ detect_full_text(analyze) }} </td> <td> {{ analyze.created_at }} </td> <td> {{ analyze.favorite_count }} </td> <td> {{ analyze.retweet_count }} </td> </tr> {% endfor %} I want to call python function from view.py in the html page -
Django testing with Multithreading, changes to database don't persist
I am attempt to replicate an issue we are experiencing on our production server where it seems if two requests are made to save or update and existing object, if made at a very close interval, results in duplicates. To test whatever solution we come up to prevent this, I am attempting to replicate this happening via multiprocessing. The only problem I am experiencing is after the two processes run and complete, when I query the database in the main function the changes supposedly made in the subprocesses haven't persisted, despite the same tests passing in the subprocesses. Code extract: def save_a_generic_model(self, id): data = {'value': '1'} request = RequestFactory().post('/api/responses/', data=json.dumps(data), content_type='application/json') request.user = self.user print(f'Process {id} started at {time()}') response = self.view(request) self.assertEqual(response.status_code, 202) self.assertEqual(len(models.GenericModel.objects.all()), 1) print(f'Process {id} finished at {time()}') def test_multiple_post_to_api(self): jobs = [] db.connections.close_all() for i in range(0, 2): jobs.append(Process(target=self.save_a_generic_model, args=(i,))) for i in range(0, 2): jobs[i].start() for i in range(0, 2): jobs[i].join() self.assertEqual(len(models.GenericModel.objects.all()), 1) # Fails here -
my url giving me this error invalid literal for int() with base 10
Hey guys i need some help in my url, im having trouble with url path, as you can see in my code i want my url /invitobidetails/ "id" = 1/"title" = Re-bidding of the Procurement for the Supply, Delivery and Installation of ICT Equipment and Software for 3D Modeling and Rendering/, i did not create slug in my database. I use the title of the file.. I tried this; path('invitobidetails/<int:mid>/<slug:title>/', views.invitobidDetails, name='invitobidetails'), ``` but this giving me and error : NoReverseMatch at / Reverse for 'invitobidetails' with keyword arguments '{'mid': 1, 'title': <MajorProjects: Re-bidding of the Procurement for the Supply, Delivery and Installation of ICT Equipment and Software for 3D Modeling and Rendering>}' not found. 1 pattern(s) tried: ['invitobidetails/(?P<mid>[0-9]+)/(?P<title>[-a-zA-Z0-9_]+)/$'] so i switch to "str:title" at first it shows no error but when i click the url it giving me this error: ValueError at /invitobidetails/1/Re-bidding of the Procurement for the Supply, Delivery and Installation of ICT Equipment and Software for 3D Modeling and Rendering/ invalid literal for int() with base 10: Here's my code btw. my url.py: path('invitobidetails/<int:mid>/<str:title>/', views.invitobidDetails, name='invitobidetails'), my views.py : def invitobidDetails(request, mid, title): try: invitobidetails = InviToBid.objects.get(id=mid, ProjectName=title) major_projectslists = ProjectNameFileType.objects.filter(ProjectName__in=MajorProjects.objects.filter( invitobid__NameOfFile=invitobidetails)) except InviToBid.DoesNotExist: raise Http404("file does … -
Why cann't i not access media
I seem do not understand what i am doing wrong. I have done research online to see if there is any changes, but yet none. Bellow is what i did settings.py STATIC_URL = '/static/' STATIC_ROOT=[ os.path.join(BASE_DIR,"static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') url.py urlpatterns +=static (settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) model.py class product(models.Model): imageone = models.ImageField(upload_to="productimage",null=True,blank=False) When i upload image from the admin, i get image location at http://127.0.0.1:8000/media/productimage/homepagebizalAfric.jpg, but image does not display. What i my doing wrong ?