Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS
I am trying to populate my model of django using the faker module, however i get an error everytime i try to run the file that my django settings are not configured. My project name is index_project there are 2 apps that i have created 1. first_app 2. second_app In the first_app there are 3 models in which i m trying to push the data. Model Name : 1. Topic 2. Webpage 3. AccessRecord this is my code : import random from faker import Faker from first_app.models import AccessRecord, Topic, Webpage import os import django os.environ.setdefaults('DJANGO_SETTINGS_MODULE', 'index_project.settings') django.setup() i am working in a venv 'myFirstDjangoApp' Error Image from cmd -
How can we use same generic UpdateView for 2 urls mappings (one with pk, and one without pk)
What I am trying to achieve is to call the generic UpdateView in 2 cases. One with pk when the Submit button is clicked - This case works fine. But, I am not able to figure out how to call the same UpdateView without the pk (from navigation bar in base.html), so that just the form is displayed, and i can go ahead and edit the form and submit it. url.py path(r'update/<int:id>', views.LinkUpdateView.as_view(), name='update'), views.py class LinkUpdateView(UpdateView): template_name = 'update.html' form_class = LinkUpdateForm success_url = "/" model = Links def get_object(self): return Links.objects.get(id=self.kwargs.get("id")) models.py class Links(models.Model): id = models.CharField(max_length=50, primary_key=True) a = models.CharField(max_length=50) b = models.CharField(max_length=50) c = models.CharField(max_length=50) d = models.CharField(max_length=50) e = models.IntegerField() forms.py class LinkUpdateForm(forms.ModelForm): class Meta: model = Links fields = [ 'id', 'a', ] base.html (Navigation bar, this is where the update shud be called, without pk and form should be displayed) <li class="nav-item"> <a class="nav-link" href="{% url 'update' %}">Update</a> </li> update.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Update</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Update Link</button> </form> {% endblock %} I do not want to create additional url mapping to achieve this. Can … -
Ajax Form Request Not Functioning With Django
I'm new to handling AJAX requests in Django, and am following this tutorial for it. However, despite doing exactly the same thing, it does not work as expected for me. My code is below. views.py def profile_card(request): h = UserProfileInfo.objects.all() w = PlayCount.objects.all() c = ArtistCount.objects.all() y = Friend.objects.all() friend_form = forms.FriendForm() friend_search_form = forms.SearchForm() # Music Profile global e e = h[0] global high high = 0 global art_high art_high = 0 global high_artist high_artist = '' global highSong highSong = '' for x in range(0, (len(h)-1)): if str(h[x]) == str(request.user.username): e = h[x] break else: pass if len(w) != 0: for i in w: if str(i.user) == str(request.user.username): if i.plays > high: highSong = i.song high = i.plays if len(c) != 0: for f in c: if str(f.user) == str(request.user.username): if f.plays > art_high: high_artist = f.artist art_high = f.plays e.most_played_artist = high_artist e.save() else: pass # Friends ''' global friendTag friendTag = '' for r in y: if str(r.user) == str(request.user.username): friendTag = r if request.method == "POST": if str(request.POST.get("friendName")) == str(friendTag.friend): print('asakura akio') ''' global term term = [] global r r = [] if request.method == "POST": friend_search_form = forms.SearchForm(request.POST) friend_form = forms.FriendForm(request.POST) if friend_search_form.is_valid(): … -
Heroku - module not found
I'm trying to deploy a Django app to Heroku and it keeps crashing. When I read the heroku logs -tail i get: 2020-04-11T11:59:59.614465+00:00 app[web.1]: ModuleNotFoundError: No module named 'ElasticSearch' 2020-04-11T11:59:59.614808+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [12] [INFO] Worker exiting (pid: 12) 2020-04-11T11:59:59.768200+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [4] [INFO] Shutting down: Master 2020-04-11T11:59:59.768448+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-04-11T12:00:15.321075+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=esprojectsam.herokuapp.com request_id=2c8510c8-14d2-4892-867a-3e3a82707fd1 fwd="86.43.201.27" dyno= connect= service= status=503 bytes= protocol=https My procfile contsains web: gunicorn ElasticSearch.wsgi --log-file - ElasticSearch is the name of the application, caps and all. I've tried different formats for the Procfile like web: gunicorn ElasticSearch:app but none of it has worked. -
How to get parent's value from ForeignKey (in django-REST)?
I have Banks model class and Branches model class as below : class Banks(models.Model): name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=74, blank=True, null=True) address = models.CharField(max_length=195, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) my querry is as follows : branch = Branches.objects.get(ifsc=IFSC) # where IFSC is passed in URL My serializers look like below : class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branches fields = '__all__' class BankSerializer(serializers.ModelSerializer): class Meta: model = Banks fields = '__all__' When i run the mentioned query, i get the following output:(example) { "ifsc": "UTIB0000007", "branch": "NEW DELHI", "address": "STATESMAN HOUSE, 148, BARAKHAMBA ROAD", "city": "DELHI", "district": "NEW DELHI", "state": "DELHI", "bank": 13 } Here 13 (in this example) is ForeignKey, But i want the value of that bank(i.e parent) instead of the key. The desired output should look like : { "ifsc": "UTIB0000007", "branch": "NEW DELHI", "address": "STATESMAN HOUSE, 148, BARAKHAMBA ROAD", "city": "DELHI", "district": "NEW DELHI", "state": "DELHI", "bank": "BANK NAME" } Please help me with this, i am new … -
Django - form.save() is not creating ModelForm
In my Django application users send feedback about task. I'm creating this form with ModelForm, and after form.save() my object is not creating and is not uploading to database. Here are my codes: views.py: @login_required(login_url='sign_in') def task_details(request, slug): if slug: task = get_object_or_404(Task, slug=slug) today = datetime.now().date() deadline = task.task_deadline.date() time_left = deadline - today form = CreateFeedbackForm() if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = CreateFeedbackForm() messages.info(request, 'Feedback sent.') context = { 'task': task, 'form': form, 'days_left': time_left.days } return render(request, 'task-details.html', context) models.py: class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) sender = CurrentUserField() is_solved = models.BooleanField(default=False) feedback_content = models.TextField(max_length=1000, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content forms.py: class CreateFeedbackForm(forms.ModelForm): class Meta: model = TaskFeedback fields = ['feedback_content', 'is_solved'] def __init__(self, *args, **kwargs): super(CreateFeedbackForm, self).__init__(*args, **kwargs) -
Django: BlockingIOError: [Errno 11] write could not complete without blocking
I have the following view in DJango: def index(request): try: if request.GET['format'] is None: # The variable print('It is None') except: print ("This variable is not defined") format_hare = 'XYZ' pass else: print ("It is defined and has a value") format_hare = request.GET['format'] url_get= request.GET['url'] print(url_get) print(format_hare) subprocess.Popen(['/usr/bin/zsh','/home/test.sh', url_get, format_hare]) html = "<html><body>"+url_get+"</body></html>" return HttpResponse(html) I keep getting the following error sometimes. Not all times. Traceback (most recent call last): File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in __getitem__ list_ = super().__getitem__(key) KeyError: 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/web_dev/django_download/download/download/views.py", line 7, in index if request.GET['format'] is None: # The variable File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/web_dev/django_download/download/download/views.py", line 10, in index print ("This variable is not defined") BlockingIOError: [Errno 11] write could not complete without blocking [11/Apr/2020 11:56:30] "GET /run-sh?url=test.com HTTP/1.1" 500 80341 How to solve this. -
What might cause Visual Studio (2019 and 2019 Preview) to have problems using crispy forms for an otherwise working simple django application?
I've a workaround for this, but flagging as I could not find any other references to this issue. I'm following the CoreyMS Django tutorials on YouTube, to get a better grip on web applications with python (I use python for some data analytics work, mostly in Jupyter notebooks nowadays, but have a hobby project which I'd like to build). Anyway, I fired up visual studio as I was aware that it has capabilities to work with python and all seemed to progress fairly well. Corey's tutorials are excellent (clear and to the point) and while there are a few nuances different from the tools used in the video's, all was going well. However, fairly early on in the series (video 6 of 17), crispy forms are introduced. install django-crispy-forms add 'crispy_forms' to the settings.py project file. {% load crispy_forms_tags %} into the relevant template update section where the form is shown to utilise cripsy as a filter: {{ form|crispy }} All straightforward and after multiple checks, no issues with typo's or similar in the code BUT: If I run from a command prompt "python manage.py runserver" the form (a new user registration page) displays without any issue with all the … -
Django display number of objects in the account model
I am currently creating a rest api. I have an account and book model. The book model has a foreign key to the account. I want to add a number_of_books field in the account model which has an int representing how many books the user has. What is the best way to implement this? Do I need to calculate from the client side? Should I create a middleware that does this? Any help is appreciated. -
How to create ViewComponent in Django?
I want to create an html containing the Menu model, and when used, only needs {% include 'menu.html'%}, no need to pass the menu variable = Menu.object.all (). It is similar to ViewComponent in ASP.NET Core -
Django Model Inheritance - Instance attributes not set properly
Alas, my code was working perfect until I decided to "fix" it and use inheritance for some linked classes. I have a UserProgram class that inherits from MyUser and Program. When I changed the class definition to UserProgram(Program, MyUser), I started getting strange behavior with my UserProgram.objects.get() function, which gets the values from a stored procedure call via get_data_pk: raw('select 1 as id, * from SP_GetUserProgram(%s,%s,%s)', params) After adding the inheritance, I see the new objects have all the inherited fields, which is fine. But their attributes are not being assigned the correct values now. For instance, maxbudget and availablebudget should both be 400000, but that is incorrectly assigned to uploaddirectoryid. Creating the UserProgram objects manually, like UserProgram(...) works fine. I'm not sure what to do here. Any ideas? Below is a simplified version of my code. models class UserProgramManager(models.Manager): def get(self, userid, programname, schoolyear): return get_data_pk(self, 'SP_DCPGetUserProgram(%s,%s,%s)', (userid, programname, schoolyear) ) class MyModel(models.Model): class Meta: managed = False abstract = True class MyUser(AbstractBaseUser): userid = models.IntegerField(primary_key=True) objects = MyUserManager() class Program(MyModel): schoolyear = models.SmallIntegerField(primary_key=True) programname = models.CharField() def __init__(self,schoolyear=None,programname=None,*args,**kwargs): super(Program, self).__init__(*args,**kwargs) self.schoolyear = schoolyear self.programname = programname class UserProgram(Program, MyUser): uploaddirectoryid = models.CharField() objects = UserProgramManager() test.py # Works … -
How to create schedule in Django
So, I want to create a schedule of training in Django. My DB models looks models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Coach(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name="coach") name = models.CharField(max_length=200) phone = models.CharField(max_length=200) desc = models.CharField(max_length=500) avatar = models.ImageField(upload_to="coach_avatars/", blank=True) def __str__(self): return self.user.get_full_name() class TypeOfTraining(models.Model): coach = models.ForeignKey(Coach, on_delete=models.CASCADE, related_name="training_type") name = models.CharField(max_length=100) desc = models.CharField(max_length=500) price = models.FloatField(default=0) def __str__(self): return self.name class TrainingSchedule(models.Model): coach = models.ForeignKey(Coach, on_delete=models.CASCADE) training_type = models.ForeignKey(TypeOfTraining, on_delete=models.CASCADE) start_at = models.DateTimeField() def __str__(self): return str(self.id) how do I display data from the database in html form that looks like an image? example: how looks schedule on HTML page I have done HTML template. but I haven't how to show data from DB in my template. P.S. Sorry for my English. -
django call .annotate context processors in DetailView
My project depending on giving users points for any thing they do (post, comment, like, favourite, ....) i created context processor to use some calculations inside several templates. My problem is i cannot call these context processors inside template without for loop Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') favourite = models.ManyToManyField(User, related_name='favourite', blank=True) class Comment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='commenter') post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') class Profile(models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') views.py class UserDetailView(DetailView): template_name = 'user/user-details.html' queryset = User.objects.all() def get_object(self): return get_object_or_404( User, username__iexact=self.kwargs.get("username") ) settings.py 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'common.context_processors.user_counters', ], templates.html <ul class="dynamic-tabs-list"> <li class="active" data-content=".content-posts">Posts <span class="badge badge-light">{{ user.posts.count }}</span></li> <li data-content=".content-comments">Comments <span class="badge badge-light">{{user.commenter.count}}</span></li> <li data-content=".content-favourites">Favourites <span class="badge badge-light">{{ user.favourite.count }}</span></li> <li data-content=".content-points">Points <span class="badge badge-light">{{ user.total_score }}</span></li> </ul> context_processors.py def user_counters(request): user_qs = User.objects\ .annotate( user_posts_count=Count('posts', distinct=True), user_posts_score=F('user_posts_count') * 10,)\ .annotate( user_comments_count=Count('commenter', distinct=True), user_comments_score=F('user_comments_count') * 10,)\ .annotate( user_favourites_count=Count('favourite', distinct=True), user_favourite_score=F('user_favourites_count') * 10,) \ .annotate( user_likes_count=Count('likes', distinct=True), user_likes_score=F('user_likes_count') * 10, ) \ .annotate( total_score=F('user_posts_score')+F('user_comments_score')+F('user_favourite_score')+F('user_likes_score') ) context = { 'user_qs': user_qs, } return context urls.py path('profile/<username>/', UserDetailView.as_view(), name='user-detail'), Any help please ? Thanks in-advance -
In a Django migration, how can I create an object and use it as default in another field?
I already have a model Area. I want to add a new model City, like: class City(models.Model): pass class Area(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT) # new field. How to create a migration which sets the existing areas to a city (called 'Mumbai')? I know I can do migrations.RunPython but how do I get the new city's id to pass to models.ForeignKey's default param? migrations.AddField( model_name='area', name='city', field=models.ForeignKey(default=???, to='location.City'), preserve_default=False, ), -
DJANGO - Extract filtred data to excel
I have a view with a django-filter that generate a filtred table. I would like to export this filtred table. For now, I success to export the non filtred data using xlwt 2 questions : - How to extract the filtred data ? - How to apply format date and hour in excel column ? I have a model Order with the fields 'Date','Hour','Category','Item', OrderFilter is a django-filter Views.py def data(request): orders= Order.objects.all() filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date','-Hour') return render(request, 'template.html',{'orders':orders,'filter': filter}) def export_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Hour', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Order.values_list('Date', 'Hour', 'Category', 'Item__Item') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response url.py path('data/',views.data, name='data'), url(r'^export/xls/$', views.export_data, name='export_data') template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <a class="btn btn-primary" href="{% url 'export_data' %}">Export</a> <table> display the filtred table ...</table> -
Where to find all models field type in Django?
class Products(models.Model): p_name = models.TextField() sku = models.TextField() price = models.TextField() desc = models.TextField() Also please suggest me an IDE that auto suggest models fields type. currently i am using sublime text. Thanks. :) -
Using django-environ; Django admin css not found
I removed the BASE_DIR and the os import because I am using django-environ. However when I entered the admin dashboard of Django, the css is not read so I only see plain html elements. Here is how part of my settings.py looks like. import environ root = environ.Path(__file__) - 3 # get root of the project env = environ.Env() environ.Env.read_env() # reading .env file SITE_ROOT = root() DEBUG = env.bool('DEBUG', default=False) TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = tuple(env.str('ALLOWED_HOSTS', default=[])) DATABASES = { 'default': env.db('DATABASE_URL') } SECRET_KEY = env.str('SECRET_KEY') # Static and Media Config public_root = root.path('public/') MEDIA_ROOT = public_root('media') # MEDIA_ROOT = root.path('media/') MEDIA_URL = env.str('MEDIA_URL', default='media/') STATIC_ROOT = public_root('static') STATIC_URL = env.str('STATIC_URL', default='static/') ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [root.path('templates/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] So I also put in root.path('templates') into the DIRS of TEMPLATES. What should be written instead? -
Celery - No result backend is configured while using gunicorn
Im unsing gunicorn like many others to run my python app. I just wanted to try things out in production mode and discoverd that I'm not able to trigger a celery @shared_task while im running in production mode which basically just means hide all output errors and use gunicorn instead of the development runserver. Celery always returns the error "No result backend is configured" which makes absolut no sense to me as everything else works as expected when using the development runserver I don't know where I could start to debug this behaviour as CELERY_RESULT_BACKEND = 'django-db' simply seems to get ignored. This is how I start gunicorn: gunicorn App.wsgi:application \ --workers $GUNICORN_WORKERS \ --bind=127.0.0.1:8000 \ --log-level info celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import environ from django.conf import settings env = environ.Env() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "App.settings") app = Celery(str(settings.SITE_NAME), broker=str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') + str("/")) app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task … -
Deploying django channel project for free [closed]
I have a django channels project. I am looking to deploy it on a free server. I don't know much about free servers that will host my project. Anyone that can help me with some info. Thanks. -
Django - Custom handler500 not working despite following docs
I followed the docs step-by-step and searched for a solution everywhere but my custom handler500 won't work. I use Django 2.2 with Python 3.8. Here's my urls.py: urlpatterns = [ # some urls ] handler500 = "path.to.my.handler" my handler: def handler500(request, exception=None, *_, **_k): print("yeah I got called") return render(request, "my_template.html", { "exception": exception }) my view: def example_view(request): # I tried all of these return HttpResponseServerError() return HttpResponse(status=500) raise Exception("There was an error") # This just shows: "A server error occurred. Please contact the administrator." in the browser. raise HttpResponseServerError() # This shows the same message as above. a_typo # This typo also shows the same message as above. Why doesn't ANY of these errors show my template? The handler didn't get executed at any time. The print() function never got called. -
Python: Selenium no such element: Unable to locate element: {"method":"xpath","selector":"//button[@data-id=1]"}
Why I got this error no such element: Unable to locate element: {"method":"xpath","selector":"//button[@data-id=1]"} test.py zone = Zone.objects.last() self.browser.refresh() time.sleep(2) self.browser.find_element_by_xpath("//button[@data-id="+str(zone.id)+"]").click() # zone.id = 1 I have also tried with self.browser.find_element_by_id('update_id_'+str(zone.id)) but not working :( what's wrong going on ? html <button type="button" id="updateButton update_id_2" class="btn btn-xs btn-primary updateButton" data-id="2"> <i class="fa fa-edit"></i> </button> -
Complex Database Query in Django Graph-Structure
I have a django-project with the following model structure. At first I have a graph-structure with nodes and (directed and weighted) edges in the following way: class Node(models.Model): name = models.TextField() class Edge(models.Model): from_node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name='edge_from_node') to_node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name='edge_to_node') costs = models.IntegerField() There also do exists token, whereby a node can be related to multiple tokens but a token can only be related to one node: class Token(models.Model): node = models.ForeignKey(Node, on_delete=models.DO_NOTHING) Additional I have a User object that can own multiple tokens: class MyUser(models.Model): tokens = models.ManyToManyField(Token) I now want to make a database query that for a given TargetNode and MyUser gives the edge with the minimal costs connecting any node, for which MyUser owns a token, with the TargetNode. Let me make a simple example: # we create 4 nodes ... n1 = Node(name="node 1") n2 = Node(name="node 2") n3 = Node(name="node 3") n4 = Node(name="node 4") n1.save() n2.save() n3.save() n4.save() # -.. and create 3 edges e1 = Edge(from_node=n2, to_node=n1, costs=3) e2 = Edge(from_node=n3, to_node=n1, costs=2) e3 = Edge(from_node=n4, to_node=n1, costs=1) e1.save() e2.save() e3.save() # create a user user = MyUser() user.save() # create 2 tokens for the given user to node2 … -
Django error: Instance of 'OneToOneField' has no 'username' member pylint(no-member)
I'm new to Django and I'm learning it throw a youtube tutorial. I'm trying to build a simple Blog but I have some problem that I think could be related to python or django version. I'm using python3.7.5 and django2.1.5. I've created the following model which represent the user's profile which overrides the save method to enable a resize of the uploaded profile picture. from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() 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) From this I get a few errors, for example in str method from this line: return f'{self.user.username} Profile' I get this error: Instance of 'OneToOneField' has no 'username' memberpylint(no-member) And I get similar error every time I use the self. Can anyone help me? -
"TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType" when installing Django via pipenv on Windows 10:
I am trying to install Django on my Windows 10 System. Python 3.7.7 and pipenv 2018.11.26 are propoerly installed. When I try to run pipenv install django==2.2.5 i get the following error message, for which I just can't figure out the reason: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts\pipenv.exe\__main__.py", line 9, in <module> File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\cli\command.py", line 254, in install editable_packages=state.installstate.editables, File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1927, in do_install pypi_mirror=pypi_mirror, File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1386, in pip_install pip_command = [which_pip(allow_global=allow_global), "install"] File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1459, in which_pip return which("pip") File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 117, in which if not os.path.exists(p): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\genericpath.py", line 19, in exists os.stat(path) TypeError: stat: path should be string, … -
How can i get image from Profile model into my Post model
There are two model profile and post..i want to get image from profile model..into my post model..how can I get?