Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django function inside models, display result inside the template
I have two models as given below. PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable')) class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,) opening_stock=models.PositiveIntegerField(default=0) def __str__(self): return '%s (%s, %s, %s) o.stock = %d ' % (self.product_group, self.manufacturer, self.product_type ,self.opening_stock) unique_together = ('product_group', 'manufacturer','product_type') def get_total_stock_in(self): Stock.objects.filter(product=self.id,ttype='I').aggregate(Sum('quantity')) def get_total_stock_out(self): Stock.objects.filter(product=self.id,ttype='I').aggregate(Sum('quantity')) and TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out')) class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) date=models.DateField(blank=False, null=False,) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Ttransaction type",choices=TRANSACTION_TYPE, blank=False) added_date=models.DateTimeField(blank=False, auto_now=True) def get_absolute_url(self): return reverse('product_detail', args=[str(self.product.id)]) def __str__(self): return ('[%s] %s (%s) %d' %(self.product, self.date, self.ttype, self.quantity)) and a view class ProductList(ListView): model=Product My intention is to have two functions get_total_stock_in() and functions get_total_stock_out() to find the sum of all stock_ins and stock_outs for each product and display the result in the template product_list.html For this, I have <ul> {% for product in object_list %} <li><a href="{%url 'product_detail' product.id %}">{{ product.product_group}}-{{ product.product_type}} {{ product.manufacturer}} </a> opening.stock: <b>{{ product.opening_stock}} </b>, total s/i: {{product.get_total_stock_in.quantity__sum}} , total s/o: {{product.get_total_stock_out.quantity__sum}} </li> {% endfor %} </ul> I don't know how to get the desired result. Any help would be appreciated. Thanks. -
Drag and drop in django project with jquery-file-upload
I have quiet old django project - django 1.6 and I'm trying make drag and drop for images. I'm trying copy this solution: https://github.com/sigurdga/django-jquery-file-upload In method form_invalid I revived an error: {"post_locale": ["This field is required."], "attachment": ["This field is required."]} My view: class PictureCreateView(CreateView): model = PostLocaleFile fields = "__all__" def form_valid(self, form): self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) print data return HttpResponse(content=data, status=400, content_type='application/json') My model: class PostLocaleFile(models.Model): post_locale = models.ForeignKey(PostLocale, related_name='files') attachment = models.FileField(upload_to="localefile/") def __str__(self): return self.attachment.name @models.permalink def get_absolute_url(self): return reverse('upload-new') def save(self, *args, **kwargs): self.post_locale = self.attachment super(PostLocaleFile, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.attachment.delete(False) super(PostLocaleFile, self).delete(*args, **kwargs) -
django invalid syntax (pagination_tags.py, line 225)
Environment: Request Method: GET Request URL: http://www.qiuqingyu.cn/cnki_spider/todolist/ Django Version: 1.9 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pagination', 'myapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'myapp.middleware.CheckSoureMiddware'] > > Traceback: File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in __getitem__ 86. return self._engines[alias] During handling of the above exception ('django'), another exception occurred: File "/root/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/root/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./myapp/views.py" in todolist 29. return render(request, 'todolist.html', context=locals()) File "/root/anaconda3/lib/python3.6/site-packages/django/shortcuts.py" in render 67. template_name, context, request=request, using=using) File "/root/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 96. template = get_template(template_name, using=using) File "/root/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in get_template 26. engines = _engine_list(using) File "/root/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in _engine_list 143. return engines.all() if using is None else [engines[using]] File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in all 110. return [self[alias] for alias in self] File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in <listcomp> 110. return [self[alias] for alias in self] File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in __getitem__ 101. engine = engine_cls(params) File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in __init__ 31. options['libraries'] = self.get_templatetag_libraries(libraries) File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in get_templatetag_libraries 49. libraries = get_installed_libraries() File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in get_installed_libraries 131. for name in get_package_libraries(pkg): File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in get_package_libraries 144. module = import_module(entry[1]) File "/root/anaconda3/lib/python3.6/importlib/__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) Exception Type: SyntaxError at /cnki_spider/todolist/ Exception Value: invalid … -
Getting TypeError while riuting to insert page using Django and Python
I am getting one error while opening my insert page using Django and Python. I am explaining the error below. TypeError at /insert/ context must be a dict rather than WSGIRequest. Request Method: GET Request URL: http://127.0.0.1:8000/insert/ Django Version: 1.11.2 Exception Type: TypeError Exception Value: context must be a dict rather than WSGIRequest. Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/context.py in make_context, line 287 Python Executable: /usr/bin/python Python Version: 2.7.6 I am explaining my code below. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import loader,Context,RequestContext from crud.models import Person # Create your views here. def index(request): t = loader.get_template('index.html') #c = Context({'message': 'Hello world!'}) return HttpResponse(t.render({'message': 'Hello world!'})) def insert(request): # If this is a post request we insert the person if request.method == 'POST': p = Person( name=request.POST['name'], phone=request.POST['phone'], age=request.POST['age'] ) p.save() t = loader.get_template('insert.html') #c = RequestContext(request) return HttpResponse(t.render(request)) I am using Django 1.11. Please help me to resolve this issue. -
PyCharm Django Javascript Debugger
I cannot figure out how to debug JavaScript code that is executed while loading a Django template. I have installed the ChromeExtension (localhost and port 63342). Then I have created a RunConfiguration: JsDebug with the url "http://localhost:63342/ThingShare/2/" Every time I try to debug this I receive :404 not found. The Debugger Console says : "Connected to JetBrains Chrome Extension" The same url "http://localhost:8000/ThingShare/2/" works like a charm. I have no clue where to continue here -
Django's non-required datetime field validation doesn't act as intended
I have a small Django application with very basic models and forms, where the element that gives me issues is the DateTimeField. Model: class Task(models.Model): what = models.CharField(max_length=255) due = models.DateTimeField(null=True, blank=True) #[...] Form: class TaskForm(forms.Form): due = forms.DateTimeField(required=False) In the view, upon POST: form = TaskForm(request.POST) if form.is_valid(): # further processing # create new task or edit existing task, for example: new_task = Task('what':request.POST['what'], 'due':request.POST['due']) new_task.save() In the template, for the displaying of the DateTimeField, I use the bootstrap datetimepicker, which works just fine. The problem is that I seemingly can't choose the correct format for Django. Form what I've read any of the below formats should be fine. [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ] But when I choose a DateTime with the DateTimePicker it's not accepted. I receive a ValidationError from Django. From what I can tell, it's not from .is_valid(), but from the .save() function. ['„“ value … -
Form validation does not work. How to call clean_field methods
I'm going to add records to DBase using form. So I need data to be written to a database when the request.method = 'Post' and form.is_valid. I have this written in my views.py def makepicturepost(request): form = PostForm2() print('View called') print('Request_method ' + request.method + ' Form.is_valid ' + str(form.is_valid())) if request.method == 'POST' and form.is_valid(): author = form.author comment = form.comment picture = form.picture newpost = PicturePost(author=author, comment=comment, picture=picture) newpost.save() return HttpResponseRedirect('/') context = { "form": form } return render(request, "makepost.htm", context) The form validation should be checked after calling form.is_valid(), so I wrote some validation methodes in my forms.py class PostForm2(forms.Form): author = forms.CharField(max_length=30, widget=forms.TextInput) comment = forms.CharField(max_length=1500, widget=forms.Textarea) picture = forms.ImageField() def clean_author(self): print('cleaned_author') author = self.cleaned_data.get('author') if not author: raise forms.ValidationError("Autor name shouldn't be blank") return author def clean_comment(self): print('cleaned_comment') comment = self.cleaned_data.get('comment') if not comment: raise forms.ValidationError("Write a pair of lines as a comment") return comment def clean_picture(self): print('cleaned_picture') picture = self.cleaned_data.get('picture') print(picture) return picture I was going to inspect picture object to find out how to check it to be only an image. But my clean_field methods seem not called at all. That's what I have in console: View called Request_method POST Form.is_valid False … -
nginx load-balancer in front of another nginx?
I have a working site which looks like. client - nginx - uwsgi - django I'd like to increase the number of the web server and put a load-balancer in front. (1. to server more user, 2. to prepare machine failure) Since one of my web server is private hosted, and one is aws hosted, I'm considering nginx as a load-balancer. (aws ELB seems to talk to only ec2 machines) This is my first time dealing with load-balancer so I'm not sure if I'm after something like.. client -- nginx (load-balancer on AWS) \ --- nginx1 - uwsgi1 - django1 (on AWS) \ \--- nginx2 - uwsgi2 - django2 (outside of AWS) Or should I make something like client -- nginx (load-balancer) \ --- uwsgi1 - django1 \ \--- uwsgi2 - django2 -
oAuth2 credentials being stored as unicode
I'm working on storing oauth2 credentials so that I can create services later on. currently my model looks like this: from django.db import models from oauth2client.contrib.django_util.models import CredentialsField from south.modelsinspector import add_introspection_rules class oAuth(models.Model): siteid = models.CharField(max_length=100L, primary_key=True) credential = CredentialsField() add_introspection_rules([],["^oauth2client\.contrib\.django_util\.models\.CredentialsField"]) when I try to save my credentials: credential = flow.step2_exchange(code) storage = DjangoORMStorage(oAuth, 'siteid', site_id, 'credential') storage.put(credential) in my DB I have a unicode string being stored which then can't be converted into a oauth object using: storage = DjangoORMStorage(oAuth, 'siteid', site_id, 'credential') credential = storage.get() return credential I am getting credentials to be the unicode that was stored previously, I just can't perform the .authorize method on it which is what I need to do, have I gotten confused somewhere? -
Django validator not triggering on file upload
I have wrote a Django app for the user to upload files and see a list of uploaded files. I want to restrict the uploads to only using gif format and wrote a simple validator. Then I pass that validator in the Model, however it never triggers and the file is saved regardless of the format. Here's what I got so far. views.py def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() messages.add_message(request, messages.INFO, "Saved") # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) checkformat.py def validate_file_type(upload): if not (upload.name[-4:] == '.gif'): raise ValidationError('File type not supported.') models.py from .checkformat import validate_file_type def content_file_name(instance, filename): return '/'.join(['documents', str(filename), filename]) class Document(models.Model): docfile = models.FileField(upload_to=content_file_name, validators=[validate_file_type], null=False, verbose_name="File") Is there something I'm missing? I've just started learning Django. Also, I know this is not a sercure way to check for a file type, but I just want to see it work … -
Django template use inlinecss with variable
I'm using inlinecss where this works: {% load static inlinecss %} {% inlinecss "/css/mycssfile.css" %} But I need to pass a variable instead of a string. It won't let me pass it with the context (I get "invalid file: None" error): {% load static inlinecss %} {% inlinecss a_context_variable %} The same happens if it's inserted on the request object using middleware: {% load static inlinecss %} {% inlinecss request.a_variable_inserted_by_middleware %} I've also tried using with: {% load static inlinecss %} {% with request.a_variable_inserted_by_middleware as cssfile%} {% inlinecss cssfile %} {% endwith %} But get: Invalid block tag on line 4: 'endwith', expected 'endinlinecss'. Did you forget to register or load this tag? Any ideas? -
What is Q operator within reduce function is doing?
I am not sure what the following line of code is doing. I am sure its being used for the search but what is going within the reduce function. Also i went through https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q to find out similar examples for Q operator didn't find anything. qgroup = reduce(operator.or_, (Q(**{fieldname + '__icontains': q_search}) for fieldname in fieldnames)) return queryset.filter(qgroup) Question below did explained it a bit what does this operator means in django `reduce(operator.and_, query_list)` -
Django render html with jinja tag in template
I have some little problem. I have site and all content save in database. What could I write in src image tag which save in my database with other HTML text to load images from static folder. For example:<p>Some text</p> <img src="???"> <p>Another text text</p>. This is the date which is in my database field called 'text'. On main page it load without any problem. But when I go to another page URL variable change from http: //127.0.0.1:8000/ to http: //127.0.0.1:8000/page/ and if I wrote in src attribute in database field 'static/img/1.png' image URL on HTML page become http: //127.0.0.1:8000/page/static/img/1.png and image don't load. How could I write or what could I change on my project to fix that? -
Add timezone with New User Creation Django
I have a user model with various fields now I want to add time zone with a new user. How can I add a time zone with a new user and update timezone with an existing user? models.py class User(AbstractBaseUser, PermissionsMixin): """ A fully featured User model with admin-compliant permissions that uses a full-length email field as the username. Email and password are required. Other fields are optional. """ username = models.CharField( verbose_name=_("Username"), max_length=255, unique=True ) email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated ' 'as active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) time_zone = models.IntegerField(blank=True, null=True, default=369) views.py class NewUser(generics.CreateAPIView): model = User serializer_class = CreateUser permission_classes = (permissions.IsAdminUser,) queryset = User.objects.all() def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): fleetz = "" if 'fleets' in serializer.validated_data: fleetz = serializer.validated_data.pop('fleets') user = User.objects.create_user(**serializer.validated_data) if fleetz: user.fleets.add(*fleetz) user.save() return Response({'message':'User created successfully'}, status=status.HTTP_201_CREATED) serializers.py class CreateUser(serializers.ModelSerializer): fleets = FleetField(many=True, queryset=Fleet.objects.all()) class Meta: model = User exclude = … -
Django: only submit a form if what they entered in one field matches something in a different class
I am working on the registration for my website, and I need a way of verifying that a teacher belongs to the school that he/she says they do when applying, as the school class has a many to many field that all the teachers of the said school are in. They way I have decided to do this, is to create a unique code for every school, and during the teachers registration, they need to enter the name of the school, and its code. If the code and the schools name match, they get registered, and if they dont, it throws an error. These are the relevant classes: class TeacherProfile(models.Model): user = models.OneToOneField(User, null = True, related_name = 'TeacherProfile', on_delete = models.CASCADE) teacher = models.BooleanField(default = True) school = models.CharField(max_length = 100) identification_code = models.CharField(max_length = 10, default = '') subject = models.CharField(max_length = 100) head_of_subject = models.BooleanField(default = False) headmaster = models.BooleanField(default = False) def username(self): return self.user.username def fullname(self): return (self.user.first_name + " " + self.user.last_name) class SchoolProfile(models.Model): school_name = models.CharField(max_length = 100, default = '', unique = True) identification_code = models.CharField(max_length = 10, unique = True) teachers = models.ManyToManyField(TeacherProfile, blank = True) The form I use for … -
Django - Setup a cron job once a model is created
I have a scenario where I want to set up a scheduler and run it at a particular time of the day. I also need to run the same cron job once an entry of a model is created. How can I achieve this? which is the best method? I have referred to following links but I am confused on to which to proceed and which is the latest one. Django scheduled jobs Django - Set Up A Scheduled Job? -
How to parse and filter a URL Web API in Django?
I am trying to filter the content from a URL Web API and I am using a GET method to obtain the complete data set, then I apply some filters to that response and I get my desired results, but the complete process of retrieval - filter - display results takes around 3-5 mins which is too much waiting time for users. I want to apply a POST method to filter directly from the URL request instead of retrieving the complete data set, in that way, I will get rid of my custom filters and greatly reduce the waiting time. How can I achieve this? This is the current code I have: from django.shortcuts import render from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.response import Response from collections import Counter from datetime import datetime, timedelta import json, urllib.request, dateutil.parser, urllib.parse # Request access to the PO database and parse the JSON object with urllib.request.urlopen( "http://10.21.200.98:8081/T/ansdb/api/rows/PO/tickets?User_0001=Pat%20Trevor", timeout=15) as url: complete_data_user_0001 = json.loads(url.read().decode()) # Custom filter to the JSON response # Count the number of times the user has created a PO between two given dates where the PO is not equal to N/A values Counter([k['user_id'] for k in complete_data_user_0001 … -
Multi-Tenant in Django
I am new to Django, can somone please help me understand about multi-tenant. I have gone through online document which only map sub-domain to schema. I would want to know if there is a way to even create multi-tenant databases through django commands. -
In password reset view custom templates not loding?
I am working on rest password via custum templates in django,but custom template not loading it is loading django's default template every time i load the /password_reset/ url. I am using the url url('^', include('django.contrib.auth.urls')), i have a registration folder in templates and using this link to work https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html and the template folder is: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', "cms.utils.context_processors.permission_based_hidding_of_sidebar", ], 'libraries':{ 'template_tag': 'cms.templatetags.template_tag', 'template_tag_time': 'cms.templatetags.tags', } }, }, ] install apps in settings:- INSTALLED_APPS = [ 'cms', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_csv_exports', 'django.contrib.auth', 'django.contrib.admin', ] -
pandas print dataframe in required format
I have data in this form: Sample Cohort CName Intensity S1 a C1 22.34 S2 a C2 17.34 I want to print it in this form Cohort Intensity1 Intensity2 a 22.34 17.34 Please suggest how to do it. I am beginner in pandas -
Serializer dropping related field data
What is the validation order for the latest DRF? My serializer has been mysteriously dropping some related fields but not others. I have tried to find documentation on the validation methods order but cannot find anything on DRF's site. I then added some print statements to a bunch of methods to see where the values get dropped: the field values are present in the view in the request the field values are present in the validate_empty_values call the validate_<field_name> method is not called for the fields in question, but I suspect these methods do not get called for related fields the field values are not present in the validate method This is odd seeing as how other related fields are defined in the exact same way and are working as desired. class PurchaseOrderSerializer(ModelSerializer): retailer_account = RetailerAccountSerializer(read_only=True) address = AddressSerializer() marketplace = MarketplaceAccountSerializer(read_only=True) retailer_product = RetailerProductSerializer(read_only=True) cc_verification = CCVerificationSerializer(read_only=True) seller_restrictions = RetailerSellersRulesListSerializer(read_only=True) class Meta: model = PurchaseOrder fields = ( 'id', 'confirmation_number', 'created', 'marketplace', 'retailer_account', 'retailer_product', 'seller_restrictions', 'address', .... ) def get_actions(self, obj): return obj.transitions def validate_empty_values(self, data): # print('validating empty: ', data) filtered = {} for key, value in data.items(): if not key: continue if value == "": value = … -
Using custom output in Django-Autocomplete-Light
I'm trying to use a custom string for the output for django-autocomplete-light. DAL currently returns the models str or unicode. I would like to return a particular field on the searches rather than the str or unicode methods. For example, if my model is fruit defined as such: class Fruits(models.Model): name = models.CharField() quantity = models.IntegerField() def __str__(self): return self.quantity I would like to return the fruit field 'name', not the quantity. -
Error using Django with Docker - "Can't connect to MySQL server on '127.0.0.1' (111)")
I am trying to use Docker with Django but I get error - db_1 | error: database is uninitialized and password option is not specified db_1 | You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)"). When I am using my app without Docker it works. Any suggestions? -
axios call to server on different port on dev and production for webpack/vue & django web app
I'm using webpack dev server for my vuejs application that runs on port 8080 and a rest api on a django server that runs on another port 8000. What configuration should I use to make an axios call that will work both on dev and on production? On production, I am using gunicorn as web server so I'm guessing I will have to bind it to port 8000 works on dev, but does not work on production axios.get('http://localhost:8000/data', { }) does not work on dev nor production axios.get('/data', { proxy: { host: '127.0.0.1', port: 8000 } }) axios.get('/data', { port: 8000 }) I also tried setting axios.defaults.port = 8000 but the axios call didn't seem to make the call to that port and instead made the call to port 8080 on webpack server -
Using both virtualenv and Docker with Django
I would like to use both virtualenv and Docker with my Django application. I wonder how it should be done. Let's assume that I have one main directory Directory1 where I have my virtualenv and Directory2 with my project. I have my dependencies requirements.txt in Directory3 inside Directory2 Where I should create Dockerfile, docker-compose.yml etc.?