Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create new field in output by annotate() with default value?
In SQL it would be SELECT *, 0 as new_field FROM table; I thought in django it would be like Article.objects.annotate(new_field=0), but it doesn't work: TypeError: QuerySet.annotate() received non-expression(s): 0. Is there the way to do it? -
How to use Google APIs to reduce in memory usage and to use Advance Google features?
A) I want to build a system that would allow users to POST videos to their youtube channel after they are logged in with the google account to my website. The video will be published on the website. B) After that, I also need that the users could comment on the videos that showed on my website, and on youtube. C) After that, I need that the user's profile pictures will be uploaded to their own Google Drive. Tasks: Upload Videos to the website with Youtube (Youtube Video API). Comment on videos on the website (Youtube Comments API). Upload profile picture to Google Drive (Google Drive API). I don't know where to start, and how to do that any user "Hosts" itself, for example, he can add videos, comments, and host his profile picture. Using Django with Python3 -
How to solve the problem of Dual behavior of django CustomUser in migration?
I have a data migration as below in which I want to use create_user method of CustomUser, get an instance of the created user, and use this instance to create instance of Partner model. It is worth mentioning that I have a Partner model that has a one-to-one relationship with CustomUser. I have two options: # Option One: def populate_database_create_partner(apps, schema_editor): Partner = apps.get_model('partners', 'Partner') CustomUser.objects.create_user( id=33, email='test_email@email.com', password='password', first_name='test_first_name', last_name="test_last_name", is_partner=True, ) u = CustomUser.objects.get(id=33) partner = Partner.objects.create(user=u, ) class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_populate_database_createsuperuser'), ] operations = [ migrations.RunPython(populate_database_create_partner), ] In option one, I see this error: ValueError: Cannot assign "<CustomUser: test_email@email.com>": "Partner.user" must be a "CustomUser" instance. I then test this: # Option Two: def populate_database_create_partner(apps, schema_editor): Partner = apps.get_model('partners', 'Partner') CustomUser = apps.get_model('accounts', 'CustomUser') CustomUser.objects.create_user( id=33, email='test_email@email.com', password='password', first_name='test_first_name', last_name="test_last_name", is_partner=True, ) u = CustomUser.objects.get(id=33) partner = Partner.objects.create(user=u, ) class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_populate_database_createsuperuser'), ] operations = [ migrations.RunPython(populate_database_create_partner), ] I the see this error: CustomUser.objects.create_user( AttributeError: 'Manager' object has no attribute 'create_user' The create_user method does not work. If I do not use the create_user method and simply use CustomUser.objects.create(...), I will not be able to set password in here. -
django database config file for "OPTIONS" can only reads a .cnf format
If this is a good template for the DATABASES dictionary in django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<DATABASE NAME>', 'USER': '<USER NAME>', 'PASSWORD': '<PASSWORD>', 'HOST': '<HOST>', 'PORT': '3306' 'OPTIONS': { 'ssl': {'ca': '<PATH TO CA CERT>', 'cert': '<PATH TO CLIENT CERT>', 'key': '<PATH TO CLIENT KEY>' } } } } I want to read the OPTIONS key from file like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<DATABASE NAME>', 'USER': '<USER NAME>', 'PASSWORD': '<PASSWORD>', 'HOST': '<HOST>', 'PORT': '3306' 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, "db_config.json"), }, } } however, this is giving me an error. The file is not being found. I noticed that all the examples from Django only use a .cnf file. and the cnf file really does work. However, I have a nested dict inside the .json file which I cannot seem to convert to .cnf (or INI) since these config files do not support nested parameters. How can I solve this? -
How can I pass empty request_body_schema to swagger_auto_schema in Django Rest Framework?
class ProfileSettingsViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer @swagger_auto_schema(??? responses={200: "Redirect to Sign In page", 401: "Unauthorized Error"}) @action(detail=False, methods=['post']) def logout(self, request): I need to in request_body_scheme will a empty data, but I get UserSerializer structure. How to fix it? -
Django Allauth Ignoring Adapter
Allauth signin keep showing despite adding adapter. Following allauth documentation on Overriding the allauth signin, i created an adapter.py in my app (accounts) with: from allauth.account.adapter import DefaultAccountAdapter class NoNewUsersAccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return False I equally added to my settings file: ACCOUNT_ADAPTER = 'accounts.adapter.NoNewUsersAccountAdapter' -
How to download files from user_directory_path in django
I am trying to download files that were uploaded to my django media directory. I am able to upload the files successfully, but I don't know the best method of downloading back these files. I have seen different examples online but I don't fully understand them. Here are my codes models.py: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) certification = models.FileField(upload_to=user_directory_path, blank=True) urls.py urlpatterns = [ ......... path('profile/', user_views.profile, name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) file.html: <a href="{{ user.profile.certification.url }}">Download Certification</a> I get this error: ValueError The 'certification' attribute has no file associated with it. Do I create a view in my views.py and a url in my urls.py to handle the download? If so How do I go about it. -
Django Middleware extend self.request error when not logged in
We know in self.reqeust, there are too many instances like self.request.user, self.request.data self.request.authenticator I am trying to make self.request.person with this, instance, i should get my Person Model instance this is my model from django.contrib.auth.models import User class Person(models.Model): auth_user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='auth_user', ) name = models.CharField(max_length=50) this is my middleware.py file from account.models import Person class PersonMiddleWare(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): person = Person.objects.filter(auth_user=request.user.id).first() request.person = person response = self.get_response(request) return response Currently is working fine for logged-in user but the problem, when I go to incognito mode and visit the admin page, it through me an error that anonymous user doesn't have attribute request.user.id to solve this, I write a condition like this if request.user.is_authenticated: but it wasn't solved the issue, I guess, I wrote my middleware wrongly, can anyone help me to achieve this? What is the right way to write middleware to extend self.request to self.request.person? -
Django - Making a Reservation system
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" and (if the apartment already isn't booked ) and book the apartment. Im a total Django newbie, and need some pointers in order to start somewhere with this task. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I'm using the provided django user models to register / log-in. What kind of model do I need for the reservation, and how could I connect everything ? I tried making a reservation model, but I got no idea where to go next. I'm not asking for you to solve this for me, I'm asking for someone to explain (if possibile in detal) to me how could I go on about achieving this on my own. this is my apartment model: class Apartment(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = … -
Breadcrumbs in custom admin view (Django)
I have custom admin view which works fine, except that I would like to add breadcrumbs. Up to now I only see "Start". But I would like to see "Start > Foo". What do I need to add to my template? -
django google_cloud_logging json format
I am trying to use google_cloud_logging with Django to log JSON logs to Stackdriver. However, the received format on Stackdriver is not as I would expect. My settings.py LOGGING setup looks like: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'stackdriver_logging': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': log_client, }, }, 'loggers': { '': { 'handlers': ['console', 'stackdriver_logging'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['console', 'stackdriver_logging'], 'level': 'INFO', 'propagate': True } } and I write dictionary logs like: _logger.info({'message_type':'profile', 'runtime': 500}) I would expect on Stackdriver for messages to appear as: { ... jsonPayload:{ 'message_type':'profile', 'runtime': 500 } } However they appear with the following format: { ... jsonPayload:{ 'message': "{'message_type':'profile','runtime': 500}" } } where instead of the jsonPayload being directly the sent dictionary, it is string encoded in 'message'. It's unclear what I should change in order to have the desired format on Stackdriver. Could anyone point me in the right direction? -
How to limit items that appear in a form dropdown within a sub form based on the selected value in the main form
I am in the process of creating a purchase order application but am strugging with limiting the products that a user can select based on a selected supplier. I have the following models within models.py: class PurchaseOrders(models.Model): po_number = models.AutoField(primary_key=True) po_date = models.DateField( verbose_name='Purchase Order Date', auto_now_add=True, auto_now=False) supplier_ref = models.ForeignKey( Suppliers, verbose_name='Supplier', on_delete=models.SET_NULL, null=True,) order_net = models.DecimalField( verbose_name='Order Net', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) order_vat = models.DecimalField( verbose_name='Order VAT', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) order_gross = models.DecimalField( verbose_name='Order Gross', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) total_items = models.PositiveIntegerField( verbose_name='Total Items', blank=True, null=True, default=0) delivered = models.BooleanField(default=False, blank=False) def __str__(self): return str(self.po_number) class Meta: verbose_name_plural = "Purchase Orders" class PoLines(models.Model): po_number = models.ForeignKey( PurchaseOrders, verbose_name='Purchase Order', on_delete=models.SET_NULL, null=True,) product_code = models.ForeignKey( Products, verbose_name='Product', on_delete=models.SET_NULL, null=True,) supplier_ref = models.ForeignKey( Suppliers, verbose_name='Supplier', on_delete=models.SET_NULL, null=True,) product_movement = models.OneToOneField( ProductMovement, on_delete=models.CASCADE) product_price = models.DecimalField( verbose_name='Product Price', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) item_quantity = models.PositiveIntegerField( verbose_name='Item Quantity', blank=True, null=True, default=0) item_net = models.DecimalField( verbose_name='Item Net', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) item_vat = models.DecimalField( verbose_name='Item VAT', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) item_gross = models.DecimalField( verbose_name='Item Gross', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) def __str__(self): return self.product_code.name class Meta: verbose_name_plural = "Purchase Order Lines" class Products(models.Model): product_code = models.CharField( … -
getting error " list indices must be integers or slices, not str "
I am new to Django. in the below data I need to get the values of text(key) from the options list of dicts and return them in list. when i trying to get the values compiler throwing the error saying 'list indices must be integers or slices, not str'.I already spent more than 3hrs on this. Thanks in advance This is my data { 'text':'man', 'offset':0, 'length':3, 'options':[ { 'text':'manglore', '_index':'locations', '_type':'_doc', '_id':'5', '_score':2.0, '_source':{ } }, { 'text':'manipal', '_index':'locations', '_type':'_doc', '_id':'6', '_score':2.0, '_source':{ } } ] } This is my code def search(request): message = request.POST['x'] res = es.search(index = "locations", body = { "_source": "suggest", "suggest": { "places": { "prefix": message, "completion": { "field": "name", "fuzzy": { "fuzziness": "AUTO", "transpositions": "true" } } } } }) city_list = [] output = res['suggest']['places'] for val in output['options']: print(val['text']) city_list.append(val['text']) return HttpResponse(output) -
How can I filter the array contain condition in Django Rest Framework?
I have a model REST list API result like this: URL localhost:8000/api/server/list: [ { "id": 320, "ipv4s": [ { "id": 1393, "vlanedipv4networkgroup": { "name": "52", "id": 147 }, "ip": "43.224.225.89", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null }, { "id": 1394, "vlanedipv4networkgroup": { "name": "52", "id": 147 }, "ip": "43.224.225.90", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null } ], "bandwidth": 1000, "user": null, "is_applied": true, "is_finish_task": true, "simple_hardware_text": "E3-1230v5/16G/256G(SSD)/ ", "switch_management_server_ip": "43.224.224.29", "all_disk_dict": { "total_count": 1, "disk_type": [ 1, 0 ], "total_size": 256 }, "name": "LA-C03-A1", "desc": "2008", "cpu": "Intel Xeon E3-1230 v5", "ram": "Supermicro DDR4___16", "disk": "Intel SSD___256", "disk2": null, "disk3": null, "disk4": null, "disk5": null, "disk6": null, "disk7": null, "disk8": null, "disk9": null, "disk10": null, "price": "1000.00", "pay_time": null, "expire_time": null, "ipmi_addr": "172.18.16.197", "ipmi_account": null, "ipmi_pwd": null, "has_intranet": false, "intranet_ip": null, "customer_desc": null, "whmcs_tblorders_id": null, "recycle_time": null, "ctime": "2019-01-16T21:27:10.870288+08:00", "uptime": "2019-06-25T09:30:55.652359+08:00", "switches": { "id": 14, "name": "LA-C03-A", "desc": "LA-C03-A", "manage_ip": "192.168.200.17", "manage_uname": "ADMIN", "manage_pwd": "ADMIN", "is_listing": true, "ctime": "2019-01-16T17:20:00.458601+08:00", "uptime": "2019-06-12T14:14:19.904123+08:00", "switch_type": 2, "routerdevice": 4, "gatewaydevice": 3 }, "physical_server_model": { "id": 11, "cpu": "Intel Xeon E3-1270 v5", "ram": "Supermicro DDR4___16", "disk": "Intel SSD___1000", "price": "2000.00", "ctime": "2019-01-16T18:42:17.308968+08:00", "uptime": … -
How to load data from variable into django paginator?
I need to create paginator based on data from variable. Variable is just python lists. views.py: def test(request): db = MySQLdb.connect(host="localhost", # your host, usually localhost user="pc", # your username passwd="3346378", # your password db="mc") cur = db.cursor() cur.execute('''SELECT * FROM hello left join hell on hello.Id=hell.Id ''') row = cur.fetchall() So, row is lot's of lists. And how can I load it into paginator? Or one way is to create table and model for data and work with it? -
int() argument must be a string, a bytes-like object or a number, not 'ForeignKey'
I am beginner in Django. I need columns showing only the type_of_due_date that exists in the selected country. In "class InputType" I tried use limit_choices_to and Q function, but see mistake like int() argument must be a string, a bytes-like object or a number, not 'ForeignKey' Please, help. What I did wrong? My models: class InputVatDueDate(models.Model): country = models.ForeignKey(Country, verbose_name='Country', on_delete=models.CASCADE, db_index=True, blank=True) date = models.DateField(_('date'), default=datetime.datetime.now) class Meta: verbose_name = _('input vat due date') verbose_name_plural = _('input vats due date') unique_together = (('country', 'date'),) def __str__(self): return self.country.name class TypeOfVatDueDate(models.Model): vat_due_date = models.ForeignKey(InputVatDueDate, on_delete=models.CASCADE) type_of_due_date = models.CharField(max_length=100, choices=enum_to_choice(TypeDueDates)) date_of_start = models.IntegerField(_('day of start date')) def __str__(self): return self.type_of_due_date class InputType(models.Model): vat_due_company = models.ForeignKey(CompanyVatDueDate, on_delete=models.CASCADE) country = models.ForeignKey(InputVatDueDate, on_delete=models.CASCADE,) type_of_due_date = models.ForeignKey(TypeOfVatDueDate, on_delete=models.CASCADE, limit_choices_to=Q(vat_due_date_id=country), ) -
getting only the date on datetime
Good day! I'm new in using Django and python and I wanted to check only the date in DateTime inside my database. model = Employee_Salary Employee_Salary.objects.filter(emp_id=employee_id, emp_in=datetime.today().date()).exists() so the code I'm currently using is this datetime.today().date() to get only the date if Employee_Salary.objects.filter(emp_id=employee_id, emp_in=datetime.today().date()).exists(): # if emp out exist then stop if Employee_Salary.objects.filter(emp_id=employee_id, emp_out=datetime.today().date()).exists(): messages.info(request,'you are already logged out...') return render(request, 'registration/register.html', locals()) else: Employee_Salary.objects.filter(emp_id=employee_id).update(emp_out=datetime.today()) # should be emp out, rendered and salary messages.info(request,'logged out...') return render(request, 'registration/register.html', locals()) else: #command if employee does not exist add employee register_emp = Employee_Salary(emp_id=employee_id, emp_in=datetime.today()) register_emp.save() messages.info(request,'logged in') return render(request, 'registration/register.html', locals()) #this is my entire code I expected it to check my model Employee_salary's emp_in, which emp_in is a DateTime, then I wanted to check only the date and if there is a date already this day, it will now put a data inside the emp_out instead, but it didn't happen, it made another login of emp_in instead... I really hope I explained it well and thanks in advance on your help! -
Django - Admin - Add link in a change_form that redirect to another change_form
I am newbie inDjango/Python I've started to implement admin forms and try to personnalize behavior I would like to add a link on a specific change_form (not all change forms) that will open a new windows that allow the user to enter data in another change_form without leaving the first change form the 2 forms correspond to 2 models linked (related tables) is-it possible with admin forms? enter image description here -
Django : dynamically update via request.data error
Stock.objects.get(id=1).update( **request.data ) data = request.data print(data) I get this - <QueryDict: {'discount_margin': ['77'], 'rack': ['77'], 'demand': ['77']}> I am getting this - float() argument must be a string or a number, not 'list' -
Is django automatically handle auto-escaping & context aware?
As now I am developing website using django web framework of python. I have very concerned with XSS & security of website. I have read some references related XSS & prevent them using escaping , encoding etc.. so my question is does Django autoescape every input data & handle XSS attacks automatically or explicitly do we need to implement code to prevent XSS attack ? How can we prevent all kinds of XSS attacks in Django ? -
Django, Ajax set progress bar
i have problem of updating html data with ajax while loading file with Django template. Some help: link_1 Data path: In my Progress object is stored updated progress value Ajax is getting this value and updating html tag text with it every second code: view.py def progress(request): if request.method == 'GET': progress_object = Progress.objects.get(id=1) data = dict({'value': str(progress_object.value)}) return JsonResponse(data) template.html <center> <p id="message">bb</p> </center> <script> function fetchdata(){ $.ajax({ url: '/products/progress/', type: 'GET', dataType: 'json', success: function (data) { $( '#message' ).text(data.value); console.log(data.value); if (data.value == 100) { clearInterval(id); } }, }); } $(document).ready(function(){ id = setInterval(fetchdata,1000); }); </script> Result: get progress value is working but is not updating the html tag text while file is processing [spinning]. I get only last result - 100 %. Question: how to update template every second with progress value? -
How to use two user of model to login in website
I am making 3 models in models.py 1)Patients, 2)Doctor, 3)Record. I need a patient and doctor to login to a website. I tried to separate both authentications in one view but I'm not able to login in actual. here Models.py from django.db import models from django import forms from django.contrib.auth.models import AbstractUser # Create your models here. class Patient(models.Model): ppname = models.CharField(max_length=264,unique=True) patient_name = models.CharField(max_length=264) pemail = models.CharField(max_length=264) ppass = models.CharField(max_length=264) page = models.FloatField(max_length=20) padd = models.CharField(max_length=264) ppin = models.PositiveSmallIntegerField() pstate = models.CharField(max_length=264) def __str__(self): return self.patient_name class Doctor(models.Model): dpname = models.CharField(max_length=264, unique=True) dname = models.CharField(max_length=264) dedu = models.CharField(max_length=264) dexpr = models.FloatField() dhadd = models.CharField(max_length=264) dhpin = models.PositiveSmallIntegerField() dhstate = models.CharField(max_length=264) demail = models.EmailField(max_length=264) dpass = models.CharField(max_length=264) dcerti = models.ImageField(upload_to = "media/doc_certi", blank=False) dpic = models.ImageField(upload_to = "media/doc_certi", blank=False) def __str__(self): return self.dname class Record(models.Model): ppname = models.ForeignKey(Patient,on_delete = models.PROTECT) dpname = models.CharField(max_length=264) disease = models.CharField(max_length=264) medicine = models.TextField() rname = models.CharField(max_length=264) rdoc = models.FileField(upload_to='media/pat_report',blank=True) def __str__(self): return self.rname my view.py :- from django.shortcuts import render from django.views.generic import View,TemplateView #for password from passlib.hash import pbkdf2_sha256 #for forms from .forms import PatientForm,DoctorForm,RecordForm,DLoginForm,PLoginForm #for login from django.urls import reverse from django.http import HttpResponseRedirect,HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout … -
Django Python arrange json into a single node
I'm working with a legacy database which has 2 records, the data in each record contain the following values: Name, Email, Company, Phone These 2 records contain the same data value except the value for Phone which is different. When I retrieve them in JSON I get the following output: "results": [ { "Name": "Mack", "Email": "Mack@email.com", "Company": "Company Name", "Phone": "123456789" }, { "Name": "Mack", "Email": "Mack@email.com", "Company": "Company Name", "Phone": "1111111" } ] My question: As you can see there is some duplicate data in the output above, so is there a way to arrange the JSON output to the following: "results": [ { "Name": "Mack", "Email": "Mack@email.com", "Company": "Company Name", "Phone": "123456789" "Phone 2": "1111111" } ] Here is the code for Views.py file: class DataView(viewsets.ModelViewSet): queryset = DataList.objects.all() serializer_class = DataSerializer Here is the code for Serializers.py file: class DataSerializer(serializers.ModelSerializer): data_details = serializers.SerializerMethodField() class Meta: model = DataList fields = 'data_details' def get_data_details(self, obj): return [{ 'name': obj.name, 'email': obj.email, 'company': obj.company, 'phone': obj.phone, }] Here is the code for models.py file: class Data(models.Model): name = models.CharField(db_column='name', primary_key=True, max_length=50) email = models.CharField(db_column='email', max_length=50) company = models.CharField(db_column='company', max_length=100) phone= models.TextField(db_column='phone') class Meta: managed = False db_table = … -
Form is not responding to submit
I have form, user must fill it and submit but I have no reaction from this form First I thought there is a problem with action directive of the form, so used redirect method in the views but no help def organization_info(request): organization_form = OrganizationInformationForm() context = { 'organization_form': organization_form } if request.method == "POST": print("POST") organization_form = OrganizationInformationForm(request.POST, request.FILES) if organization_form.is_valid(): print("VALID") new_org = OrganizationInformation.objects.create(**organization_form.cleaned_data) print("FILLED") return redirect(organization_list) return render(request, 'organization_form.html', context) <form method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-sm-4 control-label">Organization Name:</label> . . . <div class="form-group"> <div class="col-sm-4 col-sm-offset-4"> <button type="submit" class="btn btn-pink">Submit</button> </div> </div> </form> I only have the "POST" printed on the log no any errors -
When i try to run makemigrations command in django it gave me an error
When i try to run makemigrations command in django it gave me an error TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not list Help me to resolve this issue. This is my static root and media roots all stuffs. STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = [os.path.join(BASE_DIR, 'static_root')] MEDIA_ROOT = [os.path.join(BASE_DIR, 'media_root')]