Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError while connecting Django ForeignKey field to another model
I am having this name error NameError: name 'Profile' is not defined while i set my ForeignKey field value. I have had experience in Django before and this error seems so nonsense. What coulde cause issue here? my Post model: class Post(models.Model): coach = models.ForeignKey(Profile, on_delete=models.CASCADE) my Profile model: class Profile(models.Model): token = models.CharField('Token', default='1234a', max_length=100) bio = models.CharField('Bio', max_length=100, default='cool') name = models.CharField('Nimi', max_length=100, default='...') ... -
How to pass arguments to a model class?
Sorry for my English. I'm a total newbie in Django and I'm trying to pass the properties to a TodoItem instance in my views.py file: def addTodo (request): new_item = TodoItem(content=cont) new_item.save() In the example above I get to pass only one argument, but what if I have to pass several? This is my model: class TodoItem(models.Model): content = models.CharField(max_length=200) types = models.CharField(max_length=200) time = models.CharField(max_length=200) Thanks in advance -
Receive site information and display it on own site using django and bs4
hi i'm new in django and i want to receive site information and display it on your site using django and bs4 for example i want get all links and images to show in own site from django.shortcuts import render, HttpResponse from bs4 import BeautifulSoup import requests views.py: def websiteChecker(request): # for get website zoomit_url = 'https://www.zoomit.ir/' response_zoomit = requests.get(zoomit_url) digiato_url = 'https://digiato.com/' response_digiato = requests.get(digiato_url) # for find content of websites zoomit_soup = BeautifulSoup(response_zoomit.content) digiato_soup = BeautifulSoup(response_digiato.content) # title in site zoomit_title = zoomit_soup.title digiato_titl = digiato_soup.title # it is temp for zoomit website zoomit_class = 'content home col-md-6 col-sm-9 adv-center-column' digiato_class = 'home-entry featured home-entry generic clearfix ' # find all div with class above latest_news_in_zoomit = zoomit_soup.findAll( 'div', attrs={'class': zoomit_class}) latest_news_in_digiato = digiato_soup.findAll( 'article', attrs={'class': digiato_class}) # show = latest_news.content # it is return latest_news # return HttpResponse(content=latest_news) context = { # 'show': show, 'latest_news': latest_news_in_zoomit } return render(request, 'mychecker/index.html', context) index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{latest_news}} </body> </html> what can i do? It shows me that now -
How to Serialize different nested Serializes when the order is not allowing so
so i'm new to Django and i'm creating an API using djangorestframework When creating the serializers I encountered a problem which I can't find a way to go around it. I have 2 models, Site and Article Site can have many articles Article can have one site I did the relationship in the models and everything looks fine. When tried to serialize the information I started with the SiteSerializer which had a line to get the ArticleSerializer and had a related name of 'articles' (also the name of the variable) and it worked But when trying to serialize the SiteSerializer inside the ArticleSerializer with the same way it cannot be done because the order of the classes, it cannot refrence to it when it's yet to be created CODE: class ArticleSerializer(serializers.ModelSerializer): site = SiteSerializer(many=false) class Meta: model = Article fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site') class SiteSerializer(serializers.ModelSerializer): articles = ArticleSerializer(many=True) class Meta: model = Site fields = ('id', 'name', 'url', 'articles') I can't refrence to SiteSerializer when it's below, but it will be the opposite if I switch them up. What can I do in this situation, is there another way to serialize different models with many … -
creating a folder automatically for each user in Django + saving tensorflow weights in that folder
Question 1: So I want to create a folder automatically for each user, Here is my models.py: models.py #Creating a folder automatically for each user def DLWeights_path(instance, filename): return "user_{0}/MyFolder/{1}".format(instance.user.id, filename) # Create your models here. class SLRModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) DeepLearningWeights = models.FileField(upload_to= DLWeights_path, default= None) Question 2: In views.py, I want to save the weights of the machine learning model in that path defined above in the models.py views.py: from .models import * import tensorflow as tf tf.keras.models.save_model(classifier, SLRModel.DeepLearningWeights) Thanks -
How to remove the "OperationalError at / no such table: subreddit_subreddit" after deploying to Heroku?
I've been trying to deploy my project to Heroku for the past 4 days and finally after going through so many errors, I was able to deploy BUT now the error that I'm getting is the "no such table". I know that I have to "heroku addons:create heroku-postgresql:hobby-dev" and then "heroku run python manage.py migrate" but I'm still getting the same error. Also I want to mention that I know my website works because I can still go to my other pages, such as: login, signup and they're working just fine(with the styling and everything), the issue is the no such table. I'm clearly not doing something right, would love to know if any of you guys were able to fix this kind of an issue? BTW I'm on a mac, just an FYI. -
Right way to share dynamic files between services in docker compose
I have the following docker-compose file. I'd like to share the static files from the react service with the nginx and web services version: '3.6' services: web: image: shahrukh/learnup:web networks: - main command: > sh -c "python manage.py collectstatic --no-input && gunicorn learnup.wsgi:application --bind 0.0.0.0:8000 --reload" volumes: - static_cdn:/var/www/learnup/static_cdn depends_on: - react react: image: shahrukh/learnup:react volumes: - static_cdn:/app/Learnup-Frontend/learnup/export-build/static nginx: image: shahrukh/learnup:nginx restart: always ports: - 80:80 command: nginx -g 'daemon off;' volumes: - static_cdn:/var/www/static networks: - main depends_on: - web - react networks: main: volumes: static_cdn: For this, I created a named volume static_cdn on which the following steps would happen The build folder for my react app from the react service will be mounted here Static data from django's collectstatic command will be copied here This is shared with nginx which will serve it. Here's the problem I am facing. On updating my react container image with the latest build the volume static_cdn doesn't have the latest static files, as the volume isn't recreated after I use docker-compose up -d So my question is What is the best way to share files between services in this scenario? So that it takes care of the updates. Please note that I … -
Two Django apps in Nginx
I'm trying to deploy two different applications using Nginx. I deployed the first app some weeks ago, I'm trying to deploy a new one. The next are the first app. I deployed the first app using this tutorial gunicorn.socket (first application socket file) [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn.service (first application service file) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=geanmuri Group=www-data WorkingDirectory=/home/geanmuri/first_app/web_app ExecStart=/home/geanmuri/first_app/.venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ analisistweets.wsgi:application [Install] WantedBy=multi-user.target app_covid.socket (second app socket file) [Unit] Description=gunicorn socket [Socket] ListenStream=/run/app_covid.sock [Install] WantedBy=sockets.target app_covid.service (second app service file) [Unit] Description=gunicorn daemon Requires=app_covid.socket After=network.target [Service] User=geanmuri Group=www-data WorkingDirectory=/home/geanmuri/app_covid ExecStart=/home/geanmuri/app_covid/.venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/app_covid.sock \ predictor_corona_web.wsgi:application [Install] WantedBy=multi-user.target The first app is working OK, but when I try to start the second socket I failing. $ sudo systemctl start app_covid.socket $ Job for app_covid.socket failed. $ See "systemctl status app_covid.socket" and "journalctl -xe" for details. I don't know what's happening. Thanks for advice. -
Django one appp some models and one model list view in other create view template
I work with Class based view in django and i need to create one model create view in other model list view... I have no idea how to do it because i am always created list view in model_lsit.html template, ant create view in model_form.html template. [djan][1] In picture you can see my app dishes and my purpose ir in tripdishes_list.html crate favrecipes_form.html... Any advices? Thank you, I feel stuck here ) [1]: https://i.stack.imgur.com/gGvEW.png -
i can't use static files from my Django app
I went to this route http://127.0.0.1:8000/static/corefiles/chatbot-data.xlsx but i get Page not found (404) error... I added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) At the end of my URL patterns... File directory is /rootproject/core/static/corefiles/testexel.xlsx My settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = ( normpath(join(BASE_DIR, 'static')), normpath(join(BASE_DIR, 'upload')), ) STATIC_ROOT = normpath(join(BASE_DIR, 'assets')) -
How to print user.surname in django html
In my model i use mixin account: models.py class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py lass UserCreateForm(UserCreationForm): email = forms.EmailField(max_length=20) surname = forms.CharField(max_length=20) class Meta: fields = ('username','surname','email') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Name' self.fields['surname'].label = 'Surname' self.fields['email'].label = 'Email Address' I can print the username in HTML {{user.get_username}} How to print surname? I tried to {{user.get_surname}} but it does not work. Please help -
Django tries to serve cached image that does not exist
I'm running django 1.7.1 I'm trying to render a .html page that makes used of some cached images. This is the Image model that these images belong too: image_pbox = models.ImageField( upload_to='pbox', blank=True, max_length=255, storage=STORAGE, null=True) image_pbox_300 = ImageSpecField( [ResizeToFit(300, 300)], source='image_pbox', format='JPEG', options={'quality': 90}, cachefile_storage=STORAGE) On the webpage, I can use pagintaion to select different sets of Image instances to return, and eventually they are rendered using: {{image.image_pbox_300.url}} Now, initially this all worked fine. Then, my server had a power issue and the drive on which these cached images were located was temporarily disconnected. Now, I can use my web page to render some cached images - I'm assuming those that have not been cached before, but this is a guess. Other images - ones that I am sure off were cached before - return a permission error. Remember that this are just different instances of the same model. E.g. the first few images return an error, the later ones don't. The permission error: OSError at /make_data_request/ [Errno 13] Permission denied: '/data/gallery/config/media/CACHE/images/pbox/MVSrCYHsteI6D0ocQfiLwwy' The permission error seems straightforward. Must be something with ..permissions, right? Everything related to permissions seems to be configured properly - and remember, a selection of images … -
Django: template renders wrong
I'm developing a web application that consists of registering employees, customers and suppliers in a database, via Python and Django. The code works perfectly, but when I register a new customer it presents me with the following error: Error The customer is registered in the database but the template that lists the customers does not load. Can you help me? -
How to incorporate FB graph api data in django template?
I'm using the FB graph API to retrieve data on instagram users such as the bio, nb of followers, profile pic ... I am 2 python files: fbsettings.py which contains the access token, my FB account credentials and where I set the insta username instadata.py that uses the settings from fbsettings and a function to get the info from the graph API Now I am trying to incorporate the information retrieved from the graph api into a Django client profile template where the insta username has been captured manually (so its a field in a model). I have added the 2 files (fbsettings.py and instadata.py) in the project folder (same level as views.py) and I'm trying to create a class in the views.py files but when importing functions from instadata.py which itself imports functions from fbsettings.py I get the error below: File "C:\Users\User\Documents\project\my_app\instadata.py", line 1, in <module from fbsettings import getDetails, makeApiCall ModuleNotFoundError: No module named 'fbsettings' When I just run the instadata.py it works great. What I am missing? Is there another way to do this? -
Display Parent page variable on Child page with template - wagtail/django
Tried to look for solution but probably missed it, probably because of unsure what exactly to ask. I am new to Wagtail/Django. How can I make variables from parent page visible on child page? I am trying to make a page that has Header, Content and Footer. I enclosed those inside {% block name_of_section %}. Now I have a child page (actually grandchild, but whatever) which template consists only of: {% extends main_page.html %} {% load wagtailcore_tags wagtailimages_tags static wagtailuserbar %} {% block content%} {{ page.photo }} {{ page.article }} {% endblock %} and the main page template (truncated of course): {% load wagtailcore_tags wagtailimages_tags static wagtailuserbar %} htmlcode {% block header %}some stuff here{% endblock %} {% block content %}stuff to be replaced in child pages here{% endblock%} {% block footer %}{{ page.address }} {{ page.links }} {{% endblock %}} finishing html code here Now the problem I am having is that when I load the child page, the header, content and footer display almost fine. The exceptions are those variables address and links from the footer. I assume it is because it gets passed to the child page still as {{ page.address }} and of course the child … -
Where can I find a reference for Django template syntax, specifically for accessing form field attributes
Just like the title says. I have a big form and I render it through a template like this: <table> {% for field in form.visible_fields|slice:":59" %} <tr> <td> {{ field.label_tag }} </td> <td>{{ field }}</td> </tr> {% endfor %} </table> I would like to know if I can do something like {% if field.is_boolean_field %} or {% if field.widget == select %}. However, even better would be if someone could point me in the direction of such documentation. For some reason I couldn't find it in the Django docs. -
Django "snippet_detail() got an unexpected keyword argument 'snippet_slug'" error
I am trying to submit the snippet and redirect to a page where I get the snippet detail page. Below is corresponding part of my views.py: def index(request): if request.method == 'POST': f = SnippetForm(request.POST) if f.is_valid(): snippet = f.save(request) return redirect(reverse('snippet_detail', args=[snippet.slug])) else: f = SnippetForm() return render(request, 'djangobin/index.html', {'form': f}) def snippet_detail(request, snippet_slug): snippet = get_object_or_404(Snippet, slug=snippet_slug) snippet.hits += 1 snippet.save() return render(request, 'djangobin/snippet_detail.html', {'snippet': snippet}) and corresponding part of my urls.py: urlpatterns = [ path('',views.index,name='index'), path('<int:snippet_slug>/',views.snippet_detail, name='snippet_detail'), ] But I get the error: TypeError at /1598354748868126/ snippet_detail() got an unexpected keyword argument 'snippet_slug' Python version: 3.8.2 Django version: 2.0 OS: Windows 8.1(32 bit) App name: djangobin -
Can we add something like *.sqlite3 in settings.txt in Django to refer multiple db files?
I am new to Django, in order to keep the db file light weighted I wanted to store monthly data in a separate sqlite3 file so that I can easily backup or restore monthly data in Django server. right now I have added as DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } this refers to a single db file. can I use *.sqlite3 so that it maps to all the sqlite3 files present in the folder? Thanks in advance -
Django aggregate ForeignKey hierarchy
Let's say I have the models Foo, Bar and FooBar. Bar has a ForeignKey reference to Foo. FooBar has a ForeignKey reference to Bar. Given a Foo-object, how do I most efficiently gather all related FooBar objects? I don't want this: foobars = [] for bar in foo.bar_set.all(): for foobar in bar.foobar_set.all(): foobars.append(foobar) -
Im not able to insert a data in django form-checkbox
Im not able to insert a data in django form,im using a custom form which contain check box.when i try to save the data it gives error message(MultiValueDictKeyError at /Hostel_Accomodation 'hostel_Boys') -
The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead
from django import forms from .models import Blog I just rewrite code this point, from ↓: # class BlogPost(forms.ModelForm): # class Meta: # model = Blog # fields = ['title', 'body'] to ↓: class BlogPost(forms.Form): email = forms.EmailField() files = forms.FileField() url = forms.URLField() words = forms.CharField(max_length=200) max_number = forms.ChoiceField(choices=[('1','one'), ('2','two'),('3','three')]) and views.py file is here ↓: from django.shortcuts import render, get_object_or_404, redirect from .models import Blog from django.utils import timezone from .form import BlogPost from django.views.decorators.http import require_http_methods # Create your views here. def home(request): blogs = Blog.objects #쿼리셋 return render(request, 'home.html', {'blogs'`enter code here`:blogs}) def detail(request, blog_id): details = get_object_or_404(Blog, pk=blog_id) return render(request, 'detail.html', {'details':details}) def new(request): return render(request, 'new.html') def create(request): blog = Blog() blog.title = request.GET['title'] blog.body = request.GET['body'] blog.pub_date = timezone.datetime.now() blog.save() return redirect('/blog/'+str(blog.id)) #이 URL로 넘기세요 처리된 정보를 def blogpost(request): if request.method =='POST': form = BlogPost(request.POST) if form.is_valid(): post = form.save(commit=False) # post.pub_date = timezone.now() post.save() return redirect('home') else: form = BlogPost() return render(request, 'newblog.html',{'form':form}) I don't know why I only rewrite 'form.py' file, but vscode program says "The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead." what should I do?? help.. -
How can I not put data in ImageField in Django?
I am to store images in imagefield. But I don't want to print out an error even if I don't put an image in ImageField. In other words, I want to leave ImageField null.I also tried null=True and blank=True to do this, but it didn't work properly. What should I do to make it possible? Here is my code. class post (models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=40) text = models.TextField(max_length=300) image1 = models.ImageField(blank=True, null=True) image2 = models.ImageField(blank=True, null=True) image3 = models.ImageField(blank=True, null=True) image4 = models.ImageField(blank=True, null=True) image5 = models.ImageField(blank=True, null=True) -
Run django program in debug mode with virtual env in pycharm?
I am new to django and pycharm, when i am trying to run my code with terminal everything works fine first i will activate my virtual environment and then use this command: python manage.py runserver 0.0.0.0:8000 But like this i am unable to go through breakpoints in the code and debug my application. Is there any command in python like above on which my code will execute on debug mode and stops on respective break points. I also try to edit my configure but that didnot workout, can you also guide me where i have to place my virtual coomand in this to activate virtual environment during debug mode. -
how to fetch the value of src, width, height of iframe in Django using GET method
views.py def add(request): report_list = {} if request.method == "POST": src =request.POST['src'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] #context = {'report_list': report_list} report_list={'src':src, 'width':width, 'height':height, 'name':name} return render(request, 'report_one.html', report_list) else: src=request.GET.get('src', '') width=request.GET.get('width','') height=request.GET.get('height','') name=request.GET.get('name', '') #report_list={'src':src, 'width':width, 'height':height, 'name':name} #report_list={'src':request.POST['src'], 'width':request.POST['width'],'height':request.POST['height'], 'name':request.POST['name']} return render(request, 'report_two.html', report_list ) index.html <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-header">Reports</li> <li> <div class="buttons pull-right"> <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a> </div> <a href="{% url 'report:reporttwo' %}">Report one</a> </li> {% for item in report_list %} <li> <a href="{% url 'report:add' %}">{{item.name}}</a> </li> {% endfor %} </ul> **if** part getting the value of src, width ,name of report, and height from the user and then created report name should shown in the dropdown. When user click on the report name the created report will display on the screen and i think this part is handle by else ...but the problem is that i got the blank page **else** part giving blank value of iframe src, width,height -
django-crontab is not executing function
I am trying to set up a cron every minute to the following test function using django_crontab which hits a specific url but its not executing at all. drc / data_refresh.py def test(request): requests.post("https://example.com/sendmail") return JsonResponse({'message' : 'test_success'}) settings.py INSTALLED_APPS = [ ...... 'django_crontab', ] CRONJOBS = [ ('* * * * *', 'drc.data_refresh.test', ['request']) ] After the above steps, I have done ./manage.py crontab add and I waited for sometime but now nothing happens. When i ran the cron manually using ./manage.py crontab run cron_task_id , it executed perfectly. Please suggest where I am doing wrong.