Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove Set-Cookie header from Django response
I've created a middleware but there doesn't seem to be a Set-Cookie header in the response? But when testing the responses, its definitely there MIDDLEWARE = ( "apps.base.middleware.RemoveHeadersMiddleware", ### ) class RemoveHeadersMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) # No Set-Cookie header here????? # del response._headers['Set-Cookie'] return response -
My HTML and CSS causes this padding issue to happen in Django
I am not sure why when resizing my page this happens around the iPad media query level, and then gets fixed for smaller mobile devices like the iPhone once the toggle hamburger icon appears. It is broken until it goes below 768 x 1080 and above 908 x 1080. A lot of this was copy, and paste as I was trying to understand it, but this is stumping me. If anyone can help explain this issue in detail I would be very appreciative. Navbar HTML: <nav class="sticky-top navbar navbar-custom navbar-expand-md"> <div class="container-fluid"> <a class="navbar-brand abs" href="{% url 'home' %}" >"Pure White Logo Here"</a > <button class="custom-toggler navbar-toggler ms-auto" type="button" data-bs-toggle="collapse" data-bs-target="#collapseNavbar" > <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="collapseNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Home" href="{% url 'home' %}" >Home</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="About" href="#" >About</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Leadership" href="#" >Leadership</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Programs" href="#" >Programs</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="News & Events" href="#" >News & Events</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Chapter Membership" href="#" >Chapter Membership</a > </li> <li class="nav-item"> <a class="nav-link" … -
Should a background process be part of Django project?
I'm trying to build a web app which provide an interface to do some queries upon data extracted from another public API server. To complete the queries in real time, I would have to prefetch the data from the public API server. So I think it is reasonable to separate the app deal with query input(there is still some logic here, so only javascript wouldn't be enough) from the app which runs in background and builds the database which could possibly answer the query in real time. Then what comes to my mind is does this background app really have to be a part of Django project? It runs almost without interacting with any Django component. Except for the database which is also accessible by a Django app and some signals maybe(when to start/stop collecting data, but this could probably also decided internally). What would a be good design choice for my situation? -
How to Dockerize a React-Django where the front-end is served from Django?
I'm new to Docker. I have been surfing through the internet to find any resources for how to Dockerize a React-Django project, in which the React App is served from Django, both running on port 8000, but couldn't find any proper resource for this. Can someone help me with the procedure for Dockerizing a React-Django project having a monolithic architecture? -
Django REST error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'BoundField'
I have a funtion which outputs friday by taking in week number as a parameter def fridayOfWeek(p_week): p_year=2021 monday = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date() wednesday = monday + datetime.timedelta(days=2) friday = monday + datetime.timedelta(days=6.9) - datetime.timedelta(days=2) return friday but when I serializer data and Set serialize = ExamSimulatorSerializer(request.data) date = fridayOfWeek(serializer["week"]) it gives me and error File "C:\Users\user1\Desktop\backend\data_manager\views.py", line 43, in examSimulator date = fridayOfWeek(m['week']) File "C:\Users\user1\Desktop\backend\week_into_date.py", line 10, in fridayOfWeek monday = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date() Exception Type: TypeError at /api/exam-simulator/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'BoundField' my serializer class class ExamSimulatorSerializer(serializers.Serializer): week = serializers.IntegerField() subject = serializers.CharField() code = serializers.CharField() def create(self, validated_data): pass my views.py @api_view(['POST']) @parser_classes([JSONParser]) def examSimulator(request): m = ExamSimulatorSerializer(request.data) code = m['code'] date = fridayOfWeek(m['week']) subject = Subject.objects.get(name = m['subject']) for s in subject.students.all().values(): student = Student.objects.get(roll_num=s['roll_num']) score = random.randint(25,95) Exam.objects.create(code=code, date=date, student=student, subject=subject,score=score) return Response(status=status.HTTP_200_OK) Moreover Is this the right way to make a model-less serializer class -
Fushioncharts msline using python(Django)
I try to use msline chart in Django. I write code in views.py. But i cannot find exact grammer of fusioncharts in msline. dataSource1['dataset'].append({"seriesName": '2012', 'value':['1','2','3','4']}) This code is my question. when I test in web, there is no data shown. I think the way of showing value is not correct. can you help me what is exact grammer or way to make value appear def get(request): # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs. dataSource1 = {} dataSource1['chart'] = { "caption": "Temperatures Today", "subCaption": "test", "xAxisName": "Hour", "yAxisName": "Temp C", "lineThickness": "2", "numberPrefix": "%", "theme": "zune", "showValues": "0", "rotateLabels": "0", "setAdaptiveYMin": "1", "theme": "fusion", } catlist = [] for i in range (4): catlist.append({'label':str(i)}) dataSource1['categories'] = [] dataSource1['categories'].append({'category' : catlist}) dataSource1['dataset'] = [] dataSource1['dataset'].append({"seriesName": '2012', 'value':['1','2','3','4']}) dataSource1['dataset'].append({"seriesName": '2013', 'value':['1','2','3','4']}) dataSource1['dataset'].append({"seriesName": '2014', 'value':['1','2','3','4']}) dataSource1['dataset'].append({"seriesName": '2015', 'value':['1','2','3','4']}) chart1 = FusionCharts("msline", "ex1" , "600", "450", "chart-2", "json", dataSource1) a = str(10) return render(request, 'chart.html', {'output1': chart1.render(), 'data':a}) #render -
Python Separate User Data - User Authentication/Access - Django
I've nearly built a full website using python and Django and now I need to build in separate user data. By this I mean I need to keep the same model and fields and pages but when User1 submits a form and it is displayed User2 who has logged in, the same form is there but User1's data will not be displayed for User2 to see and same for when User2 uploads data. I already have models made and I already have working signup and login. I've found a lot of information on restricting pages for curtain users and other things along those lines but that's not what I'm going for. This website will have a lot of users too so I can't really do something tricky with url's but I could be wrong. My models are very big so I would prefer a solution that automatically does something for all of them but at this point I'll take any solution and any help. Thanks! -
How to translate inline javascript?
So I'm working on a django project and we're having English translated to Czech (not important). I can do fine with regular tags being translated with {% trans 'sample text' %} However, I have a button inside a link and on click, this link returns a confirmation. The full html looks like this <a href="{% url 'foo' %}" onclick="return confirm( 'Sample text')"> <button> {% trans 'Regular trans tag' %} </button> </a> Now I would like to somehow translate the 'Sample text' text inside the confirm, however when I try it with {% trans %} it gives me error that 'foo/bar expected (js)' -
Why am I getting 'module not found' on my project when trying to deploy django with apache and bitnami?
I realize this question has been asked, I've tried the other solutions but can't get the configuration right. I'm using the django instance on aws lightsail. I've followed these tutorials to set it up https://aws.amazon.com/getting-started/hands-on/deploy-python-application/ (but instead of hello world I've cloned my own django project into bitnami/projects https://docs.bitnami.com/aws/apps/weblate/get-started/deploy-django-project/ (I'm using Approach A since that was what it said to use when I ran the test command it gives). I can access the site via the <ip-address>:8000 although it doesn't load resources properly (not sure if this is related, I assume it will resolve once I get my configurations correct.) If I go to the domain or the ip without port 8000, I get a 500 error and the following in the logs [Sat Jul 03 22:52:41.094053 2021] [mpm_prefork:notice] [pid 26130] AH00163: Apache/2.4.46 (Unix) OpenSSL/1.1.1d mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Sat Jul 03 22:52:41.094156 2021] [core:notice] [pid 26130] AH00094: Command line: '/opt/bitnami/apache/bin/httpd -f /opt/bitnami/apache/conf/httpd.conf' [Sat Jul 03 22:52:56.109689 2021] [mpm_prefork:error] [pid 26130] AH00161: server reached MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting [Sat Jul 03 22:52:56.111780 2021] [wsgi:error] [pid 26134] [remote x.x.x.x:61724] mod_wsgi (pid=26134): Failed to exec Python script file '/opt/bitnami/projects/onegoodear/onegoodearstudio/onegoodearstudio/wsgi.py'. [Sat Jul 03 22:52:56.111853 2021] [wsgi:error] [pid … -
How to get first N rows from every category in Django
I have following models, with many to many table, for which I would like to get first 20 news from every category in single response. class Category(models.Model): code = models.CharField(primary_key=True, max_length=45) name = models.CharField(max_length=200, blank=True, null=True) is_active = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'category' verbose_name_plural = 'Categories' class News(models.Model): source_code = models.CharField(max_length=45, blank=True, null=True) title = models.CharField(max_length=1000, blank=True, null=True) image = models.CharField(max_length=2000, blank=True, null=True) link = models.CharField(max_length=1000, blank=True, null=True) published_at = models.DateTimeField(blank=True, null=True) scraped_at = models.DateTimeField(blank=True, null=True) is_active = models.TextField(blank=True, null=True) # This field type is a guess. categories = models.ManyToManyField('Category', through='NewsCategory') class Meta: managed = False db_table = 'news' verbose_name_plural = 'News' class NewsCategory(models.Model): news_id = models.ForeignKey(News, db_column='news_id', on_delete=models.CASCADE) category_code = models.ForeignKey(Category, db_column='category_code', on_delete=models.CASCADE) class Meta: managed = False db_table = 'news_category' unique_together = (('news_id', 'category_code'),) verbose_name_plural = 'NewsCategory' My view class looks like this, and here I would like to add some logic to return 20 rows for each category, for example if I have 5 categories it should return 100 news in single request. class NewsViewSet(viewsets.ModelViewSet): http_method_names = ['get'] serializer_class = NewsSerializer def get_queryset(self): queryset = News.objects.all().order_by('-published_at') sources = self.request.query_params.getlist('sources') if len(sources) > 0: queryset = … -
Why is there no dropdown icon on the Form.Control component?
I created a drop-down select list so a user can choose the quantity of the product he/she wants. The problem is, that there is no drop-down mark (?) on the right of the list. { product.countInStock > 0 && ( <ListGroup.Item> <Row> <Col>Quantity:</Col> <Col xs="auto" className="my-1"> <Form.Control as="select" value={ quantity } onChange={ (e) => setQuantity(e.target.value) } > { [...Array(product.countInStock).keys()].map( (x) => <option key={x} value={x + 1}>{x + 1}</option> )} </Form.Control> </Col> </Row> </ListGroup.Item> ) } This is how it looks like at this moment: and this is how it should properly look like: How can I solve this issue? -
Django Paypal: How To Pass User ID With Webhooks Or In Subscription
I am trying to pass the user id with the webhook or the subscription so that i can know which user has subscribed. I have seen Stripe do this and the ipn methods for paypal do it so is there a way to do this by their REST API? Is there a better way to do this? i have seen a few hack ways of doing it but they don't seem like the best way. I am trying to look for ways so i think i can maybe pass the subscriber id by javascript on approve of the subscription and then use that to identify the user but i would rather not use ways that can be manipulated by javascript. -
Django UNIQUE constraint failed: accounts_users.email
I am setting up a multi user account with Django 3.2.3. The first model works perfectly. It generates the tokens for a login. However the inherited model "company"produces the error UNIQUE constraint failed: accounts_users.email I would appreciate your assistance. My Model class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if email is None: raise TypeError('Users should have a Email') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): if password is None: raise TypeError('Password should not be none') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user def get_by_natural_key(self, email): return self.get(email=email) class Users(AbstractBaseUser, PermissionsMixin): is_company = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(db_index=True, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' objects = UserManager() def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } def natural_key(self): return (self.first_name, self.last_name) def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class CompanyUserManager(BaseUserManager): def create_company( self, first_name, last_name, name_of_company, company_logo, email, password=None, **extra_fields ): if email is None: raise TypeError('Users should have a Email') user = Company(first_name=first_name, last_name=last_name, email=self.normalize_email(email), name_of_company=name_of_company, company_logo=company_logo ) user.set_password(password) user.save() return user class Company(Users, PermissionsMixin): first_name = … -
Django custom model- unable to make superuser
Forgive me if this may look like an obvious error. I made my own custom User model, called Account, with custom create_superuser() and create_user() methods below: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.urls import reverse from django.db import models from djstripe.models import Customer, Subscription # Create your models here. class AccountManager(BaseUserManager): def create_user(self, username, first_name, last_name, email, university, student_year, is_subscriber, password = None): if not username: raise ValueError("Users must have a username") if not email: raise ValueError("Users must have an email") user = self.model( first_name = first_name, last_name = last_name, username = username, email = self.normalize_email(email), university = university, student_year = student_year, ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, username, first_name, last_name, email, password): user = self.create_user( username = username, email = self.normalize_email(email), first_name = first_name, last_name = last_name, password = password, ) user.university = 'Stanford University' user.student_year = '5th +' user.is_subscriber = True user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self._db) return user def create_staffuser(self, username, first_name, last_name, email, password): user = self.create_user( username = username, email = self.normalize_email(email), first_name = first_name, last_name = last_name, password = password, ) user.university = 'Stanford University' user.student_year … -
Can't redirect from port 80 to Django app in docker using Nginx
I have 3 services in docker: db, nginx, django. version: "3.9" services: db: image: postgres volumes: ... web: build: . command: python3 -m gunicorn mysite.wsgi --bind 0.0.0.0:8000 volumes: - .:/mysite expose: - 8000 depends_on: - db environment: ... nginx: build: ./nginx ports: - 80:80 depends_on: - web I need to redirect my request from http://193.123.12.2 to my Django app and have access to the Django app via HTTP nginx.conf: upstream mysite { server web:8000; } server { listen 80; server_name 193.123.12.2; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } -
Gitlab Django CI/CD postgres: Connection refused
The Error I'm having a lot of trouble getting my Django CI/CD working. I am using Django + postgres, my test cases all pass but I want to implement continuous integration. Note the the following output is from the Gitlab Runner. I keep getting this error: (the ... is where I've left out some detail, but its just traceback or name specific stuff about my project etc.) $ cd src $ python manage.py makemigrations /usr/local/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? warnings.warn( Migrations for 'app': app/migrations/0001_initial.py - Create model ... ... ... $ python manage.py migrate Traceback (most recent call last): ... ... psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? … -
Self-submitting CreateView form
As a newcomer to Django, I'm struggling to achieve my ultimate aim of submitting a form to the same page on which it's defined and displaying values entered in the form within text elements of an SVG diagram, displayed below the form. Thus far, I've managed to create a form using a CreateView and can submit the contents of that form to a separate view which displays the entered values in SVG format... models.py class Diagram(models.Model): val1 = models.FloatField(null=True, blank=True, default=None) val2 = models.FloatField(null=True, blank=True, default=None) def get_absolute_url(self): return reverse('diagram-results', kwargs={'diagram_id': self.pk}) forms.py class DiagramForm(ModelForm): class Meta: model = Diagram fields = ['val1', 'val2'] views.py def show(request, diagram_id): try: diagram = Diagram.objects.get(pk=diagram_id) except Diagram.DoesNotExist: raise Http404("Diagram does not exist") return render(request, 'calc_app/diagram.svg', {'diagram': diagram}) class DiagramCreateView(CreateView): model = Diagram form_class = DiagramForm urls.py urlpatterns = [ path('diagram/add/', DiagramCreateView.as_view(), name='diagram-add'), path('diagram/<int:diagram_id>/', views.show, name='diagram-results'), ] diagram_form.html {% extends "calc_app/base_generic.html" %} {% block content %} <form action="." method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} diagram.svg <svg width="800" height="600" xmlns="http://www.w3.org/2000/svg"> <text id="val1" stroke="#ddd" y="50.0" x="50.0">{{ diagram.val1 }}</text> <text id="val2" stroke="#ddd" y="50.0" x="50.0">{{ diagram.val2 }}</text> </svg> I'd like to take this one step further and submit … -
AssertionError: Cannot filter a query once a slice has been taken. Python Django
When trying to check the form of validity if _dict['form'].is_valid()gives an error message AssertionError: Cannot filter a query once a slice has been taken. I understand that the error in phone = ChoiceTxtField(queryset=Clients.objects.order_by('-phone')[:1]) in forms.py. How to avoid this error when adding a form? some.py def checkRelatedAddForm(self, **kwargs): context= {} request_post = kwargs['request_post'] related_form = RelatedAddForm(request_post, prefix=self.prefix) related_form.prefix = self.prefix context['form'] = related_form if related_form.is_valid(): #some code else: #some code 2 #ERROR AssertionError: Cannot filter a query once a slice has been taken return context forms.py class ListTextWidget(forms.Select): template_name = 'include/_forms_clients_datalist.html' def format_value(self, value): if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class RelatedAddForm(forms.ModelForm): phone = ChoiceTxtField(queryset=Clients.objects.order_by('-phone')[:1]) # class Meta: model = Clients fields = ['name', 'phone'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'}), } include/_forms_clients_datalist.html {% block javascript %} <script> $(document).ready(function () { $('#ajax_phone_{{ widget.name }}').keyup(function () { // create an AJAX call $.ajax({ data: $(this).serialize(), // get the form data url: "{% url 'ajax_request' %}?related=clients&data={{ widget.name }}", // on success success: function (response) { if (response.is_exist == true) { $("#ajax-{{ widget.name }}").text(response.is_taken.name); var dataList = document.getElementById('{{ widget.name }}'); var input = document.getElementById('ajax_phone_{{ widget.name }}'); var request … -
Accessing nested field from Queryset in Django
so I have 4 models class User(models.Model): userID = models.CharField(pk = True) ...... class Producer(models.Model): userID = models.OneToOneField('Users.User',on_delete=CASCADE,primary_key=True) ..... class Buyer(models.Model): userID = models.OneToOneField('Users.User',on_delete=CASCADE,primary_key=True) ..... class Inventory(models.Model): item_id = models.UUIDField(primary_key=True,auto_created=True,default=uuid.uuid4) producerID = models.ForeignKey('Producers.Producer',on_delete=CASCADE) ..... class Cart(models.Model): userID = models.OneToOneField(Buyer, on_delete = CASCADE,primary_key = True) last_updated = models.DateTimeField(auto_now = True) class Cart_Item(models.Model): cart_item_id = models.UUIDField(primary_key=True,auto_created=True,default= uuid.uuid4) item_id = models.ForeignKey('Inventory.Inventory', on_delete= SET_NULL,null=True) userID = models.ForeignKey(Cart,on_delete=CASCADE) ...... I then have a post-only view which processes all cart Items in order to create an order as follows class PlaceOrderView(generics.CreateAPIView): def post(self, request, *args, **kwargs): user = request.user cart = Cart_Item.objects.select_for_update().filter(userID = user).order_by('item_id__producerID') order = {'producer':'', 'items': [] } for item in cart: if order['producer'] == item.values('item_id.producerID'): order['items'].append(item) else: self.placeOrder(order) order['producer'] = item.values('item_id.producerID') order['items'] = [] order['items'].append(item) def placeOrder(self,order): with transaction.atomic(): #Business logic on order. What Im trying to do is to group all cart Items by items owned by specific producers, and then place an order for that group of cart Items. Where I am having trouble is in accessing the nested field "producerID" of cart Item, which needs to be done in order to group all of my cart Items. My placeOrder method, uses the cartItem object and so they are passed directly … -
Passing values into nested for loops in django
I am getting hung up between tutorials and documentation for backwards relationships. I think my issue is that I'm not passing the right information from my view into the template, but I'm unsure how to address it. I want to be able to pass all of the "lift" values from the LiftSets object to thier specific Session. My for loop for Sessions (or total_workouts) is working, but I cannot get anything to populate the nested for. # views.py def workout(request): total_workouts = Session.objects.all() total_sets1 = LiftSet.objects.all() context = { 'total_workouts' : total_workouts, 'total_sets1' : total_sets1, } return render(request, 'blog/workout.html', context=context) # workout.html {% for workout in total_workouts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ workout.author }}</a> <small class="text-muted">{{ workout.date_posted|date:"F d Y" }}</small> </div> <h2><a class="article-title" href="">{{ workout.name }}</a></h2> <p class="article-content"> test {% for child in total_sets1.session_set.all %} {{ child.lift }} {% endfor %} </p> </div> </article> {% endfor %} Foreign key in LiftSet to associate to Session. class Session(models.Model): name = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class LiftSet(models.Model): lift_options = ( ('S', 'Squat'), ('B', 'Bench'), ('O', 'OHP'), ('R', 'Row'), ) lift = models.CharField( max_length=1, choices=lift_options, blank=True, default='m', help_text='What Lift', … -
how do we create server side templates with django
let's take the example of Fiverr to explain what is basically my question. When an offer is generated on Fiverr, they say today is 5% off and a pop/modal is seen. you press cross it closes. what I want to know is this an example of server-side templates? and how to get started with server-side templates with Django -
Django AND query using Q objects
Given I have a Product model and a one-to-many ProductTag model. class Product(models.Model): [...] class ProductTag(models.Model): product = models.ForeignKey(Product) tag_value = models.CharField() [...] If I have 3 products with some tags: ProductA [TagA] ProductB [TagB] ProductC [TagB/TagC] I want to dynamically query "products" with some tags. This query returns just "ProductA" (as expected). Product.objects.filter(Q(producttag__tag_value="TagA")) This query returns all 3 products (as expected). Product.objects.filter( Q(producttag__tag_value="TagA") | Q(producttag__tag_value="TagB") ) I would expect the following query to return just "ProductC" Product.objects.filter( Q(producttag__tag_value="TagB") & Q(producttag__tag_value="TagC") ) But I get an empty queryset. Why does query #3 not work? Using __in query also returns wrong results (as expected) Product.objects.filter(producttag__tag_value__in=["TagB", "TagC"]) The above query returns both ProductB / ProductC. -
How to integrate OpenCV webcam with Django and React?
I have a barcode reader which I implemented by using opensource Dynamsoft API and OpenCV. Now I need to integrate it with Django and display on my website in React. I have no idea how to do that, I tried passing the code to my views.py but don't know what I should do next. Here is my code for barcode reading: import cv2 from dbr import * import time reader = BarcodeReader() def text_results_callback_func(frame_id, t_results, user_data): print(frame_id) for result in t_results: text_result = TextResult(result) print("Barcode Format : ") print(text_result.barcode_format_string) print("Barcode Text : ") print(text_result.barcode_text) print("Exception : ") print(text_result.exception) print("-------------") def get_time(): localtime = time.localtime() capturetime = time.strftime("%Y%m%d%H%M%S", localtime) return capturetime def read_barcode(): video_width = 0 video_height = 0 vc = cv2.VideoCapture(0) video_width = vc.get(cv2.CAP_PROP_FRAME_WIDTH) video_height = vc.get(cv2.CAP_PROP_FRAME_HEIGHT) vc.set(3, video_width) vc.set(4, video_height) stride = 0 if vc.isOpened(): rval, frame = vc.read() stride = frame.strides[0] else: return windowName = "Barcode Reader" parameters = reader.init_frame_decoding_parameters() parameters.max_queue_length = 30 parameters.max_result_queue_length = 30 parameters.width = video_width parameters.height = video_height parameters.stride = stride parameters.image_pixel_format = EnumImagePixelFormat.IPF_RGB_888 parameters.region_top = 0 parameters.region_bottom = 100 parameters.region_left = 0 parameters.region_right = 100 parameters.region_measured_by_percentage = 1 parameters.threshold = 0.01 parameters.fps = 0 parameters.auto_filter = 1 reader.start_video_mode(parameters, text_results_callback_func) while True: cv2.imshow(windowName, frame) … -
How to Submit and Retrieve data in one view in Django?
I have a little confusion in my app. I have html page in which I have added one form (form data submitting) and one table (to display the submitted data). For which I have a view that submit and retrieve the data at the same time but unfortunately, data is successfully storing in the table but in retrieving time, it gives me the error which is mentioned below. Error NoReverseMatch at /staff/add_staff_type Reverse for 'student_profile' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['student/profile/(?P[0-9]+)$'] Views.py def add_staff_type(request): if request.method == 'POST': designation = request.POST.get('designation') salary = request.POST.get('salary') datetime = request.POST.get('datetime') add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime) add_staff_type.save() messages.info(request, "Staff type has been Added.") return redirect('add_staff_type') else: #fetching records from the database table display_staff_type = staff_type.objects.all() return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type}) urls.py urlpatterns = [ path("", views.index, name="index"), path("student/Add_Student", views.Add_Student, name="Add_Student"), path("student/display_students", views.Display_Student, name="display_students"), path("student/edit/<int:id>", views.student_edit, name="student_edit"), path("student/update/<int:id>", views.student_update, name="student_update"), path("student/profile/<int:id>", views.student_profile, name="student_profile"), path("student/delete/<int:id>", views.student_delete, name="student_delete"), #below url is for staff_type on which i am currently workin path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"), ] staff_type.html <div class="card"> <div class="card-header"> <h3 class="card-title">Add Staff Type</h3> </div> <!-- /.card-header --> <!-- form start --> <form class="needs-validation" action="add_staff_type" method="POST" enctype="multipart/form-data" novalidate > {% csrf_token %} <div class="card-body"> <div class="form-row"> … -
pass values from one form to another and save in django
i have 2 Forms , In the first form i want to put some values and then move to second form passing values from first form , add few values in second form and save all, so far what im saving is empty rows and is duplicated (using modals to display forms if that helps) forms.py class AddCityForm(forms.Form): duration = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=DURATION_CHOICES) country = forms.ChoiceField(widget=forms.RadioSelect(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=CITY_CHOICE) class AddCityFormSec(forms.ModelForm): something = forms.CharField(widget=forms.TextInput(attrs={ 'style': 'background-color: #FAF9F9', 'class': 'mb-3'})) class Meta: model = Cities exclude = ['city', 'duration', 'something'] views.py def add_city(request): data = dict() if request.method == 'POST': form = AddCityForm(request.POST) city = request.POST.get('country') duration = request.POST.get('duration') something = request.POST.get('something') if form.is_valid(): form = form.save(commit=False) form.city = city form.duration = duration form.something = something form = form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = AddCityForm() context = dict(form=form) data['html_form'] = render_to_string('cites/modal_1.html', context, request=request) return JsonResponse(data) def add_city_2(request): data = dict() if request.method == 'POST': form = AddCityFormSec(request.POST) city = request.POST.get('country') duration = request.POST.get('duration') something = request.POST.get('something') if form.is_valid(): form.city = city form.duration = duration form.something = something form = form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False …