Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass function from view.py to html in Django
[ https://i.stack.imgur.com/CSAOj.png][1] [https://i.stack.imgur.com/T0qUJ.png][2] I'm currently working on a sort objects by price function, utilizing Django built in order_by functionality. I believe I have created the function in views.py but don't know how to code in html. How do I pass these values into a html format that would allow the sort functionality to be visible on the webapp? -
htmx: hx-redirect: working locally but not in production
This question is related to this one: htmx: hx-target: swap html vs full page reload I have this function in order to switch from swapping only the targeted area to trigger a full-page redirect by the server: class HTTPResponseHXRedirect(HttpResponseRedirect): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self['HX-Redirect']=self['Location'] status_code = 200 In my view function this class is used this way: return HTTPResponseHXRedirect(redirect_to=reverse('new_page')) The form is a regular htmx/django form: <div id="myform"> <form novalidate> {% csrf_token %} .. some form inputs... <button type="submit" hx-post="/swap_area/" hx-swap="outerHTML" hx-target="#myform">Submit</button> </form> </div> This works locally fine, but in production it does not work. The full page is loaded in the area of the form. Any ideas? Maybe it has todo with https instead of http? -
How to save a dataframe as csv file in filefield
I am trying to save a dataframe as a csv file in a model's filefield but it is not saving it correctly, please tell what I am doing wrong?? new_df = df.to_csv(columns=['A', 'B'], index=False) doc.csvfile.save(f'{doc.id}.csv', ContentFile(new_df)) -
How to add Social login to Saleor.io? Django and graphQL
I'm trying to add social login to Saleor but importantly I can't get the result I want. Social authentication to user account, using graphql API, I have already used https://github.com/saleor/saleor/issues/5228 guy method and currently I'm using it but I get Cannot query field "oauthTokenCreate" on type "Mutation" error here are my codes in graphql/account/mutations/social_auth.py import graphene import logging import django.conf as conf from functools import wraps from django.utils.translation import ugettext as _ from promise import Promise, is_thenable from django.dispatch import Signal from graphql_jwt.exceptions import JSONWebTokenError from graphql_jwt.mixins import ResolveMixin, ObtainJSONWebTokenMixin from graphql_jwt.decorators import setup_jwt_cookie from graphql_jwt.settings import jwt_settings from graphql_jwt.shortcuts import get_token from graphql_jwt.refresh_token.shortcuts import refresh_token_lazy from social_django.utils import load_strategy, load_backend from social_django.compat import reverse from ...account.types import User from ...core.types import Error from ...shop.types import AuthorizationKeyType from ....site.models import AuthorizationKey logger = logging.getLogger(__name__) token_issued = Signal(providing_args=['request', 'user']) def token_auth(f): @wraps(f) @setup_jwt_cookie def wrapper(cls, root, info, **kwargs): context = info.context context._jwt_token_auth = True def on_resolve(values): user, payload = values payload.token = get_token(user, context) if jwt_settings.JWT_LONG_RUNNING_REFRESH_TOKEN: payload.refresh_token = refresh_token_lazy(user) return payload token = kwargs.get('access_token') backend = kwargs.get('backend') if not hasattr(conf.settings, 'SOCIAL_AUTH_FACEBOOK_KEY') or not hasattr(conf.settings, 'SOCIAL_AUTH_FACEBOOK_SECRET'): authorization_key = AuthorizationKey.objects.get(name=backend) conf.settings.SOCIAL_AUTH_FACEBOOK_KEY = authorization_key.key conf.settings.SOCIAL_AUTH_FACEBOOK_SECRET = authorization_key.password context.social_strategy = load_strategy(context) # backward compatibility in … -
How to djanog orm filter reverse foreign key
When I use django, I created two models. class GroupModel(models.Model): group_name = models.CharField(max_length=2, null=False, default="A") class MemberModel(models.Model): name = models.CharField(max_length=8, null=False, default="") group = models.ForeignKey( to=GroupModel, on_delete=models.CASCADE, related_name="members", db_column="member", ) isActive = models.BooleanField(null=False, default=False) The contents lisk: [{'group_name': 'GROUP_A', 'id': 1, 'members': [{'isActive': False, 'name': 'j'}, {'isActive': True, 'name': 'b'}, {'isActive': True, 'name': 'y'}]}, {'group_name': 'GROUP_B', 'id': 2, 'members': [{'isActive': True, 'name': 'f'}, {'isActive': True, 'name': 'i'}, {'isActive': True, 'name': 'y'}]}] Now, I want to get the queryset wiht isActive=False queryset = GroupModel.objects.filter(members__isActive=True).distinct() but the resutl is [{'group_name': 'GROUP_A', 'id': 1, 'members': [{'isActive': False, 'name': 'j'}, {'isActive': True, 'name': 'b'}, {'isActive': True, 'name': 'y'}]}] How I can get the expected result list [{'group_name': 'GROUP_A', 'id': 1, 'members': [{'isActive': False, 'name': 'j'}]}] -
AttributeError: module ' ' has no attribute 'Command'
In my Django project ,there is a file(module) which is used to load csv data. project/apps/patients/management/commands/load_patient_data.py Inside the file(module): import psycopg2 import csv conn = psycopg2.connect(host='localhost', dbname='patientdb',user='username',password='password',port='') cur = conn.cursor() with open(r'apps/patients/management/commands/events.csv') as csvfile: spamreader = csv.DictReader(csvfile, delimiter=',' ,quotechar=' ') for row in spamreader: cur.execute(f"""INSERT INTO patients_event (patient_id, event_type_id , event_value ,event_unit, event_time) VALUES ('{row['PATIENT ID']}','{row['EVENT TYPE']}','{row['EVENT VALUE']}', '{row['EVENT UNIT']}','{row['EVENT TIME']}')""") conn.commit() When I run: python manage.py load_patient_data Error: AttributeError: module 'apps.patients.management.commands.load_patient_data' has no attribute 'Command' Any friend can help? -
how can I handle more than 1 billion data in sqlite3?
I join this site now to get answer about my problem Now, as I am a django developer, I have only one thing to question to yours on developing finance API, our customer demand to me about 1 billion data handling. So, I find "Indexes", "Vacuum", "redis" to solve my problem. Now, I want to get the better way from yours what is the better method among 3things? (customer request to me that we should finish within 5 hours.. If I can't find better way or solve the demand, I tell them that I need more times) Can I get another way to solve problem? -
Login using Facebook user not created
I am using Facebook for developers in my Django project. When I tested the project locally user gets created in DB and automatically logged in after redirecting from Facebook. But when I shift in production and made the app live on Facebook for developers, when I logged in it will redirect me to my homepage but the user was not created in DB. My Facebook Developers Settings:-- facebook-login > settings -- validte oauth URLs -- xyz.com/oauth/complete/facebook/ and in setting >Basic -- domain is xyz.com -
Django models.TextChoices is not-indexable?
I made project with django and I applied type-hinting by using pytype. But pytype gives me type-error like this type_test.py", line 11, in <module>: class ReportCategoryChoices is not indexable [not-indexable] ('ReportCategoryChoices' does not subclass Generic) For more details, see https://google.github.io/pytype/errors.html#not-indexable ninja: build stopped: subcommand failed. type_test.py category = ReportCategoryChoices['A'] and here is the ReportCategoryClass class ReportCategoryChoices(models.TextChoices): A = "A", _("a") B = "B", _("b") C = "C", _("c") # type of ReportCategoryChoices: <class 'django.db.models.enums.ChoicesMeta'> in django ReportCategoryClass is Indexable. why did pytype say ReportCategory is not indexable? -
unsupported operand type(s) for /: 'Vat' and 'int'
been searching and i cant find a proper solutions I have issue calculating Vat amount from 2 values in Django models. first the VAT model is like this class Vat(models.Model): vat_name = models.CharField(max_length=200) vat_value = models.IntegerField() def __str__(self): return str(self.vat_value) then I have the Statement model as below class Statement(models.Model): sales_invoice = models.IntegerField(blank=True, null=True) vat_value = models.ForeignKey(Vat, on_delete=models.CASCADE, blank=True, null=True) amount_in = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) def vat_amt_in(self): if self.amount_in and self.vat_value : vat_amt_in = (self.vat_value/100)*self.amount_in else: return None so after this I get the Error unsupported operand type(s) for /: 'Vat' and 'int' anyone can help with this for me to get the correct vat amount like if vat_value = 21 and amount_in =50 then vat_amt_in =10,50 -
como puedo listar imágenes en un proyecto de Django sin usar los modelos, solo quiero usar SQL puro
Buen día estoy haciendo un proyecto de Django pero no quiero usar los modelos de Django quiero usar SQL puro pero ahora intentando hacer un catalogo me di cuenta que no se como listar las imágenes lo que quiero es que en el servidor se guarde una copia de la imagen y que se guarde el nombre de dicha imagen y luego pueda acceder a las imágenes busco en el directorio donde se encuentren las imágenes y así buscar las imágenes que existen en la base de datos No se si habrá alguna manera por favor alguien me podría ayudar -
Why is myproject.wsgi missing from django project? [duplicate]
I created a project with django but the myproject.wsgi file is missing. I have located a wsgi.py file, though. Can anyone tell me what I should do? I'm done developing my server and would like to deploy it. -
Which part of Django applicated request.user.is_authenticated is made true?
I want to restrict multiple logins for which i want to access request.user.is_authenticated attribute , i tried to access this attribute in the middlewares in the response cycle when login view call has been made but still in both the cycles like from request to response and back this attricute is false , so needs help -
Allow users to draw and save their own maps in django
I want to give users the ability to draw boundaries on Google maps (or similar) within my Django website. The purpose will be to identify certain areas (farm boundaries, suburb boundaries, plot boundaries etc.), and add some custom fields such as size, crop, owner etc. to those polygons or vectors. Are there any apps available that can be integrated into Django? Most of the ones I could find needs an import from 3rd party applications or files (kml or shp). I want to give users the ability to draw those boundaries within my website. Thanks in advance. -
How to call a Python function with vanilla Javascript in a Django app
I am working on a Django app and I am trying to call a Python function in views.py on a button click. I am trying to call this function using vanilla JavaScript if possible, because I am very unfamiliar with JavaScript and would like to try to keep things simple. The idea would be to display the text returned by the hello() function by using JavaScript to create a new div after the button is clicked. I believe I can do that part, but I have not been able to find any information on calling the Python function. I have the JavaScript function alerting with the text for now. Here is a sample of my code so far: ./views.py def hello(): return "Hello world" ./static/index.js document.getElementById('button').addEventListener('click', printHello); function printHello() { var text = // call Python function alert(text) }; -
Django ORM: difference in days multiplied by field
I have a database table that represents expenses associated with a given product. These expenses, given that they're daily, have a from_date (the date in which they started) and to_date (the date in which they ended). to_date can be null, as these expenses might still be going. Given 2 Python datetimes, start_date and end_date, I need to produce in the ORM the total spent in the period for my_product. >>> start_date datetime.datetime(2021, 8, 20, 0, 0) >>> end_date datetime.datetime(2021, 9, 21, 0, 0) In this case, the expected output should be: (-104 * (days between 08/20 and 08/25)) + (-113 * (days between 08/26 and 09/21) This is what I've got so far: ( my_product.income_streams .values("product") .filter(type=IncomeStream.Types.DAILY_EXPENSE) .filter(add_to_commission_basis=True) .annotate(period_expenses=Case( When(Q(from_date__lte=start_date) & Q(to_date__lte=end_date), then=ExpressionWrapper( start_date - F('to_date'), output_field=IntegerField())) ), # Other When cases... ) ) # Sum all period_expenses results and you've got the solution And this is what's giving me problems: then=ExpressionWrapper( start_date - F('to_date'), output_field=IntegerField()) This expression always returns 0. Apparently start_date - F('to_date') is not the same as "give me the difference in days between these 2 dates". You'd acomplish this in Python with timedelta. What's the equivalent in the ORM? I've tried with ExtractDay: then=ExpressionWrapper( ExtractDay(start_date - … -
Django createsuperuser error No Django settings specified
I'm trying to create a super user with the command python3 manage.py createsuperuser from the terminal in VS Code and get the error: No Django settings specified. Unknown command: 'createsuperuser' Type 'manage.py help' for usage. -
Using optional **kwargs in python
I am in process of refactoring a codebase in Python where I am still learning their syntactical sugar so hopefully I can get some help from the experts here. I want to write a generic function that takes list of optional arguments using **kwargs and makes a call to DB model using the list of arguments present. So for eg 5 out of 8 column entries are present in the function call, make a create call using those 5 (rest 3 are already accept null in DB). However if I send 7 values in function, I should be able to use the same function again. So here is something I am thinking of : Controller Class .... create(arg1=x, arg3=y, arg4=z, arg6=a, arg7=b) create(arg1=x, arg2=x2, arg3=y, arg4=z, arg6=a, arg7=b, arg8=b2) .... Model Class arg1 = models.CharField(max_length=255, null=True, blank=True) arg2 = models.CharField(max_length=255, null=True, blank=True) arg3 = models.DateTimeField(null=True, blank=True) arg4 = models.DateTimeField(null=True, blank=True) arg5 = models.CharField(max_length=255, blank=True, null=True) arg6 = models.CharField(max_length=255, blank=True, null=True) arg7 = models.CharField(max_length=255, blank=True, null=True) arg8 = models.BooleanField(null=True, blank=True) def create(**kwargs): DBMODEL.objects.create( arg1=kwargs['arg1'], arg2=kwargs['arg2'], arg3=kwargs['arg3'], arg4=kwargs['arg4'], arg5=kwargs['arg5'], arg6=kwargs['arg6'], arg7=kwargs['arg7'], arg8=kwargs['arg8'] ) Is that something which can be done using my code above or if there is any other suggestion? End … -
Unable to populate select option from database in Django
I am a beginner to Django and unable to populate the items from my database table to <option></option>. From models.py: from django.db import models from django.db.models.fields.related import ForeignKey # Create your models here. class Tbl_Category(models.Model): cat_Id = models.AutoField(primary_key=True) cat_Name = models.CharField(max_length=20, unique=True) # def __str__(self): # return [self.cat_Id, self.cat_Name] class Tbl_Item(models.Model): item_Id = models.AutoField(primary_key=True) item_Name = models.CharField(max_length=30, unique=True) cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE) item_Price = models.IntegerField() From views.py: from django.shortcuts import render from orderapp.models import Tbl_Item # Create your views here. def displayMain(request): return render(request,'index.html') def ct(request): options = Tbl_Item.objects.filter(cat_Idf=1) context = {'alloptions' : options} return render(request, 'index.html', context) From index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css.css' %}"> <title>DATA COLLECTION</title> </head> <body> <div class="container"> <div class="order-screen"> <div class="element"> <label for="coffee-tea">Coffee-Tea</label> <select name="coffee-tea" id="coffee-tea"> {% for opt in alloptions %} <option value="{{opt.item_Id}}">{{opt.item_Name}}</option> {% endfor %} </select> </div> <div class="cart-screen">CART-SCREEN</div> </div> </body> </html> I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you. -
type object 'Post' has no attribute 'filter'
Every time I attempt to write a comment on a post, I get an AttirbuteError at the post number. e.g- 'AttributeError at /post/54/', and below this it says 'type object 'Post' has no attribute 'filter''. It then directs me to my views.py line 58, which reads: post = self.get_object(Post). It is a part of my PostDetailClass: class PostDetailView(DetailView): model = Post form = CommentForm def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = self.get_object(Post) form.instance. user = request.user form.instance.post = post reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) reply = comment_qs, reply=None form.save() form.save_m2m() return redirect(reverse("post", kwargs={ 'content': Post.content })) Can anyone point out what is wrong with my code? Thank you. -
Django SortedManyToManyField does not save order in reverse relation
I am using the SortedManyToManyField field from django-sortedm2m as in the following in my models: import uuid from django.db import models from sortedm2m.fields import SortedManyToManyField class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parent = models.ForeignKey( to="self", on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories", ) name = models.CharField(max_length=250) class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) categories = SortedManyToManyField(to=Category, blank=True, related_name="product_items") Now, lets create and add some data to both the fields: # create some categories c1 = Category.object.create(name="C1") c2 = Category.object.create(name="C2") c3 = Category.object.create(name="C3") # create some products p1 = Product.object.create(name="P1") p2 = Product.object.create(name="P2") p3 = Product.object.create(name="P3") # add categories to product P1 p1.categories.add(c1, c2, c3) # add products to category C1 c1.product_items.add(p1, p2, p3) Now, what happens is that the categories are inserted and retrieved in the correct order, where as products added to product_items are not. When I checked the underlying class type of the field p1.categories, it says that its <class 'sortedm2m.fields.create_sorted_many_related_manager.<locals>.SortedRelatedManager'> where as when I do the same for the reverse relation (product_items) it says <class 'django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager'> Does this mean that the order is saved explicitly for the field that defines the SortedManyToManyField field and not the related_name/ reverse relation? Do I have to explicitly define the … -
Adding data to linked table from link on page
Within my Django application, I have two models: Event and Game The Event model has a ForeignKey to the Game model. I have a page that lists all the games using a {% for game in game_list %}, and I'm trying to create a button that will take me to the Events Form to allow me to add an event to the game. The event form only has 3 fields. project , event_name and event_date. When you land on the event form page I'd like to have the project name populated with the game name from the previous page. But when I create the link to form my page breaks. Im using: <a class="dropdown-item" href="{% url 'add-event' game.id %}">Add Key Event</a> to take to the event form. Models class Event(models.Model): project = models.ForeignKey(Game, to_field='project_name', on_delete=models.CASCADE) event_name = models.CharField(max_length=20) event_date = models.DateTimeField(blank=True, null=True) def __str__(self): return str(self.event_name) class Game(models.Model): project_name = models.CharField(max_length=255, blank=False, unique=True) project_website = models.URLField(max_length=255, blank=True) project_description = models.TextField(blank=True) def __str__(self): return str(self.project_name) View def add_event(request,game_id): event = Event.objects.get(pk=game_id) form = addEventForm(request.POST or None, instance=event) return render(request, 'pages/add_event.html', {'event': event, "form" : form}) URL path('add_event/<game_id>', view=add_event, name="add-event"), Error DoesNotExist at /apps/add_event/13 Event matching query does not exist. Request Method: … -
Django Unique together With abstract class inheritance
I have two models class BaseModel(models.Model): class Meta: abstract = True created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) obj_status = models.BooleanField(default=True, null=True) and class Client(BaseModel): class Meta: unique_together = ( ('obj_status', 'document') ) document = models.IntegerField() But when a try to run makemigration a recieve HINT: This issue may be caused by multi-table inheritance. How can I resolve this problem without write obj_status in every model that I have? -
Django Products model for e-commerce site
I am trying to build a sample e-commerce site with Django and I am trying to figure out as to how can I model the relationship between a product having multiple sizes and each of those sizes having their individual stocks this my products/products varied models: from django.db import models from colorfield.fields import ColorField # Create your models here. class Color(models.Model): Color = models.CharField(max_length=120,null=True,blank=True) value = ColorField(default='#FF0000') def __str__(self): return self.Color class Size(models.Model): Size = models.CharField(max_length=120,null=True,blank=True) def __str__(self): return self.Size class Product(models.Model): title = models.CharField(max_length=120,null=True,blank=True) def __str__(self): return self.title class ProductVaraiant(models.Model): product =models.ForeignKey(Product,on_delete=models.CASCADE,null=True,blank=True) slug = models.CharField(max_length=120,null=True,blank=True) Color = models.ForeignKey(Color,on_delete=models.CASCADE,null=True,blank=True,) Size = models.ManyToManyField(Size) def __str__(self): return self.slug -
Django , linking three models
I have a question. I have a Bb model that includes the rubric and sub_rubric parameters. There are also Rubric and Sub_rubric models, one-to-many related. Question: how to link rubric and sub_rubric to each other in the Bb model, so that when a new instance of the Bb model is created, when the rubric changes, the subrubruc list changes too. Code: class Rubric(models.Model): name = models.CharField(max_length=50, db_index=True) class Sub_Rubric(models.Model): rubric = models.ForeignKey(Rubric, null=True, on_delete = models.PROTECT) name = models.CharField(max_length=50, db_index=True, unique = True) class Bb(models.Model): title = models.CharField(max_length=50) content = models.TextField(null=True, blank=True) price = models.FloatField(null=True,blank=True) published = models.DateTimeField(auto_now_add=True, db_index=True, ) rubric = models.ForeignKey(Rubric, null=True, on_delete = models.PROTECT, related_name='name') sub_rubric = models.ForeignKey(Sub_Rubric, null=True, on_delete = models.PROTECT)