Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django, who to excess data from models and user it as a conditional in templates
I have profileinfo model that is linked to user model. there are two usertypes student and teacher. I want to display "add courses" link if user is authenticated and usertype is Teacher. if not link should not appear on navbar I have tried following code in templates <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> </head> <body> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'index'%}">YFEA Academy</a> </div class= "nav navbar-nav-right"> {% if user.is_authenticated and user.ProfileInfo.UserType == 'Teacher' %} <ul class="nav navbar-nav"> <li><a href="#">Add Courses</a></li> </ul> {%endif%} {% if user.is_authenticated %} <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'app:logout'%}">Logout</a></li> </ul> {% else%} <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'app:register'%}">Register</a></li> <li><a href="{% url 'app:login'%}">login</a></li> </ul> {%endif%} </div> </nav> {%block body%} {% endblock %} </div> </body> </html> class UserProfile(models.Model): user = models.ForeignKey(User ,related_name = 'ProfileInfo') choices= (('S','Student'),('T','Teacher')) UserType = models.CharField(max_length = 50 , choices = choices) picture = models.FileField(upload_to = 'media', default = None) -
How do I register a tag in Django
I'm trying to add some css styles to a base html file in django version 2.2.0. However, I'm getting the following TemplateSyntaxError: Invalid block tag on line 4: 'static'. Did you forget to register or load this tag? The css file named base.css exists in a directory named static. Here a print screen of the tree command. . ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── blog_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── Pipfile ├── static │ └── css │ └── base.css └── templates ├── base.html └── home.html And here is how I included the css in the base.html file. <html> <head> <title>Django Blog</title> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> <body> <header> <h1><a href="{% url 'home' %}">Django blog</a></h1> </header> <div> {% block content %} {% endblock content %} </div> </body> </html> Here is how I have my static files directory inside the settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] My installed apps list inside settings.py looks like this: INSTALLED_APPS … -
Django: Making boolean form field from value of a Queryset
I want to create a Django Form of all BooleanField. What I want is to make these fields from records/values of a Model's queryset. For example: Let my model be ABC with 3 records 1. name=xyz country=India 2. name=rst country=Australia 3. name=pqr country=India My form should look like this for every India entry for country: xyz=forms.BooleanField() pqr=forms.BooleanField() Please anyone help! -
How to use grammar-check for python in view in django
I have installed grammar_check in a virtualenv and the I created a django project. Then in a my view I imported grammar_check and used it on some text but the issue is that I am getting import error. I don't understand what is the problem here. Traceback (most recent call last): File "c:\users\saqib\appdata\local\programs\python\python36\Lib\threading.py", line 916, in _bootstrap_inner self.run() File "c:\users\saqib\appdata\local\programs\python\python36\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\utils\autor eload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\core\manage ment\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\core\manage ment\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\core\manage ment\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\core\checks \registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\core\checks \urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\core\checks \urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\utils\funct ional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Saqib\Desktop\tbw\code\pro\lib\site-packages\django\urls\resolv ers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'gcpro.urls' d oes not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here is my view function: import grammar_check def output_text(request): if request.method == 'GET': name= … -
Django API is not returning URLs with the port in URLs so the links are broken. How to include the port?
I have a basic Django API working in development when I launch via the runserver command. I am returning a list of objects including the URL of an image in my media folder. In development, this image URL includes the port as shown below. The link works fine when I click it in the browser. "image_url": "http://0.0.0.0:1337/mediafiles/publisher/sample-image4.jpg", In production (gunicorn, nginx, docker) everything works the same except the URLs returned by the API do not include the port, so the links are broken. How can I ensure the port is included even in production? "image_url": "http://0.0.0.0/mediafiles/publisher/sample-image4.jpg", My guess is it could be an nginx config issue since it works in development server, but I don't really know where the problem is so my searches are not really helping. I'm still quite new to nginx, django and docker. settings.py ... STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') ... docker-compose.yml version: '3.7' services: web: build: ./app command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles ports: - "8000" env_file: ./app/.env environment: - DB_ENGINE=django.db.backends.postgresql - DB_USER - DB_PASSWORD - DB_HOST=db - DB_PORT=5432 - DATABASE=postgres depends_on: - db networks: - backend nginx: build: ./nginx … -
how to display many to many field properly in django
This code saves the data and displays the data as i wanted.but while displaying courses it displays like this , ]> .It displays with QuerySet[].i only want the courses name to be displayed.How can i do that models.py class Teacher(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField() image = models.ImageField(upload_to='Teachers',blank=True) courses = models.ManyToManyField(Course) views.py def viewteacher(request): teachers = Teacher.objects.all().order_by('-joined_date') year1 = datetime.datetime.today().year return render(request,'students/view_teacher.html',{'teachers':teachers,'year_list':range(2016,year1+1)}) template {% for teacher in teachers %} <tr> <td>{{teacher.name}}</div></td> <td>{{teacher.courses.all}}</td> <td>{{teacher.address}}</td> <td>{{teacher.phone}}</td> <td><a href="{% url 'students:profile_teacher' teacher.id %}">Profile</a></td> <td><a href="{% url 'students:edit_teacher' teacher.id %}">Edit</a></td> <td><a href="{% url 'students:confirm_delete_teacher' teacher.id %}">Delete</a></td> </tr> {% endfor %} </tbody> -
Display only last unread message associated with same user Django
I have a notification dropdown that displays unread messages in any threads that the logged in user is a part of. Example, Sam and Jane. Jane is in 3 threads with 3 different people. Sam has sent her 6 messages in a row. Right now, the notification dropdown displays all 6 unread messages from Sam, which is inefficient. Even though the red unread notification will show 6 the dropdown should display only the last unread message from Sam. I'm having trouble with this because I don't know what to filter by in order to extract/display only the last message. The Notification model only has 3 fields. class Notification(models.Model): notification_user = models.ForeignKey(User, on_delete=models.CASCADE) notification_chat = models.ForeignKey(ChatMessage, on_delete=models.CASCADE) notification_read = models.BooleanField(default=False) When a user sends a message, it is saved as a Notification object with the receiving user as notification_user. So right now I have this function def notification(request): if request.user.is_authenticated: notification = Notification.objects.filter(notification_user=request.user, notification_read=False) notification_read = Notification.objects.filter(notification_user=request.user, notification_read=True) return { 'notification':notification, 'notification_read':notification_read } return Notification.objects.none() Which displays all read/unread notifications associated with the logged in user, but that obviously shows all 6 messages from Sam. models.py class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) … -
Dependent drop-down chained django-filter
****Stuck**how do i get the dependent filters on two fields,, i want to make a filter not form** #models.py class FinanceAccountDetail(models.Model): accountName = models.CharField(max_length=40) msdmName = models.CharField(max_length=80) deliveryManagedFrom = models.CharField(max_length=40) marketName = models.CharField(max_length=20) isActive = models.BooleanField(default=True) year = models.IntegerField ( default=2019 ) sdu_id = models.IntegerField ( default=1) def __str__(self): return u'%s' % (self.accountName) How to make two fields dependent in filters.py #filters.py class dashboard_filter(django_filters.FilterSet): deliveryManagedFrom = django_filters.ModelChoiceFilter(queryset=FinanceAccountDetail.objects.values_list('deliveryManagedFrom',flat=True).distinct()) accountName = django_filters.ModelChoiceFilter(queryset=FinanceAccountDetail.objects.values_list('accountName',flat=True).distinct()) class Meta: model = FinanceAccountDetail fields = ['accountName', 'deliveryManagedFrom'] "I want to filter and hen use these filter to make querysets" "Dependent filter" "Dependent filter" "Dependent filter" "Dependent filter" "Dependent filter" "Dependent filter" "Dependent filter" views.py def Dashboard(request , *args , **kwargs): q = {k: v for k , v in request.GET.items () if v} total_budget_usd_queryset = FinanceAccountDetail.objects.filter(**q).aggregate(budget=Sum(F('budget__january' ) + F ( 'budget__february' ) + F ( 'budget__march' ) + F ( 'budget__april' ) + F ( 'budget__may' ) + F ( 'budget__june' ) + F ('budget__july' ) + F ( 'budget__august' ) + F ( 'budget__september' ) + F ( 'budget__october' ) + F ( 'budget__november' ) + F ( 'budget__december' ) ) ) total_usd_budget = total_budget_usd_queryset['budget'] month_query = Hours.objects.values_list ( 'month' ).distinct () month_final = [item for sublist … -
Error while saving many to many field in django
I am trying to save teachers with many courses but i got error while saving.I am using custom form and i want to use custom form for this.How can i solve this??Error is like this Django Version: 2.1.5 Exception Type: ValueError Exception Value: "" needs to have a value for field "id" before this many-to-many relationship can be used. models.py class Teacher(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField() image = models.ImageField(upload_to='Teachers',blank=True) courses = models.ManyToManyField(Course) views.py def addteacher(request): courses = Course.objects.all() if request.method == 'POST': form = AddTeacherForm(request.POST,request.FILES) if form.is_valid(): teacher = form.save(commit=False) course = form.cleaned_data['courses'] # teacher.courses = course teacher.courses.set(course) teacher.save() messages.success(request,'Teacher with name {} added.'.format(teacher.name)) return redirect('students:add_teacher') else: return HttpResponse(form.errors) else: form = AddTeacherForm() return render(request,'students/add_teacher.html',{'form':form,'courses':courses}) template <div class="form-group"> <h5>Courses<span class="text-danger">*</span></h5> <div class="controls"> {% for course in courses %} <input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.id}}"> <label for="course-{{course.id}}">{{course.title}}</label> {% endfor %} </div> </div> -
invalid literal for int() with base 10: b'25 18:12:59.592724'
I added the following two functions to Board model and I am getting above error: class Board(models.Model): name = models.CharField(max_length=150, unique=True) description = models.CharField(max_length=150) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(topic__board=self).count() def get_last_post(self): return Post.objects.filter(topic__board=self).order_by('-created_at').first() Then I applied migration after running the server I get this error, here is a full trackback: Environment: Request Method: GET Request URL: http://localhost:8000/board/1/ Django Version: 2.2.1 Python Version: 3.7.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'board.apps.BoardConfig', 'crispy_forms', 'accounts', 'widget_tweaks'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Administrator\Desktop\board0a\src\board\templates\board\base.html, error at line 23 invalid literal for int() with base 10: b'25 17:52:56.629918' 13 : <link rel="stylesheet" href="{% static 'css/mystyle.css' %}"> 14 : 15 : {% block stylesheet %} 16 : {% endblock stylesheet %} 17 : 18 : </head> 19 : 20 : <body> 21 : <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> 22 : <a class="navbar-brand" href="{% url 'board:home' %}">Navbar</a> 23 : <button class="navbar-toggler" type="button" data-toggle="colla pse" data-target="#navbarSupportedC ontent" 24 : aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> 25 : <span class="navbar-toggler-icon"></span> 26 : </button> 27 : 28 : <div class="collapse navbar-collapse" id="navbarSupportedContent"> 29 : <ul class="navbar-nav mr-auto"> 30 : <li class="nav-item active"> 31 : <a class="nav-link" href="{% url 'board:home' %}">Home … -
DJANGO How to make a Q query that can filter between two values?
I am making a real estate application in which I am stuck right now on a search functionality . My main problem is that I have to make a search function that can filter a query set based on the choices user chooses. And i am able to do it but the problem is there are two options that user can filter on and that's area and price and they both have min and max value so how I have to make a filter that can take both min and max values and then present the filter queryset which contains the objects that have values between the min and max. Here's my search function def search(request): queryset = models.Property.objects.all() query1 = request.GET.get('q1') query2 = request.GET.get('q2') query3 = request.GET.get('q3') query4 = request.GET.get('q4') query5 = request.GET.get('q5') query6 = request.GET.get('q6') if query: queryset = queryset.filter( Q(status__icontains=query)| Q(address__icontains=query2)| Q(rooms__icontains=query3)| Q(bathroom__icontains=query4)| Q(area__icontains=query5)| Q(price__icontains=query6) ).all() return render(request,'properties/properties_search_list.html',{'queryset':queryset}) Here's the area and price code in html <div class="range-slider"> <label>Area</label> <div data-min="0" data-max="10000" data-min-name="min_area" data-max-name="max_area" data-unit="Sq ft" class="range-slider-ui ui-slider" aria-disabled="false" name="q5" ></div> <div class="clearfix"></div> </div> <div class="range-slider"> <label>Price</label> <div data-min="0" data-max="150000" data-min-name="min_price" data-max-name="max_price" data-unit="USD" class="range-slider-ui ui-slider" aria-disabled="false" name="q6" ></div> <div class="clearfix"></div> </div> -
ModuleNotFoundError: No module named 'Blog'
Made a new app called Blog and now not able to import it. created basic apps called products, pages. Now adding one more app called Blog into the project. Not able to solve migrate issues and terminal ends up with no model named 'Blog' import error: Here is my directory structure: Dev -python3 -trydjango -src -blog -migrations -templates HTML FILES PYTHON FILE -pages -products -migrations -templates -templates -trydjango SETTINGS,URL,WSGI here is BLOG/models.py file: from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=120) abstract = models.CharField() author = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) here is Blog/view.py file: from django.shortcuts import render from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, ListView, DeleteView ) from .models import Article # Create your views here. class ArticleListView(ListView): queryset = Article.objects.all() -
Connecting an HTML page to Django page
I need to make a project in which statistics are needed and have to be made with matplotlib. For this I need to use Django, the goal is to create a project in Django that shows you 3 graphics of statistics. The problem is that I need to make it from an HTML page and by pressing a button it redirects you to the Django's that shows the graphics. I have practically no knowledge in Django, but I know Python. My main problem is how to create that Django web page that executes the graphics script and how to make the HTML reference to the Django page. -
Adding a positive integer field causes "invalid literal for int() with base 10" error
When I add 'views' field to Topic model I get above here. here is the details. I added 'views' field at Topic model, see code below class Topic(models.Model): subject = models.CharField(max_length=225) last_updated = models.DateField(auto_now_add=True) board = models.ForeignKey( Board, on_delete=models.CASCADE, related_name='topics') starter = models.ForeignKey( User, related_name='topics', on_delete=models.CASCADE,) views = models.PositiveIntegerField(default=1) # here Then applying migrations and finally adding this to view function in order to count number of views a topic has been seen. def view_topic(request, pk, topic_pk): topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk) topic.views += 1 # here topic.save() # here return render(request, 'board/view_topic.html', {'topic': topic}) and adding that view field in my template as : <td>{{ topic.views }}</td> Then when I run the server, I get this error: invalid literal for int() with base 10: b'25 18:12:59.592724' I read some other answers, and bring the following changes in views and models still it didn't solved the problem. in views I changed above with topic.views += int(1) and in models I changed above code with models.PositiveIntegerField(default=int(1)). In a nutshell, I added int() around every numeric value I find. That still didn't solve the problem. Can you help me solve it? Thanks -
Is there any way to customize the order of multiple fields for forms.Form class with a field initiated by __init__?
When I render the form to a HTML template, a certain field of form which is initiated by init is ordered always at bottom of table, even though I defined the field at the middle of form class. Is there any way or method to customize the order of fields in the form where a initiated field exists by init. I wanna put the field in the middle of form table in HTML template. the screenshot of the template is the link below: https://i.stack.imgur.com/t7tNu.png I am using Django 2.2 and python 3.7 on Windows 10. Thanks from django import forms from .models import Category_name class MakePurchaseLog(forms.Form): buy_date = forms.DateField(input_formats=['%Y-%m-%d']) shop = forms.CharField(max_length=50) def __init__(self, user, *args, **kwargs): super(MakePurchaseLog, self).__init__(*args, **kwargs) self.fields['category_name'] = forms.ChoiceField( choices = [(item.category_name, item.category_name) \ for item in Category_name.objects. \ filter(owner=user)]) goods_name = forms.CharField(max_length=50) price = forms.IntegerField(min_value=0) memo = forms.CharField(max_length=50, required=False) field_order = ['category_name'] -
Django: How to create a Group through a command?
I want to automate all the data creation on my data base, for this I'm using different commands. I know how to do this for my models, because I know its fields. But how to do this for Group model? from django.contrib.auth.models import Group When I query its fields I get: 'user', 'id', 'name', 'permissions' [f.name for f in Group._meta.get_fields()] But in Admin Panel I only See that in order to create a Group the name and the permission fields are required: command: import pandas as pd from django.contrib.auth.models import Group from django.core.management.base import BaseCommand tmp_data_groups=pd.read_csv('static/data/groups.csv',sep=',', encoding='iso-8859-1').fillna(" ") class Command(BaseCommand): def handle(self, **options): groups = [ Group( name=row['name'], permissions=row['permissions'] ) for _, row in tmp_data_groups.iterrows() ] Group.objects.bulk_create(groups) I get this error (with the command or in shell): TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. Example using the shell: I've a Group named "Clientes" and it has assigned all the permisions. Group.objects.all()[0].permissions.all() #Clientes is the only group created I wan to create a new group called "NuevosClientes" (NewClients in english). Group.objects.create(name='NuevosClientes', permissions='Can view user') Tried this but got: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use … -
Cannot remove folders from django media root
I'm trying to delete the directory from MEDIA_ROOT with shutil. After I have processed the files in the MEDIA_ROOT, I just want to clean up the directory along with the files in it. But getting permission denied error while using shutil. The default user is myuser. Is there a way to set folder with delete permission. I even tried the following permission in settings.py. FILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o755 FILE_UPLOAD_PERMISSIONS = 0o644 -
'str' object has no attribute 'db'
I'm trying to save a model but i'm receiving the error 'str' object has no attribute 'db' class User(models.Model): _username = models.CharField(max_length=250) _email = models.CharField(max_length=250) _name = models.CharField(max_length=250) _state = models.CharField(max_length=250) _avatar_url = models.CharField(max_length=250) _web_url = models.CharField(max_length=250) _is_admin = models.BooleanField() _created_at = models.DateTimeField() -
Edit data and save it to database in Django
I am a newbie. I'm creating restaurant order management system which once the customer order food, the kitchen side can retrieve the customers' order and change the status of their food (example: cooked or ready to be served). I want to edit the status of customers' order by using the select option, save it to database when i click "change status" button, and show it to kitchen_page.html page. But i am not sure how to do it? Anyone can help me to do it? Here is my templates: views.py: def kitchen_view(request): chef_view = OrderItem.objects.all() #chef_view = OrderItem.objects.get(OrderId=OrderId) return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view}) if request.method == "POST": OrderId = request.POST.get("OrderId") Status = request.POST.get("Status") chef_view.OrderId = OrderId chef_view.Status = Status get_status = chef_view.save() return render(request, 'restaurants/kitchen_page.html', {'chef_view':chef_view}) -
Static css and js not loading in django
My settings.py is STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') My base .html is {% load staticfiles %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'css/master.css' %}"> <script src="{% static "js/master.js" %}" type="text/javascript"></script> </head> In my file.html {% extends "base.html" %} {% block head %} {% endblock %} {% block content %} {% endblock %} My directory root -project directory -->appname -->Static ---->css ------>master.css ---->js ----->master.js The error message I get is "GET /static/css/master.css HTTP/1.1" 404 77 "GET /static/js/master.js HTTP/1.1" 404 77 What I do to correctly load the .css and .js on the development server ? -
Cannot create file in pycharm
]2 I'm trying to create a file in pycharm. I get an error 'Cannot create file'. I tried restarting pycharm too. I get the same error. This happens not only while creating python files, but any other type of files too. -
Django Save extra_data from Twitter(social-auth-app-django)
Django2.1 social-auth-app-django I want to save user's avatar from extra_data.But I do not know how. Similar posts have been written in the past, but I can not do the same. (Is the information old?)[post]:django django-allauth save extra_data from social login in signal What I do now is to get avatar from the logged-in user extra_data. However, because I can not save it, I can not use it at the time of logout. settings.py SOCIAL_AUTH_TWITTER_EXTRA_DATA = [ ('name', 'name'), ('profile_image_url_https', 'picture'), ('link', 'profile_url'), ] -
how can i get rid of space and amp inside of django template variable without using js or html
I am not sure how to remove spaces and &amp in the django template variable. Actually I rendered a url string as django variable when I load a page. But it automatically contains &amp and spaces. After all, in html view, it is showed with &amp, % inside of the variable when I print it out in js console. Of course, I can fix in js code by replacing them, but code will get messy so I want to another way with python or django code. any ideas to remove them in server-side? Result: http://127.0.0.1:8000/users?key=fff&ids=(1%,3%,4%,12%) what I expect: http://127.0.0.1:8000/users?key=fff&ids;=(1,3,4,12) -
How can I call a function and pass a arguument to it when the user clicks on it?
I've created a virtual machine dashboard. It interacts with my VMWare server. I display data about my virtual machines. If a Virtual Machine is off, I added a button to turn it on. I want to execute a function I created in a module that's in the app/modules directory. I'm not sure how to do that. dashoardapp/modules/poweronvm.py import atexit from pyVim import connect def reboot_vm(uuid): si = connect.SmartConnectNoSSL(host='10.0.0.202', user='administrator@vsphere.local', pwd='Nuclab@1515') vm = si.content.searchIndex.FindByUuid(None, uuid, True, False) vm.PowerOn() Each button has the UUID added to the 'id'. I figured with some jquery (maybe) i can pass the ID to the function but I can't seem to figure how to do this. Most of the examples I found online don't apply to what I want to do. example of the button being generated in the dashboard.html template (you will see the UUID there) <button type="button" class="btn btn-outline-success btn-sm" id="564d5283-b51b-f5b5-d5c9-0bee2ea23169">TURN ON</button> Any help would greatly be apperciated. -
Django requiments.tx with Security vulnerability
I have a project in GitHub, which after the commit is displaying security vulnerabilities in your dependencies message in the requirements.txt file. I tried to identify, but I could not. Below the requirements.tx file: astroid==2.0.4 autopep8==1.3.5 Dijkstar==2.4.0 dj-database-url==0.5.0 Django==2.1 django-cors-headers==2.4.0 django-heroku==0.3.1 djangorestframework==3.8.2 gunicorn==19.9.0 isort==4.3.4 lazy-object-proxy==1.3.1 mccabe==0.6.1 psycopg2==2.7.5 psycopg2-binary==2.7.5 pycodestyle==2.4.0 pylint==2.1.1 pytz==2018.5 six==1.11.0 typed-ast==1.1.0 whitenoise==4.1 wrapt==1.10.11