Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i make a qrcode from a python function with django
im doing a school project where i need a slackbot to send a message to the chat when scanning a qrcode. Im having problems finding a solution where i can convert the python function to a qrcode inside a html template. views.py: from django.shortcuts import render from rest_framework import viewsets import os import slack import qrcode from dotenv import load_dotenv from django.contrib import messages load_dotenv() client = slack.WebClient(token=os.getenv("SLACK_TOKEN")) #Index view def home(request): return render(request, 'rest/index.html') #Beer function def nobeer(request): data = client.chat_postMessage( channel='#general', text="some text here" ) qr.add_data(data) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') messages.success(request, 'message sent to slack') return render(request, 'rest/index.html') index.html <title>Slackbot</title> </head> <body> <div class='container'> <div class='row'> <div class='col'> <div> {% load qr_tags %} {% qr_from_object nobeer “size” %} </div> </div> <div class='col'></div> <form method="POST" action="/api/beer/"> {% csrf_token %} <button type="submit" class="btn btn-primary">send message</button> </form> </div> </div> <div> {% if messages %} {% for message in messages %} {% if message.tags %} <script>alert("{{ message }}")</script> {% endif %} {% endfor %} {% endif %} </div> </div> </body> </html> -
How do i hide button in user profile
How do i hide edit profile button in my profile page from other users, i want only the profile owner to be able to access the edit profile button. When every other users view another user profile page, the edit profile button will not be displayed to other users but only to the owner of the profile. I attached an image for a clear explanation. I tried this: {% if request.user.is_authenticated %} Edit Profile {% endif %} but did not hide the Edit Profile button. How can i do this using only template? -
Django REST framework dict to viewsets
I would like use viewsets with router. I have script with dict response. I can work with APIView because result is dict response, but viewsets need serializer and queryset. How I can do with viewsets? class Myapi(APIView): def get(self, request): vars_dict = my_script_result_dict response = JsonResponse(vars_dict) return response -
GeoDjango and postgis setup in docker
I'm trying to create a docker setup such that I can easily build and deploy a geodjango app (with postgis backend). I have the following folder structure: |-- Dockerfile |-- Pipfile |-- Pipfile.lock |-- README.md |-- app | |-- manage.py | |-- app | `-- app_web In my Dockerfile to setup Django I have the following: # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install pipenv COPY . /code WORKDIR /code/ RUN pipenv install --system # Setup GDAL RUN apt-get update &&\ apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal # set work directory WORKDIR /code/app CMD ["python", "manage.py", "migrate", "--no-input"] In my docker-compose.yml file: version: '3.7' services: postgis: image: kartoza/postgis:12.1 volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /code/app/manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/code depends_on: - postgis volumes: postgres_data: And finally in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'postgis', }, } Now when I: run docker-compose up --build It all seems to work (both the database as well as the django app spin up their containers). But whenever I try to actually work with the database … -
How to pass multiple values in Django template
I made a change to the quantity of the shopping cart using css / javascript without using the django form. I want to pass multiple values to request.POST outside the form tag. How can I pass values by request.POST? <tbody> {% for cart in carts %} <tr> ... <td> <form id="update" action='{% url "cart:update_cart" %}' method="post"> <input class="cart-qt" type="text" name="cart-{{forloop.counter}}" value="{{ cart.quantity }}"> {% csrf_token %} </form> </td> ... <tr> </tbody> {% endfor %} ... <div class="cart-bt"> <button type="submit" form="update">Update Cart</button> </div> -
Filter objects in ManyToMany relationship by multiple criteria
I want to get the model instance of my 'Collection' object where 'request.user' is either in 'owner' or 'contributors' relationship and id of that object is 'collection_id'. Here is my code: models.py class Collection(models.Model): title = models.CharField(max_length=250, unique=True) owner = models.ForeignKey(User, related_name='owner', on_delete=models.DO_NOTHING) contributors = models.ManyToManyField(User, related_name='contributors', blank=True) views.py def collection_edit(request, collection_id) ... # Here I want to check if request.user is in contributors or owner collection = Collection.objects.filter(owner_id=request.user, pk=collection_id).first() # Do stuff ... Also is 'on_delete=models.DO_NOTHING' in owner relationship going to break my database integrity if user is deleted? -
How to link login user to post that he created?
I'm learning django and i made the tutorial on django site. I thought that i could link user to poll that he created but i'm strugling with it. When i'm logged in and creating a poll i can't see user name. In database column "author_id" has value "null". I would appreciateevery help. Here is my code from django.db import models from django.utils import timezone import datetime from django.contrib import auth # Create your models here. User = auth.get_user_model() class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py: class UserCreateForm(UserCreationForm): class Meta: fields = ('username', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' class CreatePollForm(forms.ModelForm): class Meta: model = Question fields = ('question_text',) and views.py class CreatePoll(LoginRequiredMixin, generic.CreateView): form_class = forms.CreatePollForm success_url = reverse_lazy('pollapp:index') template_name = 'polls/createPoll.html' -
Retrieving model objects created by different users in Django
I am making simple feed which consists of entries made by authors which current user is subscribed to. I have 3 models which are default user model, my "Post" model which is related to User via ForeignKey: class Post(models.Model): ... author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") ... "Relations" model which has 2 fields: follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follows") following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followed") So I wrote this code to retrieve needed posts: user = request.user posts = Post.objects.filter(author__in = [relation.following_id for relation in user.follows.all()]).all() And honestly it works just fine, but is there any way to make my query better? Thank you. -
Django basic models logic
Looking for a way to create a model with a lot of tasks, each task is boolean ('Completed', 'Uncompleted'), and also it's own uniqe timestamp. class project(models.Model): task1 = models.BooleanField() task1date = models.DateTimeField() [...] It's don't make amy sence to me, since there will be a lot to tasks. Every task has it's own title, the title stay the same for every single project (A list of tasks, if you will), but i need an sperate timestamp for the time the task have completed on the speacific project. What am i missing? -
Django: how to make React and export/import work in a single JS static file?
In my Django template, I am loading React via CDN and also loading the index.js script from static url where the React code lives: <!DOCTYPE html> <html> {% load static %} <head> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script> </head> <body> <div id="root"></div> </body> <script src="{% static 'react/js/index.js' %}" type="text/babel"></script> </html> Index.js is: class App extends React.Component { constructor() { super() } render() { return <div>App</div> } } ReactDOM.render(<App />, document.getElementById('root')) This works fine. But I also have helpers.js script sitting in the same static directory as index.js and if I try to import something from it in index.js: import { some_helper } from './helpers' class App extends React.Component { ... I get ReferenceError: require is not defined error in the browser console. I could change the script type to module to make import/export work, but then React would not work. So instead I included require over CDN in index.html: <!DOCTYPE html> <html> {% load static %} <head> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script> </head> but then I get the following error in the console: Error: Module name "helpers" has not been loaded yet for context: _. Use require([]) https://requirejs.org/docs/errors.html#notloaded and I don't know how to move on from … -
Ajax with forms
Fairly new Django developer here. Have a question regarding how to add ajax to an entry form. I want to be able to have options that can be selected (one to many) that can be modified during entry of the main project. Much like the inline crud from the admin page. Is there a simple way to do this... Where I want to add the ajax crud inline -
Converting Function Based View to class Based View
I want to implement a bootstrap modal for a CreateView with JSon response. I have already done something similar to this before with function based views. However, when I try it with Class Based Views (CBV), I get numerous errors. After I solve one error, I get another one. I don't even know what is wrong now because the current error is not really explanatory. forms.py: class CategoryForm(ModelForm): category_name = forms.CharField(max_length=70) class Meta: model = Category fields = ['category_name'] def __init__(self, user, *args, **kwargs): super(CategoryForm, self).__init__(*args, **kwargs) views.py class CategoryCreateView(LoginRequiredMixin, CreateView): form_class = CategoryForm data = dict() def get_context_data(self, **kwargs): # Call the base implementation first to get a context #context = super().get_context_data(**kwargs) #context['form'] = form_class context = {'form': form_class} return context def form_valid(self, form): form.instance.user = self.request.user form.save(commit=True) data['form_is_valid'] = True data['html_form'] = render_to_string('partial_category_create.html', super().get_context_data(), request=self.request ) return JsonResponse(data) def form_invalid(self, form): data['form_is_valid'] = False data['html_form'] = render_to_string('partial_category_create.html', super().get_context_data(), request=self.request ) def post(self, request): form = CategoryForm(data=request.POST, user=request.user) def get(self, request): form = CategoryForm(request.user) data['html_form'] = render_to_string('partial_category_create.html', super().get_context_data(), request=self.request ) The code below is basically the functionality I want to implement in Class Based Views @login_required def category_create(request): data = dict() if request.method == 'POST': form = CategoryForm(data=request.POST, user=request.user) … -
Unable to runserver Django
I am unable to runserver in a Django-Python code. I read that it could be related to the models.py file. Here is the file: from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __Str__(self): """Return a string representation of the model""" return self.text class Entry(models.Model): """Something specific learned about the topic.""" topic = models.ForeignKey('Topic',on_delete=models.PROTECT) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model""" return self.text[:50] + "..." -
How to use a reverse url lookup with argument in Django?
I have the following URL config in my Django project: urlpatterns = [ path('', views.record_create), path('<entry_method>/', views.record_create, name = "record_create"), ] The view goes: def record_create(request, entry_method="bulk/"): In my template I do: <a href="{% url "record_create" entry_method=request.path_info %}"> And I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'record_create' with keyword arguments '{'entry_method': '/bulk/'}' not found. 1 pattern(s) tried: ['(?P<entry_method>[^/]+)/$'] Not sure what I'm doing wrong. Any suggestions are welcome. -
How can I add parameters to a Python Shell command?
I have a Django + Python application. I have a python script that takes requirements as command line options. The issue for me is that when I try to put in the command line arguments he script fails to execute. When I take out he command line arguments, it runs fine. I need those command line arguments. I am using node JS with Python Shell to execute the python script when the button is clicked in the django HTML front page. Here is my code: let {PythonShell} = require('python-shell') var path = require("path") function track_object() { //document.getElementById("detect").value = "One moment please ..." var python = require("python-shell") var path = require("path") //let {PythonShell} = require('python-shell') var options = { scriptPath : path.join(__dirname, '/../engine/opencv-object-tracking/'), pythonPath : '/usr/bin/python' } **//let pyshell = new PythonShell("opencv_object_tracking.py --video dashcam_boston.mp4 --tracker csrt", options); let pyshell = new PythonShell("opencv_object_tracking.py", options);** } Note: the two lines in bold are show the calling of the script with and without arguments Please let me know what is the correct way to pass command line arguments with Python Shell. -
How do I have the deletion of a user in Django trigger execution of some additional code?
In my Django application, when a user is created, a database is created too. This is defined in my registration view. I have the database creation to make up for the lack of support for dynamic models. My problem is that I want to have the deletion of a user in the Django admin page call some code which will also delete the database. I am not sure how to do this. -
How to add objects to a different model when using a form in Django?
I have a few forms that retrieve objects through a ForeignKey, e.g. Flight, Trip. So, for example, when someone tries to create a new Trip, they can choose an Hotel from a dropdown. My question is: how can we, on the Trip form, add an Hotel. Just like when using Django's own admin dashboard, where you get a plus sign, and you can add a new Hotel while creating a Trip. -
Combine independent form with DetailView
I want to display DetailView and independent form to send API request to the other website server. I made views.py but only i get is empty page. I'm trying to figure out how to adjust it for over past fiew days and still don't have any clue how to do this. Hope you will help me with this views.py class DetailPostDisplay(DetailView): model = EveryPost template_name = 'post/detailpost.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = DictForm() return context class DictWindowForm(SingleObjectMixin, FormView): template_name = 'post/detailpost.html' form_class = DictForm model = EveryPost def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('detailpost', kwargs={'slug': self.object.slug}) class DetailPostList(View): def get(self, request, *args, **kwargs): view = DetailPostDisplay.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = DictWindowForm.as_view() return view(request, *args, **kwargs) HTML I'm not sure whether action should be empty or include url DetailPostDisplay(require to pass slug, which i don't have how to get) <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" class="btn btn-dark float-right mt-2" value="Tłumacz"> </form> urls.py from django.urls import path from . import views from .views import PostListPl, PostListRu, DetailPostDisplay urlpatterns = [ path('', PostListPl.as_view(), name='index_pl'), path('ru/', PostListRu.as_view(), name='index_ru'), path('about/', views.about, … -
python-rq scheduler count the number of times job executed
I'm using Django-rq which has the functionality of Scheduling the jobs with specified interval. https://github.com/rq/django-rq#support-for-rq-scheduler task = scheduler.schedule( scheduled_time=datetime.utcnow(), # Time for first execution, in UTC timezone func=func, # Function to be queued args=[arg1, arg2], # Arguments passed into function when executed kwargs={'foo': 'bar'}, # Keyword arguments passed into function when executed interval=60, # Time before the function is called again, in seconds repeat=None, # Repeat this number of times (None means repeat forever) meta={'foo': 'bar'} # Arbitrary pickleable data on the job itself ) print(task.id) ### JOB ID 5eedcd69-a318-4195-959f-eb6a404dec97 Now we have the JOB which executes for every 60 seconds and returns JOB ID for our scheduler, All I wanted to see the (number of times/count the number of times) the job has been executed. example: checking job `queue.fetch_job('5eedcd69-a318-4195-959f-eb6a404dec97').count` should return `5` times after 5 minutes Is there any way to achieve it through the Django or RQ way? -
Can “list_display” in a Django ModelAdmin display other fields of realated table?
I can't get "list_display" to display field from related table. models.py class product(models.Model): product_id = models.AutoField(primary_key=True) EAN = models.CharField(unique=True, editable=False, max_length=13) Product_name = models.CharField(max_length=50) class price(models.Model): price_id = models.AutoField(primary_key=True) EAN = models.ForeignKey(product, to_field="EAN", on_delete=models.CASCADE) Vendor = models.ForeignKey(vendor, to_field="Vendor_name", on_delete=models.CASCADE) Qty = models.CharField(max_length=15) Price = models.DecimalField(max_digits=8, decimal_places=2, null=True) panels = [ FieldPanel('EAN'), FieldPanel('Vendor'), FieldPanel('Qty'), FieldPanel('Price'), ] hooks.py class price_admin(ModelAdmin): model = pricelist menu_label = 'price' menu_icon = 'pilcrow' menu_order = 300 add_to_settings_menu = False exclude_from_explorer = False list_display = ('EAN_id', 'Vendor_id', 'Price') # <-Here I have a problem list_filter = ('Vendor_id__Name',) search_fields = ('Vendor_id__Name', 'EAN_id__EAN') I'm able to get "Vendor_id__Name" to work in "list_filter" and "search_fields", but when I put "Vendor_id__Name" to list_display, I get this error: AttributeError: Unable to lookup 'EAN_id__Product_name' on price or price_admin So, what is the right way to display field(Vendor_id__Name in my case) from related table? Any help would be really appreciated!! -
Sending variable Client Side (JS Ajax) to Server Side (Python Django)
I am using Python 3.7.4 with Django 3.0.3 and I have a script Ajax in javascript run in the front end app. When the user click in link, a variable must to be sending to back end python. See the exemple $('.likebutton').click(function() { var catid; catid = $(this).attr("data-catid"); $.ajax({ type: "GET", url: "/likePost", data: { post_id: catid }, success: function(data) { $('#like' + catid).remove(); $('#message').text(data); } }) }); In the urlpattner of app I have urlpatterns = [ path('', views.index, name='index'), # index view at / path('likePost/<str:post_id>/', views.likePost, name='likepost'), # likepost view at /likepost ] In Debug I received the follow message error Not Found: /likePost [25/Feb/2020 16:12:17] "GET /likePost?post_id=1 HTTP/1.1" 404 2335 What I am doing wrong? -
Python - Django - Filter and count all people in first year from start date
I need to count all the people who are in the first year of the contract. I even made several attempts and failed. Can anyone help me? Thanks! Model: class Contracts(models.Model): person = models.CharField(max_length=50, null=True, blank=True, verbose_name='Name') start_date = models.DateField(null=True, blank=False, verbose_name='Start') def __str__(self): return '{}'.format(self.person) So far... View: def people_in_first_year(request): people = Contracts.objects.filter(Q(start_date__lte=timezone.now()) & Q(end_date__gte=timezone.now() + timedelta(days=365))) total_people = people.count() context = { 'total_people': total_people, } return render(request, 'people.html', context) -
Getting model instance by passing field name and not primary ID
I want to get a model instance using URL as http://127.0.0.1:8000/db/User/email (i.e. using email as a query) and not by http://127.0.0.1:8000/db/User/1/. How to approach this. Model: class Employee(models.Model): firstname = models.CharField(max_length=100) email = models.CharField(max_length=100) serializers.py class EmployeeSerializers(serializers.ModelSerializer): field = NestedSerializers() class Meta: model = Employee fields = '__all__' def create(self, validated_data): #overwrite this method for writable nested serializers. view.py: class UserView(viewsets.ModelViewSet): queryset = Employee.objects.all() serializer_class = EmployeeSerializers urls.py: router = routers.DefaultRouter() router.register('User', views.UserView) urlpatterns = [ path('', views.index, name='index'), path('/', include(router.urls)) ] Is it possible to do using ModelViewSet? -
Django REST Serializer Many to Many field displays only through table id, need list of many records
How do i get list of Many 2 Many field objects? I am just getting the ID. This one is MainHost class which is having Many2Many field class MainHost(models.Model): host_id = models.IntegerField(verbose_name='HOST ID', primary_key=True) group = models.ManyToManyField(MainGroup, related_name='hostgroups', through ='HostGroup') This class is created for through keyword, contains all the relationship for Host and Group class HostGroup(models.Model): host = models.ForeignKey(MainHost, on_delete=models.CASCADE) group = models.ForeignKey(MainGroup, on_delete=models.CASCADE) This class contains all the Groups data class MainGroup(models.Model): group_id = models.IntegerField(verbose_name='GROUP ID', primary_key=True) Serializer class class MainGroupSerializer(serializers.ModelSerializer): class Meta: model = MainGroup fields = ( 'group_id', 'group_name', .... 'groupinv_path' ) HostSerialzer class class MainHostSerializer(serializers.ModelSerializer): group = serializers.PrimaryKeyRelatedField(queryset=HostGroup.objects.all(), many=True) class Meta: model = MainHost fields = ( 'host_id', 'host_name', 'group' ) class HostGroupSerializer(serializers.ModelSerializer): host = MainHostSerializer() group = MainGroupSerializer() class Meta: model = HostGroup fields = ( 'id', 'host', 'group' ) read_only_fields = ['host', 'group'] def create(self, validated_data): host_data = MainHost.objects.create(**validated_data.get('host')) group_data = MainGroup.objects.create(**validated_data.get('group')) conn = HostGroup.objects.create( host=host_data, group=group_data ) return conn MainHost API response { "host_id": 4087, "host_name": "10.240.144.2", "group": [ 280, 285, 300 ] } 280, 285 and 300 are group objects from MainGroup I want to see the whole object content. MainGroup Response is showing the complete object. { "group_id": 2, "group_name": … -
Tabindex inDjango template does not move cursor to correct field
I have a Django form and want the user to be able to tab to the username, password and login button in that order. tabindex does not seem to work in my template. Instead it moves to username, login button and password in that order. <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td><div tabindex="1">{{ form.username }}</div></td> <td rowspan="2"><div tabindex="3"><button type="submit" class="btn btn-success">Login</button></div></td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td><div tabindex="2">{{ form.password }}</div></td> </tr> </table> </form> what am I doing wrong?