Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Back-end vs front-ent django vs react and tensorflow.js
I am not completely sure whats the difference between front-end and back-end Is, some rough definitions you find around are that front-end is just the user interface, and the back-end is the functionality. But in principle, you can also implement the functionality in javascript, and part of the UI can also be the functionality of the website. For example if you have a calculator web app, the rendering can go along side with the functionality (you can hard code the calculations and render them). Can you clarify this and maybe illustrate it with a clear example? Does front-end mean that it runs completely on the browser and back-end runs on the server? Can a python app run completely on the browser? if not, why? for example if you just render the views with Django for a static web app, would this run locally on the browser? or it would run on the server? why? What is the advantage of running tensorflow conpletely on the browser with tensorflow.js? Isn't it better to just use python and tensorflow to run a machine learning model? Meaning that you could build the whole web app with Django or flask. Why do companies use Django … -
Can't get Celery to work on digital ocean droplet with prod settings
It is working fine on local server, but when I try to start a worker after ssh I get an error. /var/www/bin/celery -A stock worker -l info I know DJANGO_SETTINGS_MODULE is set correctly as I have a print statement showing it is set, (and the rest of the server is live, using production settings). I've also tried using this command, which gives the same error. DJANGO_SETTINGS_MODULE="stock.settings.pro" /var/www/bin/celery -A stock worker -l info I have a celery directory that is in my main directory (beside my settings directory). It contains an init.py file and a conf.py (that sets the results backend). Here is the init file: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stock.settings.pro') DJANGO_SETTINGS_MODULE = os.environ.get('DJANGO_SETTINGS_MODULE') print("celery - ", DJANGO_SETTINGS_MODULE) BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') app = Celery('stock') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.broker_url = BASE_REDIS_URL app.conf.beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler' Here is the traceback error: Traceback (most recent call last): File "/var/www/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/www/bin/celery", line 8, in <module> sys.exit(main()) File "/var/www/lib/python3.8/site-packages/celery/__main__.py", line 16, in main _main() File "/var/www/lib/python3.8/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) … -
MultiValueDictKeyError on django
home.html {% extends 'base.html'%} {%block content%} <h1>hello word{{name}}</h1> <form action="add"> <label>fname</label><input type="text" name="fn"> <label>lname</label><input type="text"name="ln"> <input type="submit" > </form> {%endblock%} base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body bgcolor="red"> {%block content%} {%endblock%} <p>hello dhiraj how are you</p> </body> result.html {% extends 'base.html'%} {%block content%} Result is :{{result}} {%endblock%} urls.py from django.urls import path from .import views urlpatterns = [ path('',views.index ,name="index"), path('add',views.add,name="add") ] views.py def index(request): return render(request,'home.html',{'name':'dhiraj'}) def add(request): val1=request.GET["fn"] val2=request.GET["ln"] res=val1+val2 return render(request,'result.html',{'result':res}) getting error is Quit the server with CTRL-BREAK. Internal Server Error: /add Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'fn' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dhiraj Subedi\fpro\fproject\fapp\views.py", line 11, in add val1=request.GET["fn"] File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'fn' [09/May/2021 17:14:11] "GET /add? HTTP/1.1" 500 73579 Internal Server Error: /add Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'fn' During handling of … -
Logout feature not working using Django REST API at backend and React at frontend
Registration and login feature working fine but using the same approach I am unable to logout user after login ... please tell me what I am doing wrong... // CHECK TOKEN & LOAD USER export const loadUser = () => (dispatch, getState) => { // User Loading dispatch({ type: USER_LOADING }); axios .get("/auth/user/", tokenConfig(getState)) .then((res) => { dispatch({ type: USER_LOADED, payload: res.data, }); }) .catch((err) => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: AUTH_ERROR, }); }); }; // LOGIN USER export const login = (username, password) => (dispatch) => { // Headers const config = { headers: { "Content-Type": "application/json", }, }; // Request Body const body = JSON.stringify({ username, password }); axios .post("/auth/login/", body, config) .then((res) => { dispatch({ type: LOGIN_SUCCESS, payload: res.data, }); }) .catch((err) => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: LOGIN_FAIL, }); }); }; // REGISTER USER export const register = ({ username, password, email }) => (dispatch) => { // Headers const config = { headers: { "Content-Type": "application/json", }, }; // Request Body const body = JSON.stringify({ username, email, password }); axios .post("/auth/registration/", body, config) .then((res) => { dispatch({ type: REGISTER_SUCCESS, payload: res.data, }); }) .catch((err) => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: REGISTER_FAIL, }); }); }; // … -
How to add the 'id' of a django model in a django form
So I want to associate a comment with a transfernews and so I have to get the transfernews id and auto populate the transfernews id in the transfernews field of my comment form. But currently in my comment form, it is showing the transfernews field and it is letting my users select which transfernews to comment on. How can I change my code so that my view fetches the transfernews id and assigns it to the transfernews field of my comment form and hides it from my users. My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body', 'transfernews') My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.save() return redirect(request.path_info) return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My transfernews.html: <h2>Comments...</h2> {% if not transfer.comments.all %} No comments Yet... {% else %} {% for comment in transfer.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added … -
Put a django forms CheckboxSelectMultiple into a dropdown
I'm working on a django project where I have to put multiple checkboxes into a dropdown. The field is modelmultiplechoicefield like this : towns = forms.ModelMultipleChoiceField(queryset=models.Town.objects.all(),required=False,widget=forms.CheckboxSelectMultiple(#widget=s2forms.Select2MultipleWidget()) It gives a list of checkboxes which I want to put into a dropdown. I tried a solution given in a similar question but the jquery SumoSelect is not working eventhough I have the required jquery version it states that it's not found. -
Django Filters How to return queryset with on else conditions
I have following Model. Bus and Covid Seat Layout Models. class Bus(BaseModel): bus_company = models.ForeignKey(BusCompany, on_delete=models.CASCADE) layout = models.ForeignKey( SeatLayout, on_delete=models.SET_NULL, null=True ) class CovidSeatLayout(BaseModel): layout = models.ForeignKey(SeatLayout, on_delete=models.CASCADE) bus_company = models.ForeignKey(BusCompany, on_delete=models.CASCADE) locked_seats = models.ManyToManyField(Seat) I have set my serializers in following way such that if there is covid seat layout then it gives information/list from CovidSeatLayout else It gives Bus list both filtered based on bus company So here is my serializers. class ListCovidSeatLayoutSerializers(serializers.Serializer): id = serializers.CharField(source='layout.id') image = serializers.ImageField(source='layout.image') name = serializers.CharField(source='layout.name') covid_layout = serializers.CharField(source='id') I usually use usecase.py to put my logics here is my usecase.py class ListBusCompanyLayoutUseCase: def __init__(self, bus_company: BusCompany): self._bus_company = bus_company def execute(self): return self._factory() # return self.covid_layout def _factory(self): # Filtering BusCompany From CovidSeatLayout self.covid_layout = CovidSeatLayout.objects.filter(bus_company=self._bus_company) # self. self.bus = Bus.objects.filter(bus_company=self._bus_company) if len(self.covid_layout) == 0: return self.bus else: return self.covid_layout Basically I want to send none in serializer covid_layout if there is no covid layout. Ps the above usecase.py code gets ultimately called on views.py and we are sending bus_company instance from views to usecases. How can I sort this out? -
NameError: name '_mysql' is not defined -- On airflow start in MacOSX
There are numbers of articles on the titled question but none of them worked for me. The detailed error is as follows: Traceback (most recent call last): File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Expected in: flat namespace in /Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/hiteshagarwal/Documents/venv/bin/airflow", line 25, in <module> from airflow.configuration import conf File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/airflow/__init__.py", line 47, in <module> settings.initialize() File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/airflow/settings.py", line 403, in initialize configure_adapters() File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/airflow/settings.py", line 326, in configure_adapters import MySQLdb.converters File "/Users/hiteshagarwal/Documents/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined If I uninstall mysqlclient from python envioronment with pip then I am getting the error like this and then my airflow webserver and schedulers run but not airflow worker while in above case any of the airflow command don't work. -------------- celery@Hiteshs-MBP v4.4.7 (cliffs) --- ***** ----- -- ******* ---- Darwin-20.3.0-x86_64-i386-64bit 2021-05-09 16:11:23 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: airflow.executors.celery_executor:0x7fe6603a9668 - ** ---------- .> transport: sqla+mysql://airflow:**@localhost:3306/airflow - ** ---------- .> results: mysql://airflow:**@localhost:3306/airflow - *** --- * --- .> … -
customising django allauth templates
mostly trying to modify the email verification that is sent on sign-up following the allauth documentation the sent email is modified when i change email_confirmation_message.txt but when i want to use an html representaion the documentation says to use email_confirmation_message.html but it is not recognized and instead it sends the default email or if i include both it only sneds the text one and ignores the html email_confirmation_message.html : {% extends "account/email/base_message.txt" %} {% load account %} {% load i18n %} {% block content %}{% autoescape off %}{% user_display user as user_display %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %} <!doctype html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <title>Snippet - GoSNippets</title> <link href='https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css' rel='stylesheet'> <link href='' rel='stylesheet'> <script type='text/javascript' src=''></script> <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js'></script> <script type='text/javascript' src='https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js'></script> </head> <body oncontextmenu='return false' class='snippet-body'> <div style="display: none; font-size: 1px; color: #fefefe; line-height: 1px; font-family: 'Lato', Helvetica, Arial, sans-serif; max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden;"> We're thrilled to have you here! Get ready to dive into your new account. </div> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"> <tr> <td bgcolor="#ffffff" align="left" style="padding: 20px 30px 40px 30px; color: #666666; font-family: 'Lato', Helvetica, Arial, sans-serif; font-size: 18px; font-weight: 400; … -
Non logged in user in django. how can they see profile photo of author and full name which is created by profile model from account.models.py
first of all i am very sorry i don't know how to ask it. account/models.py from django.db import models from django.conf import settings from django.contrib.auth import get_user_model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles') date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) full_name = models.CharField(max_length=100, blank=True, null=True, default="Jhon Doe") def __str__(self): return self.full_name class Contact(models.Model): user_from = models.ForeignKey('auth.User', related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey('auth.User', related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' # Add following field to User dynamically user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) blog/models.py from django.conf import settings from django.db import models from django.urls import reverse from django.utils import timezone from django.contrib.auth.models import User from taggit.managers import TaggableManager from category.models import Category from account.models import Profile class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class DraftedManager(models.Manager): def get_queryset(self): return super(DraftedManager, self).get_queryset().filter(status='draft') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=256) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='post_category') cover = models.ImageField( upload_to='cover/%Y/%m/%d', default='cover/default.jpg') slug = models.SlugField(max_length=266, unique_for_date='publish') author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() published = PublishedManager() drafted = … -
Django deployment not loading static files in Google app engine
Hi I am trying to deploy django app on Google app engine. My Django app works fine in the locally but in google app engine it is not working. I checked and found that issue is with my static files. My static files are not getting loaded in app engine. ********.appspot.com/static/youtube/about.css Not Found The requested resource was not found on this server. Its been two days I have trying to follow answers on various forums but none worked for me. I have following in my settings.py my settings.py code snapshot # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'youtube', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sitemaps', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Just for your information, I tried changing STATIC_ROOT to 'static' but didn't work. STATIC_ROOT = 'static' STATIC_URL = '/static/' My directory structure: my project dir structure My HTML file from app youtube, and app directory structure about page html file snapshot <link rel="stylesheet" type="text/css" href="{% static 'youtube/about.css' %}"> My App.yaml runtime: python env: flex runtime_config: python_version: 3.7 entrypoint: gunicorn -b :$PORT yt_analytics.wsgi … -
so many warning of pylint as Missing function or method docstring
from django.shortcuts import render,HttpResponse from .models import Question def index(request): qlist =Question.objects.all() output = ','.join([q.question_text for q in qlist]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." %question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) error { "resource": "/d:/openjournalitiom/openjournalism/polls/views.py", "owner": "python", "code": "missing-function-docstring", "severity": 2, "message": "Missing function or method docstring", "source": "pylint", "startLineNumber": 4, "startColumn": 1, "endLineNumber": 4, "endColumn": 1 } Missing function or method docstring -
Doing a POST with both data and file to multiple models
I'm trying to send some data and files when creating a new post in my tables. I want to be able to send both the data for the fields and file/files at the same time. My models: class Tool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("Name"), max_length=70) description = models.TextField(_("Description"), blank=True) department = models.ManyToManyField( "models.Department", verbose_name=_("department"), blank=True) tag = models.ManyToManyField( "models.Tag", verbose_name=_("tag"), blank=True) byUser = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("createdby"), related_name="byuser", blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): """returning a string representation of Tool""" return self.name class ImageTool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True) tool = models.ForeignKey( Tool, on_delete=models.CASCADE, related_name='images') image = models.ImageField( _("Image"), upload_to=tool_image_file_path, blank=True, null=True) byUser = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("createdby"), related_name="byuser", blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): """Returning a string representation of the image""" return '%s %s' % (self.tool, self.name) class Department(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("Name"), max_length=70) description = models.TextField(_("Description"), blank=True) history = HistoricalRecords() def __str__(self): return self.name class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("Name"), max_length=70) description = models.TextField(_("Description"), blank=True) def __str__(self): """Return string representation of tag""" return self.name This is my unittest right now. def test_upload_image_when_creating_tool(self): """ Creating a tool and upload image at the same time """ uuidTool = '2f44ab21-4e05-4e0a-ade1-05cdbdbf1cab' … -
django-allauth not saving google extra data
here how my settings.py is # other settings SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': [ 'email', 'public_profile', 'user_friends', 'user_gender', 'user_birthday', 'user_location', 'user_link', 'user_age_range', ], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, # 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'first_name', 'last_name', 'middle_name', 'name', 'short_name', 'name_format', 'gender', 'birthday', 'age_range', 'friends', 'location', 'picture', 'link', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': False, # 'LOCALE_FUNC': 'path.to.callable', 'VERSION': 'v7.0', }, 'google': { 'SCOPE': [ # 'profile', # 'email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/user.emails.read', 'https://www.googleapis.com/auth/user.phonenumbers.read', 'https://www.googleapis.com/auth/user.birthday.read', 'https://www.googleapis.com/auth/profile.agerange.read', 'https://www.googleapis.com/auth/user.addresses.read', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } it's working fine with facebook and i get what i want there, but with google everything works will while signing (asks for permissions.. everything goes will) it authenticates the user and save it on db, but on extra data field i just get { "id": "...", "email": "...", "verified_email": true, "name": "..", "given_name": "..", "picture": "..", "locale": "en" } so what happens to birthday, gender, addresses, agerange and other fields. -
Where do i find senior django developers [closed]
I’m looking for senior django-react fullstack developers for a project. Pays well. Please dm or answer this post -
post form changed to get in view
I am using a createuser html page in my django project with a form that sets method to 'post'. but when recieving the call in the corresponding view it has changed to 'get' as can be seen in my print(request.method). Why? createuser.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> urls.py: path('createuser',views.createuser,name='createuser'), views.py: def createuser(request): print('method: ',request.method) if request.method=='POST': print('in post') form=SingupForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') raw_password=form.cleaned_data.get('password') user=authenticate(username=username,password=raw_password) login(request,user) return redirect('edit.html') else: form=SignupForm() return render(request,'createuser.html',{'form':form}) else: print('no post..') return render(request,'edit2.html') -
When running pip install channels I get the following this error
ERROR: Command errored out with exit status 1: command: 'E:\Users\S.Mary\Documents\WebProject1\chatty_env\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout\setup.py'"'"'; file='"'"'c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'c:\users\s3c67~1.mar\appdata\local\temp\pip-pip-egg-info-yzixua' cwd: c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout Complete output (5 lines): Traceback (most recent call last): File "", line 1, in File "c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout\setup.py", line 1, in import pathlib ImportError: No module named pathlib ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Nginx Permission Denied but has permission (nginx, gunicorn, django)
I have tried to get rid of the error message for over 6 hours, but I can't still figure it out. At First, I had my Django+React project directory at /home/pi/pidjango and I got a 403 Forbidden(css, js) Error message from Nginx, so I searched for a long time and I moved my project (pidjango) to /home/pi/.local/share and it seemed to be fine. Then I got a 502 Bad Gateway Error, and also fixed that (It was a problem from nginx) and I got 403 error again. It is the error about nginx not getting static files(css, js) and I gave chmod 755 (-rwxr-xr-x) and it still doesn't work. Can anybody solve this? Thank you. I tried this tutorial(but except postgres) $ sudo tail -F /var/log/nginx/error.log *3 open() "/home/pi/.local/share/pidjango/static/css/main.js" failed (13: Permission denied), client: 127.0.0.1, server: localhost, request: "GET /static/frontend/main.js HTTP/1.1", host:"127.0.0.1", referrer: "http://127.0.0.1" *3 open() "/home/pi/.local/share/pidjango/static/css/index.css" failed (13: Permission denied), client: 127.0.0.1, server: localhost, request: "GET /static/frontend/index.css HTTP/1.1", host:"127.0.0.1", referrer: "http://127.0.0.1" *3 open() "/home/pi/.local/share/pidjango/static/css/main.js" failed (13: Permission denied), client: 127.0.0.1, server: localhost, request: "GET /static/frontend/main.js HTTP/1.1", host:"127.0.0.1", referrer: "http://127.0.0.1" # nginx (sites-enabled) server { listen 80; server_name localhost 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location … -
Django View Only Returns Data for one part of QuerySet
I am trying to send the following thing to the front end: Objects (venues in this case) that have been "liked" by somebody the user follows within a particular set of geocoordinates on a Google Map The way my view is currently set up seems to only be sending back the id of the person the user follows but not any of the cafes they have liked (I am testing in a space where this definitely exists). I'm not sure how to fix the problem. Views.py def get_friends(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) geom = Polygon.from_bbox(bbox) friends = UserConnections.objects.filter( follower=request.user ) cafes = mapCafes.objects.filter( geolocation__coveredby=geom, uservenue__user_list__user__pk__in=friends ).distinct() friend_list = [[friend.followed.username] for friend in friends] friend_cafe_list = [[cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x] for cafe in cafes] return JsonResponse([ { 'friends': friend_list, 'cafes': friend_cafe_list } ], safe=False) Models.py class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) … -
New to django, my terminal thinks that there is a syntax error with "path"
path('details/<int:pk>/', ArticleDetailView.as_view(), name="article_details"), my terminal thinks that there is syntax error here, specifically an arrow that points to the 'h' in 'path' i am running ubuntu 18.04 on a jetson nano, and this is in urls.py. terminal page after python3 manage.py runserver -
How to properly add a m2m 'through' field in django models? Now I am getting this error: 'M2M field' object has no attribute '_m2m_reverse_name_cache'
Hey guys I am trying to add a m2m through field to have assistants to my 'Department' model to call like department.assistants.all(), but while doing so, I am getting this error AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'. I also tried migrating everything to a new db to test. This is my model: class Department(models.Model): id = models.BigAutoField(primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) assistants = models.ManyToManyField('Department', through='Assistants', related_name='dep_assistants', symmetrical=False) class Assistants(models.Model): id = models.BigAutoField(primary_key=True) department = models.ForeignKey(Department, related_name='of_department', on_delete=models.CASCADE) assistant = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='dt_assistant', verbose_name="Department Assistant", on_delete=models.CASCADE) added = models.DateTimeField(auto_now_add=True) I am pretty new to this concept. Can someone tell me what I did wrong here? Thanks -
http://127.0.0.1:8000/admin | How to resolve this type errror issue?
https://i.stack.imgur.com/pybod.jpg This type error is coming as output when i am typing http://127.0.0.1:8000/admin. Can anyone help me ? Plz...Need urgent help -
In Django ProgrammingError at /profile/edit/1/ earlier I used sqlite3 database it was fine but when I changed to postgresql it caused this problem
ProgrammingError at /profile/edit/1/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Internal Server Error: /profile/edit/1/ Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\jobapp\permission.py", line 21, in wrap return function(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\account\views.py", line 208, in employee_edit_profile user = get_object_or_404(User, id=id) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404 return queryset.get(*args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 431, in get num = len(clone) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in execute_sql cursor.execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", … -
I want to save my users name,email,password on a separate table instead django-auth table
Please give some suggestions on how to create my models to achieve the above requirements. -
How to make the 'return' from a django model conditional to the value of a global variable?
I am a novice in both Python and Django, and I am struggling to find the way to make a 'return' from a Django model conditional upon the value of a global variable. More specifically, I am designing an app to run an interview with the user / visitor. In the interview the questions to the user can be in past or present tense. This depends on an introduction view from which I get the choice from the user, i.e. either 'past' or 'now'. My model is class Question(models.Model): key = models.CharField(max_length=50) value = models.CharField(max_length=50) question_text_past = models.CharField(max_length=2000) question_text_now = models.CharField(max_length=2000) def __str__(self): global TENSE if TENSE == 'past': return self.question_text_past else: return self.question_text_now However, no matter what I've tried (while testing the code within the shell), my model does not reflect the changes in the value of TENSE. The model returns a "not defined" error. I've also tried to put TENSE into a module globals.py and import this into my models.py with no success. I might be missing something simple but fundamental about Django, so I appreciate any help.