Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django templates not showing objects
hi i m trying to pass data from my models but it does not show anything.. it is rendering {{Experience.first.Designation}} but {{Experience.Designation}} is showing nothing.. also if i use {{Experience.first.Designation}} it will ony show one row of database in for loop repetedly which i dont want {% for queryset in Experience %} <li class="{% if forloop.counter|divisibleby:2 %}timeline-right{% else %}timeline-left{% endif %}"> <div class="timeline-badge"> <i class="fa fa-calendar"></i> <p class="{% if forloop.counter|divisibleby:2 %}date-inverted wow {% else %}date wow {% endif %}">{{Experience.first.FromDate}} -{{Experience.first.ToDate}}</p> </div><!-- end timeline-badge --> <div class="timeline-panel wow slideInRight"> <div class="experience-content"> <h4>{{Experience.Designation}}</h4> <h5>{{Experience.Department}}</h5> <p>{{Experience.ShortNote}}</p> </div> </div><!--end timeline-panel --> </li><!-- end timeline-right --> {% endfor %} here is views.py file from django.shortcuts import render from home.models import * from django.views.generic import ListView # Create your views here. def index(request): abt = About.objects.all() return render(request,'home/index.html',{'abt': abt.first()}) def Experience(request): Exp = Experience.objects.all() return render(request,'home/Experience.html',{'Exp': Exp}) class MyView(ListView): context_object_name = 'name' template_name = 'home/index.html' queryset = About.objects.all() def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['Experience'] = Experience.objects.all() context['About'] = self.queryset return context here is models.py from django.db import models import datetime # Create your models here. class About(models.Model): image = models.ImageField(upload_to = 'pics') desc = models.TextField() class Experience(models.Model): Designation = models.CharField(max_length=150) Department = models.CharField(max_length=150,default='my dept') … -
Adding multiple filters onto a template variable
I am having trouble applying multiple filters to my template variables. The two filters I want to use are: add_class:"px-0" AND floatformat:2 When I add both filters it doesnt render the data no matter the order I put the filters. I am currently trying to implement it like this: {{ form.field | add_class:"px-0" | floatformat:2 }} -
Get field data from database to populate form fields for a user who has already submitted the form
I built a model form wherein I want a user to first login and then fill my form fields. For a new user with no previous submission, I want the form to be blank. For a customer who has submitted the form before, I want to get the id of that logged in customer making GET request and retrieve field values from database to populate the form, with data he previously entered to submit the form. At the moment I am trying this approach to get id of logged in user to populate the fields in views.py cur_customer = Customer.objects.get(id=request.user.id) This however gives me an error saying Customer matching query does not exist. So how would I implement this? views.py def multi_form(request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Your Response has been recorded") context={'form':form} return render(request, 'customer/index.html', context) else : return render(request, 'customer/index.html', {'form': form}) else: cur_customer = Customer.objects.get(id=request.user.id) form=RegForm(initial={ 'first_name':cur_customer.get('first_name',''), 'last_name':cur_customer.get('last_name','')}) context = {'form': form} return render(request, 'customer/index.html', context) models.py class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.OneToOneField(CustomerReg, on_delete=models.SET_NULL, null=True, blank=True) first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) class CustomerReg(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField(max_length=254) -
ValueError: The 'photo' attribute has no file associated with it. from pillow
I got this error The 'photo' attribute has no file associated with it. when I am trying to save the image after process with Pillow. This is my view.py def preview_page(request, invoice): applicant_image_form = ApplicantImageForm( request.POST or None, request.FILES or None ) applicant_info = ApplicantInfo.objects.get(invoice=invoice) education_info = ApplicantEducation.objects.get(invoice=applicant_info.sl) if request.method == 'POST': photo = request.FILES.get('photo') signeture = request.FILES.get('signature') photo_open = Image.open(photo) signeture_open = Image.open(signeture) p_s = photo_open.size s_s = signeture_open.size if p_s[0] == 300 and p_s[1] == 300 and s_s[0] == 300 and s_s[1] == 80: photo = photo_open.thumbnail(size=(100, 100)) signeture = signeture_open.thumbnail(size=(100, 50)) applicant = ApplicantInfo.objects.get(invoice=invoice) ApplicantImage.objects.create( invoice=applicant, photo=photo, signeture=signeture ) return redirect('final-report', invoice=invoice) else: context = { 'applicant': applicant_info, 'education': education_info, 'form': applicant_image_form, 'message': 'invalid' } return render(request, 'dpe/preview.html', context) context = { 'applicant': applicant_info, 'education': education_info, 'form': applicant_image_form } return render(request, 'dpe/preview.html', context) How can I solve this issue? -
Django Slugfield with how to treat underscore and hyphen the same in uniqueness?
I have a slugfield: name = models.CharField( unique=True, validators=[ validate_slug, ], max_length=255 ) However, I also want to ensure uniqueness is checked where hyphens and underscores are treated the same. For this test case: name1 = 'surfer_190_chap` name2 = `surfer-190_chap` record = Record(name=name1) if record.full_clean(): record.save() record2 = Record(name=name2) with self.assertRaises(ValidationError): if record2.full_clean(): record2.save() The second name should fail, however it does not. What I tried (I'm still researching how to do this part): def validate_unique_underscore_hyphen(value): if '_' in value or '-' in value: ... name = models.CharField( unique=True, validators=[ validate_slug, validate_unique_underscore_hyphen ], max_length=255 ) -
convert list of dictionaries to queryset django
def db_data(request): grid_data = list(table_name.objects.all().values()) return JsonResponse(grid_data, safe=False) I am hitting above endpoint which gives list of dictionaries as response. Is there a way where I can convert this back to Queryset object at the receiver side so that I can perform ORM operations on this queryset object. -
Django , error when trying to pre populate form when editing it
I am trying to write a code to edit a post, and when I click to edit this post it must be pre populate with the old text. I trying many ways. Could someone help to see what is wrong with this code? enter code heredef edit_entry(request): if request.method == "POST": form = EditEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title,content) args = {'form':form, 'content':content} return render (request, "encyclopedia/edit.html", { "name": title, "content": content }, args) if request.method == "GET": util.save_entry(title, content) return render(request, "encyclopedia/edit.html",{ "previous_title": title, "previous_content": content }) -
How Saleor core app flow for graphql query from database?
i am very new to saleor.io and in saleor currently i am seeing code of saleor core and run it successfully on local host. And it shows me result of grapghql query also. My question is that: When i try to run grapghql query in debug mode the saleor core doesnot stop at debug point of saleor core where i put the breakpoint (in my case i put debug points on urls.py). But when i start my application it stop on all break point which confuse me more that how it is getting data and returing data from postgres database. By debugging, i just want to see the flow of it and i am feeling difficulty in understanding it. Can anyone have a useful link or someone can explain it easily the flow of saleor core. So that this post also help other new users of saleor.io -
Remove duplicate result in django search
I hope you're well. Does anyone know how I can remove duplicate in search result? For instance, if i search "Louis". I got 4 duplicates results. Is there any way to got unique result? thanks in advance. user/views.py #search profile @method_decorator(login_required(login_url='/earlycooker/login/'),name="dispatch") class UserProfileResultsView(ListView): model = UserProfile template_name = 'search_results_user.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) | Q(user__username__icontains=query) | Q(mealtrend__name__icontains=query) | Q(pricetrend__name__icontains=query) | Q(speedtrend__name__icontains=query)| Q(strengthtrend__name__icontains=query) | Q(wellnesstrend__name__icontains=query) ) return object_list templates/search_result_user.html {% for userprofile in object_list %} <a href="{% url 'user:user_public_cookwall' slug=userprofile.user.userprofile.slug %}" class="search_user_link">{{ userprofile.user.username }}</a> {% endfor %} -
How to store a mysql database in the project folder for django3?
My settings.py looks like this :-> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'NAME': BASE_DIR / 'db.sqlite3', 'NAME': 'django_test_db', 'USER': 'root', 'PASSWORD':'123', 'HOST': 'localhost', 'PORT': '3306', } } The database is getting stored in the default mysql directories on my computer. I want to save this database in the project folder itself. Please help. -
Generate Django model from Open API spec
I'd like to generate a set of Django models from a 3rd party's Open API / Swagger spec (so I can then use the Django Rest framework to receive messages from that 3rd party) In Swaggerhub / Codegen there is an option to export 'server stubs' for a variety of frameworks inc ASP.net and Flask Is there an equivalent way for Django? -
Using Static JSON and CSV Files for D3 Visuals in Django App
I am trying to test the capability of adding D3 Visualizations into my Django app. I found and am using this Sun Burst code here (thanks to Eduard Trott and Serhii Pahuta): https://bl.ocks.org/maybelinot/5552606564ef37b5de7e47ed2b7dc099 The page renders just fine when using the default code (since the data from that code is being called from an internet location, however, it fails when I try to use my own static file in the following way: d3.json("file_path_on_local_machine/json_file", function(error, root) { ... }; How do I properly call my data into this code? -
while sending data to api it gives integrity error
when i send date to my api it throws the following error IntegrityError at /api/add/ NOT NULL constraint failed: api_userinfo.user_id urls.py path('add/',views.UserAdditionalView.as_view()) models.py class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) #phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') #phone = PhoneNumberField(unique=True,blank=False,null=False) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email class UserInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) address = models.CharField(max_length=50) zipcode = models.CharField(max_length=20) def __str__(self): return str(self.user) my views is views.py class UserAdditionalView(generics.ListCreateAPIView): queryset = UserInfo.objects.all() serializer_class = UserAdditionalSerializers i'm trying to add more user info to database through the api.i used djoser for registering of user. whenever i try to add user through postman it throws IntegrityError . i cant find a solution -
how to redirect after delete obj?
i want to redirect to that URL : user/str:username after delete task so I set success_url='user-tasks' but after delete task error (Page not found (404) ) appear . so is there any other way to use success_url ? #-----------------------views.py----------------------- class UserDeleteView(LoginRequiredMixin,DeleteView): model=tasks success_url='user-tasks' # <==== does not work def test_func(self): task=self.get_object() if self.request.user == task.user: return True return False #----------------------------------------------------- #----------------------urls.py------------------------------------------------------- from django.urls import path from . import views from . views import TaskListView,TaskCreateView,TaskUpadteView,UserTaskListView urlpatterns = [ path('', views.TaskListView.as_view(),name='home-page'), path('task/new/', views.TaskCreateView.as_view(),name='create-task'), path('task/<int:pk>/update/', views.TaskUpadteView.as_view(),name='update-task'), path('task/<int:pk>/delete/', views.UserDeleteView.as_view(),name='delete-task'), path('user/<str:username>', views.UserTaskListView.as_view(),name='user-tasks') ] #------------------------------------------------------------------------------------ enter image description here -
From a django library can we overwrite only parts of a viewset instead of rewriting the viewset completely?
I am working with djoser and upon reading the documentation, I want to alter some parts of the code from Userviewset. I want to overwrite def me(self, request, *args, **kwargs) and customize it. For the get request, instead of returning all the fields of the model, I want to return only Username and Profile Picture. I tried doing from djoser.views import UserViewSet. Then, class UserViewSet(viewsets.ModelViewSet): # from djoser docs which I want to update @action(["get", "put", "patch", "delete"], detail=False) def me(self, request, *args, **kwargs): self.get_object = self.get_instance if request.method == "GET": return self.retrieve(request, *args, **kwargs) elif request.method == "PUT": return self.update(request, *args, **kwargs) elif request.method == "PATCH": return self.partial_update(request, *args, **kwargs) elif request.method == "DELETE": return self.destroy(request, *args, **kwargs) But I wonder this would work since neither retrieve nor get_instance are mentioned. Is there a shorter correct way to do this? -
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'))