Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i loop through blog posts and show it as this template in django?
i got a beginning level problem, actually i found a free template , and i'm trying to do the backend for template, but i don't know how i can show post lists same as the template in djnago, basically i'm trying to say that how can i implement or loop through and show my posts same as it is shown in template. I"m trying to do something like this template but i don't know how can i loop through and show it same as template. -
Profile ID not stored in User after creation Django
I wrote the following code: class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') @login_required(login_url="/login") def index(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): profile = Profile().save() user = form user.profile = profile user.save() return redirect('users') else: print(form.errors) else: form = RegisterForm() user_model = get_user_model() users = user_model.objects.all() paginator = Paginator(users, 15) page = request.GET.get('page') users = paginator.get_page(page) return render(request, 'users/index.html', {'users': users, 'form': form}) class Profile(models.Model): has_premium_until = models.DateTimeField(null=True, blank=True) has_premium = models.BooleanField(default=False) has_telegram_premium_until = models.DateTimeField(null=True, blank=True) has_telegram_premium = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class CustomUser(AbstractUser): email = models.EmailField(max_length=255, unique=True) profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True) When I'm submitting the form the user as well as the profile is created but the profile is not stored in the user (the profile_id stays null). Anyone who can help me out? -
Access a field of a through Model of an ManyToManyField before saving
I am trying to sum the cost of the ingredients of a recipe to have the total cost of a recipe. However when I try to access the cost of "ingredients" or "Ingredient.objects.filter(recipe=self)" these objects aren't created even after a manual save to super. I did however notice if I save it through the Django Admin twice the "Ingredient" objects are populated and the cost field is available. So how can I sum up the total cost of recipe cause my way seems not to work properly? Thanks in advance. class Material(models.Model): UNITS = [ ('kg', 'kg'), ('g', 'gramm'), ('l', 'liter'), ('stk', 'Stuck'), ('dkg', 'deka'), ] name = models.CharField(max_length=200) unit = models.CharField(max_length=20, choices=UNITS, default="kg", verbose_name="Einheit") lieferant = models.ForeignKey(Lieferant,default=1, verbose_name="Lieferant",on_delete=models.CASCADE, null=True) costpunit = models.FloatField(verbose_name="Stuckpreis") menge = models.FloatField(default=1,verbose_name="Menge") costpkg = models.FloatField(editable=False, verbose_name="Kilopreis") class Meta: verbose_name_plural = "Materialien" def __str__(self): return self.name def save(self): if self.unit and (self.unit is not "stk"): kilogramms = convert_SI(self.menge, self.unit, "kg") self.costpkg = self.costpunit/kilogramms super(Material, self).save() class Recipe(models.Model): name = models.CharField(max_length=200) cost = models.FloatField(default=1, editable=False, verbose_name="Kosten") ingredients = models.ManyToManyField(Material, through='Ingredient') def __str__(self): return self.name def save(self): x = 0 super(Recipe, self).save() for ing in Ingredient.objects.filter(recipe=self): x += ing.cost self.cost = x super(Recipe, self).save() class Ingredient(models.Model): UNITS = [ … -
Django Rest Framework Schema view
I follow a tutorial to generate a dynamic schema with SchemaView https://www.django-rest-framework.org/api-guide/schemas/#generating-a-dynamic-schema-with-schemaview In my main urls.py I do: apiv1_urlpatterns = [ url(r'^company/', include('app.company.api_v3.urls', namespace='company')), url(r'^geographic/', include('app.geographic.api_v3.urls', namespace='geographic')) ] urlpatterns += [ url(r'^api/v1/', include(apiv1_urlpatterns, namespace='api_v3')), ] schema_v3_view = get_schema_view( title='MY API Verson 3', url='https://www.example.org/api/', patterns=apiv1_urlpatterns ) urlpatterns += [ url(r'^open-api/v1/', schema_v1_view, name='openapi-v1-schema'), ] And this is what I see: If I remove patterns param, then I get: { "detail": "You do not have permission to perform this action." } -
Potential docker permission issue is causing pillow to say it's not installed, although it is
Following This Tutorial Basically my issue is that when I try to run a certain command, I get a permission error. This ends up affecting other parts of my workflow despite not having an immediate impact. When Running: RUN pip install --upgrade pip RUN pip install --no-cache /wheels/* I Get: WARNING: The directory '/home/app/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. WARNING: The directory '/home/app/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. And then oddly, I go to run: docker-compose -f docker-compose.prod.yml exec app python manage.py migrate --noinput I get a weird error saying: estimate_creator.TopLevelService.service_image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". I do have Pillow installed, and there isn't an issue with it in my development environment. No problem though, I'll just install it. So … -
why django-daphne is not working with docker?
I have a local & production docker-compose services for my django app, in the local service all be right, but in the production service daphne not work, in the same the redis connection is equals and i'm not using a special network conf for my docker compose services. local compose: version: "3" services: app: image: dspm build: context: . dockerfile: ./compose/local/Dockerfile environment: - DJANGO_SETTINGS_MODULE=psvt.settings.local volumes: - ".:/django/" ports: - "8000:8000" depends_on: - redis - db links: - redis:redis - db:postgres redis: image: redis restart: always expose: - '6379' daphne: restart: always image: "dspm:latest" working_dir: /django/ command: bash -c "daphne -b 0.0.0.0 -p 8001 psvt.asgi:channel_layer" ports: - "8001:8001" environment: - REDIS_HOST=redis - DJANGO_SETTINGS_MODULE=psvt.settings.local depends_on: - redis links: - redis db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ expose: - "5432" volumes: postgres_data: production: (here daphne is not working) version: "3" services: app: image: dspm_production build: context: . dockerfile: ./compose/production/Dockerfile #command: bash -c "gunicorn psvt.wsgi:application --bind 0.0.0.0:8000" command: bash -c "./manage.py runserver" working_dir: /django/ environment: - DJANGO_SETTINGS_MODULE=psvt.settings.production volumes: - ".:/django/" - static_files:/static/ - media_files:/media/ ports: - "8000:8000" depends_on: - redis - db links: - redis:redis - db:postgres daphne: restart: always image: "dspm_production:latest" working_dir: /django/ command: bash -c "daphne -b 0.0.0.0 -p 8001 psvt.asgi:channel_layer" ports: … -
django models return empty when use templete but have result witout template
when i have this in view.py def index(request): products = product_page.objects.order_by('name')[:5] output = ', '.join([q.name for q in products]) return HttpResponse(output) it return test1,test2 but when change it to def index(request): products = product_page.objects.order_by('name')[:5] context = { 'products': products, } return render(request, 'dashboard/index.html', context) and have a index.html in /dashboard/template/dashboard <html> <head> <title>test</title> </head> <body> <h1>PRODUCTS LISsssT</h1> {% if products %} test in if {{produtcs}} <ul> {% for product in produtcs %} test in for <li><a href="#">{{ product.name }}</a></li> {% endfor %} </ul> {% else %} <p>No product are available.</p> {% endif %} <ul><li>hello</li></ul> </body> </html> i got no <li> tag, i using django==2.2.8 -
how to implement archiving of old users in my app
I am working on a Django project where user data needs to be archived after they have left the platform. This means that we still wanna show old users to the admins of the site but only in a read only manner; we want to completely freeze their records and prevent all changes to their data. -
Conditionally create different sets of crispy forms from multiple models
I want to create different sets of forms depending on some attribute. I expect similar to: Conditionally display a Fieldset with Crispy Forms except I have multiple models in play - my case is about displaying one form or another, not conditionally displaying part of a form. models.py: class Zoo(models.Model): zoo_id = models.AutoField(primary_key=True) zoo_name = models.CharField( max_length=100, verbose_name=Zoo Name') class Animal(models.Model): zoo = models.ForeignKey(Zoo, on_delete=CASCADE) animal_id = models.AutoField(primary_key=True) animal_name = models.CharField( max_length=100, verbose_name=Animal Name') class Dog(models.Model): dog_id = models.IntegerField(primary_key=True) animal_id = models.ForeignKey(Animal, on_delete=models.CASCADE) collar_type = models.CharField( max_length=100, null=True, verbose_name='collar_type') class Cat(models.Model): cat_id = models.IntegerField(primary_key=True) cat_id = models.ForeignKey(Animal, on_delete=models.CASCADE) meow_type = models.CharField( max_length=100, null=True, verbose_name='meow_type') The behaviour i'm looking for is to: 1) always display the animal form. 2) display EITHER dog or cat forms - depending on the zoo. I set this project up by adding animal, then dog forms and have that roughly working. However, the way my views.py is set up just now has a lot of context setting for Dog forms - here is an example. I would like to know if there is a good pattern to follow so I don't end up with if zoo_id = 1: DogForm else: CatForm type statements everywhere. (Plus I … -
How can i implement or loop through these blog post layout same way in django template?
i got a beginning level problem, actually i found a free template , and i'm trying to do the backend for that template, but i don't know how i can show post lists same as the template in djnago, basically i'm trying to say that how can i implement or loop through and show my posts same as it is shown in template. [<section class="blog_area p_120"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="blog_left_sidebar"> <article class="blog_style1"> <div class="blog_img"> <img class="img-fluid" src="{% static 'img/home-blog/blog-1.jpg' %}" alt=""> </div> <div class="blog_text"> <div class="blog_text_inner"> <div class="cat"> <a class="cat_btn" href="#">Gadgets</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> March 14, 2018</a> <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 05</a> </div> <a href="#"> <h4>Nest Protect: 2nd Gen Smoke + CO Alarm</h4> </a> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.</p> <a class="blog_btn" href="#">Read More</a> </div> </div> </article> <div class="row"> <div class="col-md-6"> <article class="blog_style1 small"> <div class="blog_img"> <img class="img-fluid" src="{% static 'img/home-blog/blog-small-1.jpg' %}" alt=""> </div> <div class="blog_text"> <div class="blog_text_inner"> <div class="cat"> <a class="cat_btn" href="#">Gadgets</a> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> March 14, 2018</a> <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 05</a> … -
How do you implement groups/permissions with an abstractUser in Django 2.2.9
I can create groups in my /admin and I have created a field called group on my CustomUser(AbstractBaseUser,PermissionsMixin) model as shown here: group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) I can put the user in a different Group. The issue is that the permissions are not enforced... user is not a super user. Can someone show me a clean and simple implementation on how to use permission groups with an abstract user in django? I am unable to find any good references explaining how to do it. -
Uncaught ReferenceError: $ is not defined - Django with adminlte2
I don't have much experience with Django and even less with jQuery. I'm currently building an app using Django 3.0 and installed django-adminlte2 to put a nice skin on it. However, I seemingly cannot get jQuery to work with extended templates. I've tried adding a line to print out something at the top of the templates, but it only works when I have jQuery defined in the same template. I have made sure that STATIC_URL and STATIC_ROOT have been defined in settings.py and are point to the correct location. Here is the code that includes the file with the definitions (this is in base.html): {% block javascript %} {% include 'adminlte/lib/_scripts.html' %} {% endblock %} The file itself: {% load static %} {% block scripts %} <script src="{% static "jquery/dist/jquery.min.js" %}"></script> <script src="{% static "jquery/dist/jquery-ui.min.js" %}"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <script src="{% static "bootstrap/dist/js/bootstrap.min.js" %} "></script> <script src="{% static "admin-lte/dist/js/app.min.js" %}"></script> {% endblock %} Where I'm trying to use jQuery: {% extends "adminlte/base.html" %} <script>let sg_v2 = $('<div>daughter jQuery is okay</div>'); console.log(sg_v2.text())</script> I debug it with Pycharm and get "Uncaught ReferenceError: $ is not defined". If I boot up … -
ValueError at /user/register Cannot assign "('Civil Engineering (CE)',)": "User.department" must be a "Department" instance
i can not inserting data into database i want to create a user with specific department name and the department table with foreign key to detect the user from which department here is my model file model.py class Department(models.Model): name = models.CharField(max_length=100, blank=False, null=False) admin_id = models.ForeignKey('Admin' , on_delete=models.CASCADE) admin_post_id = models.ForeignKey('Admin_Post' , on_delete=models.CASCADE) def __str__(self): return name this is my custom user model class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) address = models.CharField(max_length=150) phone_number = models.IntegerField( blank=False, null=False, unique=True) department = models.ForeignKey('Department' , on_delete=models.CASCADE) semester = models.FloatField(blank=False, null=False) registation = models.IntegerField(blank=False, null=False, unique=True) email = models.EmailField(max_length=150, blank=False, null=False, unique=True) password = models.CharField(max_length=150, blank=False) password_con = models.CharField(max_length=150, blank=False, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email'] objects = UserManager() def _str__(self): return registration; here is my view file views.py def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] address = request.POST['address'] phone_number = request.POST['phone_number'] department = request.POST['department'] semester = request.POST['semester'] registration = request.POST['registration'] email = request.POST['email'] password = request.POST['password'] password_con = request.POST['password_con'] user = Department() user = User.objects.create_user(first_name=first_name ,last_name=last_name ,address=address ,phone_number=phone_number ,department=department ,semester=semester ,registration=registration ,email=email ,password=password) if User.objects.filter(email=email).exists(): messages.info(request,'Email is Already taken') elif User.objects.filter(registration=registration): messages.info(request,'Registration Id is Already taken') elif password != password_con: … -
Secure way to upload images to Instagram Account using Instapy-cli?
Since, there is no official way to publish content to a user's instagram feed (from PC using Instagram Graph API), Insta-Py is there as a third party alternative. But this violates user security (as password is exposed), is there any way to use Insta-Py CLI securely. We are building an Web Application which needs to upload images to Instagram. What is best secure workaround for it. -
How to slice a paginated view in jinja2 django?
I have this paginated generic ListView class ShoseListView(generic.ListView): model = Shose context_object_name = "Shose_list" template_name = "products/listings.html" paginate_by = 8 I want to slice it in two parts and use it but there is problem with slice {% for shose in Shose_list|slice(4) %} TemplateSyntaxError slice requires 2 arguments, 1 provided although i read the jinja documentation its work fine with one argument -
How do I return the difference from two DateTimeFields in Django Models?
I'm trying to create a simple timesheet that includes time in, time out, and total time in separate columns, but I'm running into troubles trying to work with the DateTimeFields. I initially tried this in my models.py: class Entry(models.Model): time_in = models.DateTimeField(default=timezone.now) time_out = models.DateTimeField(default=timezone.now) total_time = models.Duration(time_out - time_in) and after reading some answers I tried this: class Entry(models.Model): time_in = models.DateTimeField(default=timezone.now) time_out = models.DateTimeField(default=timezone.now) @property def duration(self): return self.time_out - self.time_in and both returned TypeErrors (- is an unsupported operand for DateTimeField). I tried adding this to the View: def new_entry(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): timeIn = form.cleaned_data.get('time_in') timeOut = form.cleaned_data.get('time_out') totalTime = timeOut - timeIn form.save() But if this is the right direction to take, I'm not sure how to send it back to the model and into my database table without it being a circular import. -
Não consigo incrementar no Django
(Estou utilizando o Python 3.8 e Django 3.0). Sou iniciante e estou praticando fazendo uma APP para controlar pagamentos, Uma empresa pode ter mais de um pagamento, por isso preciso saber o total pago por empresa. MODELS from django.db import models class Pagamento (models.Model): empresa = models.CharField(verbose_name=("Empresa"), max_length=80, blank=False, null=False) valor = models.DecimalField(verbose_name="Valor Total da Nota", max_digits= 10, decimal_places= 2, default=0) def get_total(self): tot = 0 for self.valor in Pagamento: tot += self.valor return tot def __str__(self): return str(self.empresa) class Meta: verbose_name_plural = "Pagamento de notas" ADMIN from django.contrib import admin from .models import Pagamento class PagamentoAdmin(admin.ModelAdmin): list_display = ('empresa', 'valor', 'get_total') def get_total(self, obj): return obj.get_total() get_total.short_description = 'Total' DJANGO ADMIN No meu DJANGO ADMIN quando eu comento o "FOR" aparece: enter image description here -
localhost:8000 working but mywebsite:8000 with etc/hosts modified doesn't work
Everything is in the title: I'm launching my webserver (Django / Python) on port 8000. /home/olivier/my_venv3.8/bin/python3 /home/olivier/pycharm-2018.1.3/plugins/python/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 40761 --file /home/olivier/projects/evalr/manage.py runserver 8000 pydev debugger: process 5923 is connecting Connected to pydev debugger (build 193.5662.61) http://evalr.hqf.fr:8000/fr/assistant/ http://evalr.hqf.fr:8000/fr/sessions/ pydev debugger: process 5935 is connecting http://evalr.hqf.fr:8000/fr/assistant/ http://evalr.hqf.fr:8000/fr/sessions/ Watching for file changes with StatReloader Performing system checks... I've added in my /etc/hosts this line : 127.0.1.1 evalr.hqf.fr and when I ping it, it correctly shows "127.0.0.1" When I try go on http://evalr.hqf.fr:8000 I get connection refused and when I try to go on http:/localhost:8000 it works. The problem is that when I try to go on http://evalr.hqf.fr:8000 I dont have any trace on the server side, i.e. it stays here: System check identified no issues (0 silenced). January 03, 2020 - 20:41:31 Django version 3.0.2, using settings 'evalr.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. And when I go on http://127.0.0.1:8000/ I get a log of every single access like: [03/Jan/2020 20:47:42] "GET /fr/sessions/ HTTP/1.1" 302 0 [03/Jan/2020 20:47:42] "GET /fr/login/?next=/fr/sessions/ HTTP/1.1" 200 7031 [03/Jan/2020 20:47:43] "GET /static/vendors/css/all.min.css HTTP/1.1" 200 54456 ................ blabla............; [03/Jan/2020 20:47:43] "GET /favicon.ico HTTP/1.1" 301 0 I've even tried to reboot (even … -
Django 3.0 message close button is not working
I'm using this code: {% if messages %} {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> {% endfor %} {% endif %} Massages are displayed correctly but I have some problem with close button. It's not working. I can't close any message. Django 3.0/2.2 - same problem Any Ideas? -
google-appengine"KeyError: 'REQUEST_METHOD'" error
I do not know why i am getting this error. It has something to do with appengine but do not understand it enough to debug it. Does anyone know why i could be getting this error. I am using Django 1.2 and python 2.7; the project i am working on is an old web app KeyError: 'REQUEST_METHOD' Traceback (most recent call last): File "main.py", line 1429, in <module> main() File "main.py", line 1426, in main run_wsgi_app(application) File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/ext/webapp/util.py", line 101, in run_wsgi_app run_bare_wsgi_app(add_wsgi_middleware(application)) File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/ext/webapp/util.py", line 119, in run_bare_wsgi_app result = application(env, _start_response) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webapp2.py", line 1548, in __call__ return self._internal_error(e)(environ, start_response) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webob/exc.py", line 358, in __call__ is_head = environ['REQUEST_METHOD'] == 'HEAD' KeyError: 'REQUEST_METHOD' -
How to have multiple of the same form on the same page in django
I am using the same form multiple times on my webpage. This is my views.py if request.method == "POST": form1 = TheForm(request.POST) form2 = TheForm(request.POST) form3 = TheForm(request.POST) if form1.is_valid() and form2.is_valid() and form3.is_valid(): This is my template page: <form method="POST"> {% csrf_token %} {{form1.as_p}} {{form2.as_p}} {{form3.as_p}} <button class="waves-effect waves-light btn"> Button </button> </form> When I try this however it only saves values from form3 not the others. Thanks -
How can I find the total number of users?
I'm looking for a way to get the total number of users in Django. My best guess would be something like: {{users.count}} I've tried finding it on google with no luck -
[ Migration between postresql and Django ]
i have a Customer table in pgadmin, postgresql and Customer app in Django with almost the same Fields. Both customer table in postresql and Customer in Django contains the Customername, Paymentterms QuotationTerms and OrderCurrency. How to migrate the added Django objects to the postgresql table? regards, -
How do I display fractions in a Django App?
I am trying to display fractions on a website. I need them to add different dimensions for products and i do that in the django admin. I wrote a template tag, which you can see here. It works on firefox, but not on other browsers. I appreciate any help on this. Thank you in advance. https://i.stack.imgur.com/pRowC.png -
A little confused about Django generic views
my question could be very basic and I apologize for posting such questions here. Unfortunately, I couldn't find a proper solution for this. I've got two classes, one of them inherits from generic.DetailView and the other one inherits from generic.ListView. Besides getting details of the Post model, I would like to call a query in the same template to pull out posts that are marked as essential. Though, I'm a little confused about the correct way of doing it. I would be thankful if anyone guides me about this. from django.shortcuts import render from django.views import generic from .models import Post class Details(generic.DetailView): model = Post class EssentialPosts(generic.ListView): def getessentialposts(self): queryset = Post.objects.filter(essential=True).order_by('-created_on') return queryset class PostDetail(Details , EssentialPosts): template_name = 'post-detail.html'