Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pythonanywhere. ImportError: No module named 'crispy_forms'
I have implemented my Django application on 'pythonanywhere' but when I try to load my website in logs I see the following information: 2019-02-27 20:20:37,677: Error running WSGI application 2019-02-27 20:20:37,678: ImportError: No module named 'crispy_forms' 2019-02-27 20:20:37,679: File "/var/www/zen404_pythonanywhere_com_wsgi.py", line 15, in <module> 2019-02-27 20:20:37,679: application = get_wsgi_application() 2019-02-27 20:20:37,679: 2019-02-27 20:20:37,679: File "/home/zen404/.virtualenvs/zen404.pythonanywhere.com/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-02-27 20:20:37,679: django.setup(set_prefix=False) 2019-02-27 20:20:37,684: 2019-02-27 20:20:37,684: File "/home/zen404/.virtualenvs/zen404.pythonanywhere.com/lib/python3.5/site-packages/django/__init__.py", line 24, in setup 2019-02-27 20:20:37,684: apps.populate(settings.INSTALLED_APPS) 2019-02-27 20:20:37,684: 2019-02-27 20:20:37,684: File "/home/zen404/.virtualenvs/zen404.pythonanywhere.com/lib/python3.5/site-packages/django/apps/registry.py", line 89, in populate 2019-02-27 20:20:37,685: app_config = AppConfig.create(entry) 2019-02-27 20:20:37,685: 2019-02-27 20:20:37,685: File "/home/zen404/.virtualenvs/zen404.pythonanywhere.com/lib/python3.5/site-packages/django/apps/config.py", line 90, in create 2019-02-27 20:20:37,685: module = import_module(entry) Of course, I installed a virtual environment and 'crispy_forms' inside. What can trigger this error? When I run the python3 manage.py runserver command inside in Bash PythonAnywhere, the server starts correctly. But in the logs the error is still visible and the page basic does not work. Any help will be appreciated. -
Writing into a current entry instead of creating a new one in django
I'm trying to create a document form and write the document location into the user's current database entry, it keeps creating a new entry when I attempt to do so, aswell as if I attempt to use pk=p in the part that writes the data it will overwrite the entire entry. views.py ** I import everything here ** @login_required(login_url='/accounts/login/') def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): p = request.user.pk newdoc = CustomUser.objects.get(pk=p) newdoc = CustomUser(docfile = request.FILES['docfile']) # I also attempted the following which overwrit the entire user # newdoc = CustomUser(pk=p, docfile = request.FILES['docfile'])) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form current_user = request.user # Render list page with the documents and the form return render(request, 'list.html', {'form': form,'pk':current_user.pk}) models.py for the user from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass def __str__(self): return self.email docfile = models.FileField(upload_to='static/users/',) -
Foreign key to user model not working as expected
Django beginner here.. Tearing my hair out with this problem.. I have a django project with a custom user model. I have this "Subscriptions" model that uses the custom user model as its foreign key. class Subscriptions(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) app_subscriptions = models.CharField(max_length=100) def __str__(self): return self.app_subscriptions But if I try to retreive all users app_subscriptions with "..app_subscriptions_set.all()" it always returns with the following error: AttributeError: 'CustomUser' object has no attribute 'app_subscriptions_set' I have the same type of model in use here: from django.db import models class Software(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Version(models.Model): version = models.CharField(max_length=50) software = models.ForeignKey(Software, on_delete=models.CASCADE) def __str__(self): return self.version And on this model I have no issues querying for all software versions with ...version_set.last() Anyone have any ideas? Thank you in advance. -
the post gets liked when the user submits a comment
I wanted to create a blog on which the users can like and comment but whenever the user submits a comment. 1)the comment isn't saved to the data base 2)the post on which the user comments get liked automatically. the views is meant to handle the back end of the comment section but whenever the comment form isn't empty and the user presses submit it automatically likes the post the code to my project is given below models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField() date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) likes=models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def get_absolute_url(blog_id): return reverse('post-detail',args=[str(blog_id)]) class comment(models.Model): post=models.ForeignKey(Blog, on_delete=models.CASCADE) user=models.ForeignKey(User, on_delete=models.CASCADE) content=models.TextField(max_length=160) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title,str(self.user.username)) views.py from django.shortcuts import render,get_object_or_404 from django.views.generic import ListView from .models import Blog, comment from blog.forms import CommentForm from django.http import HttpResponseRedirect,JsonResponse from django.template.loader import render_to_string class BlogsList(ListView): model=Blog template_name='blog/home.html' context_object_name='blogs' ordering=['-date_posted'] def post_detail(request, id): post=get_object_or_404(Blog, id=id) comments=comment.objects.filter(post=post).order_by('-id') if request.method=='POST': comment_form=CommentForm(request.POST or None) if comment_form.is_valid(): content=request.POST.get('content') new_comment=comment.objects.create(post=post, user=request.user, content=content) new_comment.save() return HttpResponseRedirect(Blog.get_absolute_url(blog_id)) else: comment_form= CommentForm() context={ 'post':post, 'is_liked': post.likes.filter(id=request.user.id).exists(), 'comments':comments, 'comment_form':comment_form, } return render(request, 'blog/post_detail.html',context) forms.py from .models import comment from django import forms class CommentForm(forms.ModelForm): class Meta: … -
how to display the selected options from dropdownlist using django
i have 3 dependent dropdownlists country city road. where the user make its selection the system works as it should. my question is : how to display the selected option on the page? example: selected country = ?? selected city = ?? selected road = ?? i am sending the data from the view as a json where its displayed in dropdownlist what i need is also to send the selected data as a dictionary to be able to display on the template the correct result as the displayed example shows. home.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script>$(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; $.ajax({ type:"GET", url:'/getCity', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }, }); }); $('select#selectcities').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var city_name = optionSelected.text(); data = {'ct' : city_name }; $.ajax({ type:"GET", url:'/getRoads', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectroads option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectroads").append('<option>'+ result[i].name +'</option>'); }; }, }); … -
How to make use of files that are in static folder after deployment in django?
Project Structure This image has project structure, where static folder has all css,js stuff, I am facing the problem of how to add the file's path of static directory after deployment. My project is not fetching required stylesheet. -
Django Two Factor Authentication Setup
I recently asked a question about Django Two Factor authentication here...Django Two Factor Authentication. Based on the feedback I received I am trying to deploy it in my project. I have read the basic installation instructions, but I can't quite figure out how to get it to work in my project... I have installed it via... pip install django-two-factor-auth Then I added it to my settings.py file... INSTALLED_APPS = ( ... 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'two_factor', ) And I have added it to my settings.py file... from django.core.urlresolvers import reverse_lazy LOGIN_URL = reverse_lazy('two_factor:login') # this one is optional LOGIN_REDIRECT_URL = reverse_lazy('two_factor:profile') And I have added it to my urls.py file... urlpatterns = patterns( '', url(r'', include('two_factor.urls', 'two_factor')), ... ) I was using the LoginView from from django.contrib.auth.views via the following import... from django.contrib.auth.views import LoginView I since have changed it to subclass LoginView from two_factor as shown below: from two_factor.views import LoginView Then I set up a two_factor/_base.html file in my project directory... But when I enter the initial credentials of username and password, I get the following message... SuspiciousOperation at /project/login/ ManagementForm data is missing or has been tampered. I'm not sure if any more detailed instructions are available...but I've … -
Can I run Eclipse che on a small VPS?
I have a relatively small VPS that I use as a remote dev environment : 1 vCore 2 Mb of RAM I plan to have up to 3 dev environments on the VPS. I dont need to run 2 simultaneously however. The biggest project is roughly the same size as a small Magento eShop. It is actually run by Python and Django. The environment runs on Ubuntu + Nginx + uWCGI but this could be changed. I can code remotely in the VPS using Eclipse RSE or Codeanywhere. However Eclipse CHE offer very interesting functionalities for this type of remote environment. The main risk is that the VPS configuration is very small. It is exactly the minimal configuration stated in the doc. I don't know if I can use it this way without making things really slow... -
How to link address model to views
I'm trying to create an address form with multiple address, where the user can choose home or shipping address. I have the current model: from django.db import models from django.contrib.auth.models import User from PIL import Image class Address(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60, default="Miami") state = models.CharField(max_length=30, default="Florida") zipcode = models.CharField(max_length=5, default="33165") country = models.CharField(max_length=50) class Meta: verbose_name = 'Address' verbose_name_plural = 'Address' def __str__(self): return self.name # All user data is/should be linked to this profile, so when user gets deleted, all data deletes as well class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nick_name = models.CharField('Nick name', max_length=30, blank=True, default='') bio = models.TextField(max_length=500, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') addresses = models.ManyToManyField( Address, through='AddressType', #through_fields=('address', 'profile') ) # If we don't have this, it's going to say profile object only def __str__(self): return f'{self.user.username} Profile' # it's going to print username Profile def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class AddressType(models.Model): HOME_ADDRESS = 1 SHIPPING_ADDRESS = 2 TYPE_ADDRESS_CHOICES = ( (HOME_ADDRESS, "Home address"), (SHIPPING_ADDRESS, "Shipping address"), ) address = models.ForeignKey('Address', on_delete=models.CASCADE) profile = models.ForeignKey('Profile', on_delete=models.CASCADE) # This is the field you … -
setting default data in django form
i have this 2 models and i have a CreateModel2Form inside model1 DetailView , how can i set a model1 field default to the current One instead of selecting everytime the model1 field from a long list class Model1(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Model2(models.Model): name = models.CharField(max_length=100) model1 = models.ForeignKey(Model1 , on_delete=models.CASCADE) def __str__(self): return self.name class CreateModel2Form(ModelForm): class Meta: model = Model2 fields = ['name', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if "model1" in self.data: try: model1_id = int(request.GET.get("id")) self.fields["model1"] = Model2.objects.get(id=model1_id) except (ValueError, TypeError): print("ValueError, TypeError") -
django date picker input in template
I´m trying to use a date picker widget from a model form in the template. I´ve seen several posts but couldn´t get it working. The one I´m trying now is: Answered question Form.py My form code looks like class FormularioTareas(forms.ModelForm): class Meta: model = Tareas widgets = {'fecha_limite': forms.DateInput(attrs={'class': 'datepicker'})} fields = ["destinatario", "titulo", "tarea", "resuelto", "fecha_limite"] Template In the template I add this script: /* Include the jquery Ui here */ <script> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, yearRange: "1900:2012", }); }); </script> And have this form call in the html <div style="background: white;">{{ tareas_form.fecha_limite }}</div> All of this seems to have no effect, I still get the text input widget in the HTML. Any clues welcome. Thanks! -
How to check if Django Signal works?
I have a model that I want to implement signal's post_save on. Here's my model: class Answer(models.Model): question = models.ForeignKey( Question, related_name='answers_list', on_delete=models.CASCADE) answer = models.CharField(max_length=500) additional = models.CharField( max_length=1000, null=True, blank=True, default=None ) created_at = models.DateTimeField(auto_now_add=True) I'm trying to catch Answer's creation. I've created a new signals.py file with the following context: from django.dispatch import receiver from django.db.models.signals import post_save from core.models import Answer @receiver(post_save, sender=Answer) def answer_question(sender, instance, **kwargs): print("CAUGHT A SIGNAL") print(instance.question.sentence, instance.answer) But when I create a new answer it doesn't seem to trigger the signal (I'm creating it via front-end, since I'm using django-rest-framework). I don't see anything in my console instead of POST method that's going to my API. What's wrong? -
updateview in form validation
updateview in form validation in the form below I'm using uddateview for updates and it's working, but when I type a wrong data, or when I leave a required field, the HTML message appears to clear the field, but that same form, in the normal register, it shows the errors using as_crispy_field, leaving red and with the messages that I wrote How can I make mistakes that are marked without being used by HTML I would appreciate any help views.py class DataUpdate(LoginRequiredMixin, UpdateView): model= Usuario fields = ['nome','sobrenome','cpf','telefone','data_nascimento','sexo','endereco','numero','bairro','cidade','estado', 'cep'] template_name='profile/change-data.html' def get_object(self, queryset=None): if queryset is None: queryset = self.get_queryset() # This should help to get current user # Next, try looking up by primary key of Usario model. queryset = queryset.filter(pk=self.request.user.usuario.pk) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404("No user matching this query") return obj def get_success_url(self): return reverse('sistema_perfil') urls.py url(r'^change-data/$', views.DataUpdate.as_view(), name='sistema_change_data'), change-data.html {%extends 'bases/base.html' %} {% load static %} {% load bootstrap %} {% load widget_tweaks %} {% load crispy_forms_tags %} {% block main %} <div class="container"> <div class="card text-white bg-primary mb-3"> <div class="card-header"><small class="text"> <a href="{% url 'sistema_index' %}" class="text-white ">Home /</a> <a href="{% url 'sistema_perfil' %}" … -
Cryptography error in Django run on Docker
I'm trying to deploy a web site which has a backend developed in Django. I've set two Docker containers which contain a Django instance and a MySQL instance. I've set also a network between containers in order to create a communication. The problem is that when I start the MySQL container with the parameter MYSQL_ROOT_PASSWORD Django gives me the error below: Error given by Django I've checked that the 3306 port is available on my PC, and yes it is. On the other hand, if I start MySQL container with MYSQL_ALLOW_EMPTY_PASSWORD, and set a blank password in settings.py, it works. Here there is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'userpwd', 'HOST': 'db', 'PORT': '3306' } } Instead, this is my docker-compose.yml file version: "3" services: app: build: context: . container_name: app ports: - "8000:8000" networks: - backend_split depends_on: - db restart: always volumes: - ./app:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" db: image: mysql container_name: db expose: - "3306" networks: - backend_split environment: - MYSQL_ROOT_PASSWORD=rootpwd - MYSQL_DATABASE=databasename - MYSQL_USER=username - MYSQL_PASSWORD=userpwd networks: backend_split: I'm stucked into this error days. Thank you in advance. -
Django forms how to dynamically render fields in a loop
Let's say I have a form with some fields. Some of those fields are units of measurements: ['quantity_units', 'weight_units', 'dimension_units'] I also have these fields: ['quantity', 'weight', 'dimension'] I would like to display the unit of measurement right beside the field: Quantity: ___________________ _______<unit of measurement drop-down list>______ I thought I should first loop through the form's fields. For each iteration through the form's fields, I would check if the field name is in the units_list, if it is, then I would render the field and its unit field like so: {% for field in form %} {% for field_name in units_fields %} {% if field.name in field_name %} {{ field|add_class:"site-form-control" }} {{ form.field_name}} {% else %} {% ifchanged %} {{ field|add_class:"site-form-control" }} {% endifchanged %} {% endif %} {% endfor %} {% endfor %} This does not render the unit of measurement field with the drop-down list widget. Any ideas how to fix this? -
How to implement Django (and Allauth) PasswordChangeView (and others views)?
I have a question about using these views, especially with Django-Allauth (which should not be too different). I know that Pass change view changes the password, ok. But it uses a template and a url only for this, but we all know that no project in the world redirects the user to a template only containing inputs to change the password. So how do I join this with other views, for example, a view to change only username, location, email etc? Should I inherit these views and change to only redirect and return messages of success or error? Ex: /profile/ has two forms, one for /profile/changepassword and the other for /profile/changeusername, and the two simply do the work and redirect to /profile/, so the user does not need to go to a template only with the inputs. Or should I do something on the front end for this, like fetch/ajax (which I have not yet studied)? -
Autocomplete search with jquery and AJAX in django webapp
I am trying to implement an autocomplete search by following this tutorial https://medium.com/@ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd And i am failing to implement it, and i think it has something to do with my urls or the way i am putting scripts in my .html file. My search bar is in my index view index.html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> </head> <body> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'KPI/style.css' %}"> <script> $(document).ready(function(){ $("#txtSearch").autocomplete({ source: "/login/index", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); </script> <form id="search" method="POST" action="{% url 'kpi:search' %}"> {% csrf_token %} <input type="text" class="form-control" id="txtSearch" name="txtSearch"> <button type="submit" class="btn btn-default btn-submit">Submit</button> </form> </body> </html> urls.py app_name = 'kpi' urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('login/index/', views.IndexView.as_view()), ] now in the tutorial it says to put this path url(r'^ajax_calls/search/', autocompleteModel), but it doesn't seem like the path has to be this way, so i changed the path to login/index/ and called the class view IndexView which holds the autocompleteModel like so views.py class IndexView(LoginRequiredMixin,TemplateView): template_name = 'KPI/index.html' def autocompleteModel(self,request): if request.is_ajax(): q = request.GET.get('term', '').capitalize() search_qs = Epic.objects.filter(name__startswith=q) results = [] … -
Django captcha - cannot import name 'comment'
I'm trying to add a Captcha form to my Django login. I can see the captcha but the validation is still not working, i keep getting the error: cannot import name 'Comment' from 'main.models' This is what my views.py file looks like: import urllib import urllib2 import json from django.shortcuts import render, redirect from django.conf import settings from django.contrib import messages from .models import Comment from .forms import CommentForm def comments(request): comments_list = Comment.objects.order_by('-created_at') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = json.load(response) ''' End reCAPTCHA validation ''' if result['success']: form.save() messages.success(request, 'New comment added with success!') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return redirect('comments') else: form = CommentForm() return render(request, 'core/comments.html', {'comments': comments_list, 'form': form}) I already tried to remove these two lines: from .models import Comment from .forms import CommentForm But if i remove them the captcha won't work, it will basically let you login without validating it. -
No Post matches the given query
I am using Django version 2. I am working on a blog web app using PostgreSQL database. I am trying to add a search feature to the web app but when I open the url (http://localhost:8000/search/) to make a search, I get the error below. Page not found (404) Request Method: GET Request URL: http://localhost:8000/search/ Raised by: blog.views.post_detail No Post matches the given query. here is the blog/urls.py from django.contrib.postgres.search import SearchVector from .forms import CommentForm, SearchForm from .models import Post, Comment from django.shortcuts import render, get_object_or_404 from django.urls import path from . import views urlpatterns = [ path('', views.PostListView.as_view(), name='home'), path('<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share', views.post_share, name='share'), path('search/', views.post_search, name='post_search'), ] here is the views.py def post_detail(request, post): post = get_object_or_404(Post, slug=post) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment,'comment_form': comment_form}) def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Post.objects.annotate( search=SearchVector('title','body'), ).filter(search=query) return render(request, 'search.html', {'form':form,'query':query,'results':results}) Here are the templates files. For search.html -(page to make … -
Updating a JSON field for each user using Signals
I currently have a JSONfield on my User model that will ocasionally need to be updated, I setup a signal in which I query all users and then try to perform an update: all_users = User.objects.all() Initially, i thought I could update the field value by appending a new key/value to the JSONfield, however, this doesnt seem to be possible: value_updates = all_users.values("json_data").update(json_data.myDictionary[key]= False) so, I am iterating over all the returned values and doing so 1 by 1: and re-querying for the user with the primary key and updating them independently as follows: for item in values_updates: try: usrData = item['json_data'] usrData['key'][instance.title]=False User.objects.filter(pk=item['pk']).update(json_data=usrData) except KeyError as err: print(err) I highly doubt that my approach is optimal (and definitely not scalable) however, I have not figured out some other way to do it. What would be the best approach in achieving this without iterating over all my users in the querySet, fetching and updating the JSONfield and then re-querying the individual users to update the field? -
Serve Django Media Files via Nginx (Django/React/Nginx/Docker-Compose)
Context I have a single page web app using the following stack: React for the frontend Django for the backend Nginx for the webserver The web application is dockerized using docker-compose. My React app, fetches data from the Django server (django is built as an api endpoint using Django Rest Framework). Question/Problem I am having an issue on deployment where I am unable to serve my media files via Nginx. What have I tried so far My initial thought was to serve the media files as shown on this stackoverflow post - which is pretty straight forward. Though, since Nginx runs in its own docker (and so does my django server), I unable to point to my django media files since they are in different containers. Ideally, I would not want to use webpack, and have Nginx take care of serving media files. If you look at the nginx Dockerfile below, you will see that I am copying my static files into /usr/share/nginx/html/static/staticfiles to then serve them using nginx (see location ^~ /static/ in nginx.conf). I have tried to do the same thing for my media file (as a test) and it works - though, all the files I am … -
Is possible to customize the models package path in Django
The default folder structure of a project in Django is something like: myproject/ - myapp/ - models.py - myproject/ - settings.p Would it be possible to change that structure? I'd like to do something like: myproject/ - myapp/ - infrastructure/ - models.py - myproject/ - settings.py or myproject/ - myapp/ - infrastructure/ - models/ - __init__.py - some_model.py - myproject/ - settings.py I know I can make a models package and split the models into different files. But I'm looking to change also the name/path of that package. -
Needing VueJS Getter to only return all values of the last JSON property as an array
I am using a Django REST back-end to ship API data to a VueJS front-end. I am trying to place daily counts in a ChartJS graph. import { HorizontalBar } from '../BaseCharts' export default { extends: HorizontalBar, data() { return{ } }, mounted () { /* Need to write the API call for chart data here. */ this.$store.dispatch("DailyCountAction") this.renderChart({ labels: [this.$store.state.DailyCount], datasets: [ { label: 'Existing Patients', backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1, data: [4,8,2,] }, You can see in the "label" field I have a getter which returns the data: { "Check_In_Count": "7", "Average_Time_Spent": "3", "Average_Wait_Time": "2", "Cancelations": "0", "New_Patient_Count": "4", "Existing_Patient_Count": "3", "Current_Cycle_Date": "2062019" }, { "Check_In_Count": "4", "Average_Time_Spent": "8", "Average_Wait_Time": "6", "Cancelations": "0", "New_Patient_Count": "1", "Existing_Patient_Count": "3", "Current_Cycle_Date": "2072019" }, { "Check_In_Count": "7", "Average_Time_Spent": "3", "Average_Wait_Time": "9", "Cancelations": "0", "New_Patient_Count": "0", "Existing_Patient_Count": "7", "Current_Cycle_Date": "2082019" }, { "Check_In_Count": "8", "Average_Time_Spent": "8", "Average_Wait_Time": "1", "Cancelations": "0", "New_Patient_Count": "4", "Existing_Patient_Count": "4", "Current_Cycle_Date": … -
How can i make post category list visible in all page in django
I am trying to make category name visible in every page. so for that I passed category model to every view. But here it is visible only in category_view.html page only. I want to make it visible everywhere as I am listing out category name in navbar. so far I did this templates/navbar.html <nav class="nav d-flex justify-content-between"> {%for name in category_name %} {% for lst in post %} <a class="p-2 text-muted" href="{% url 'posts:categoryview' slug=name.slug %}">{{name}}</a> {% endfor %} {% endfor %} </nav> views.py from django.shortcuts import render, get_object_or_404,render_to_response from .models import Post, Category # Create your views here. def posts_list(request): query_list = Post.objects.all() category_name = Category.objects.all() context = { "title" : "Latest Post", "query_list": query_list, "category_name": category_name } return render(request, "post_list.html", context) def view_category(request, slug): category = get_object_or_404(Category, slug=slug) category_name = Category.objects.all() return render_to_response('category_view.html', { 'category': category, 'post': Post.objects.filter(category=category).values(), 'category_name': category_name }) urls.py urlpatterns = [ path("", posts_list, name="list"), path("<slug>", view_category, name="categoryview"), ] -
Do I still Need To use cookies and session if i use JWT Django rest_framework
I'm devlopping an app and I want to use jwt to authenticate uses. so, Do I Need To use cookies and session_id and can i delete the form settings?