Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect react with django channels?
I want to add chat to my react app and I am using DRF to build my apis want to know how is it possible to connect django channels to my react app -
How do I filter items by name and timestamp range in django?
I want to filter transactions by external id that fit in start and end date range. When I add dates within the range they don't show up. Here is my current code filtered_transactions = Transaction.objects.filter( organisation_id_from_partner=organisation_id, timestamp__range=[latest_transaction.timestamp, start_date] ) -
Django: Issue displaying updates for a MultipleChoiceField, template keeps displaying initial values
First post, apologies in advance for errors. My problem: I initialize my model fields from a proprietary db. These fields are displayed correctly in my template (I can see the html reflects the values in my proprietary db). I then change the initial selection options (for the MultiSelectField) in my template, and save these changed options to the Django db (verified its saved via the admin function) via post overloading in my views. My success_url is setup in urls.py to redisplay the same view. I have overloaded get_context_data in views to load the form data from the Django database, and to update context data with this loaded data, the idea being that when the templates redisplays, my form should now displays the from data loaded from the Django db (not the initial values). What's happening, though, is that the initial values seems to be displayed, as opposed to the changed values I have loaded from the Django db. I would really appreciate help wrt understanding why the template displays values other than what I have loaded from the Django db. my models.py: class LiquidAssetModel(models.Model): #Get my initial values from an external db unq_assets = Jnance_base_data_main.get_unq_assets() init_values = Jnance_base_data_main.get_liq_indexes() liq_dates = … -
How to filter queryset with custom function
I have the following models and I am trying to apply some filtering. Basically I have this player model that can have multiple Experiences, and I want to send on my query params xp that will receive a value in years, and my queryset should only retrieve the players with at least that amount of years of experience in total. The calc_player_experience method reads throw the players experience and calculates de amount of experience the player has and returns true or false if it meets the xp received on the query params. How do I apply a function to model.filter()? is that a thing? models.py class Player(BaseModel): name = models.CharField(_("name"), max_length=255, blank=True) class Experience(BaseModel): player = models.ForeignKey( "players.Player", on_delete=models.CASCADE ) team = models.CharField(_("team"), max_length=255) start_date = models.DateField(_("start_date"), null=True, blank=True) end_date = models.DateField(_("end_date"), null=True, blank=True) views.py class PlayersViewSet(viewsets.ModelViewSet): serializer_class = PlayerSerializer queryset = Player.objects.all() def get_queryset(self): """Filters the players to retrieve only those not archived and approved""" queryset = Player.objects.filter(is_approved=True, is_active=True) return apply_filters(self, queryset) def apply_filters(obj, queryset): """Apply filters to given queryset""" xp = dict(obj.request.GET).get("xp", []) if xp: queryset = queryset.filter(lambda player: obj.calc_player_experience(player,xp[0])) -
Docker-compose up with conda not working properly
Good afternoon. First of all, I'm very beginner in Docker and I have a ongoing project with Django+PostgreSQL. I have issue with running docker-compose up. First of all I was facing a error code 137. I went through the steps. I give docker more ram (was 2GB, I give it 4GB firstly and then expand to 8GB). Here is SO thread for this error Error was solved, but now I'm facing infinity loading on this steps. ' => [3/5] RUN conda install -y --file /conda_files/requirements.txt -c conda-forge -c anaconda ' It can be going for 2000secs+ Here is my Dockerfile FROM conda/miniconda3 COPY requirements.txt /conda_files/requirements.txt RUN conda install -y --file /conda_files/requirements.txt -c conda- forge -c anaconda RUN pip install requests-html==0.10.0 COPY . /app/ref_wallet ENV PYTHONPATH "${PYTHONPATH}:/app/ref_wallet" Here is my docker-compose.yml version: '3.7' services: web: build: . command: python /app/current/manage.py runserver 0.0.0.0:80 volumes: - .:/app/current/ ports: - 8082:80 The most strange thing. That my colleague can run this code on his Windows PC. And I'm on my MacBook can not. Any ideas of why it's happening and how I can solve it? Cause currently I don't receive any errors. It's just infinity loading for me now. -
How can I show a HTML but not in string?
I'm working with Django. I save text and images with a HTML editor to show it in another HTML file with format, but it shows only text. I write all description with: <div class="col-sm-6"> <div class="form-group"> <label for="{{mails_form.subject.label}}">{{mails_form.subject.label}}</label> {{mails_form.subject}} </div> </div> Then I save the content with description = send_mails.description in the view. And in another HTML file I show: <tr> <td class="content-block"> <strong>{{description}}</strong> </td> </tr> But it just shows this: https://i.stack.imgur.com/zmU2E.png (I wrote a little text and included an image) I don't want to show only the text, I want to show it in HTML format, not write the tags, but use them. -
django-rest-framework override get_queryset and pass additional data to serializer along queryset
This is a toy example of the problem that I am facing. For some reason, I am unable to pass the expected data to my serializer and that is raising the following error. AttributeError at /my-end-point/ Got AttributeError when attempting to get a value for field main_data on serializer ParentSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'main_data'. class MainModelSerializer(serializers.ModelSerializer): class Meta: model = MainModel class ParentSerializer(serializers.Serializer): main_data = MainModelSerializer(many=True) extra_data = serializers.FloatField() class View(ListCreateAPIView): serializer = ParentSerializer def get_queryset(self): # extra_data would have some calculated value which would be a float extra_data = some_calculated_value() queryset = MainModel.objects.filter(some filters) return { 'main_data': queryset, 'extra_data': extra_data } # expected data that is passed to the ParentSerializer # { # 'main_data': queryset, # 'extra_data': extra_data # } -
Redirecting a user to checkout page in Django
I want to redirect a user to checkout page that is automatically generated by the payment gateway. Anytime a user submits a request, the payment gateway returns a response in the format below. What i want to do is redirect the user to the checkout page to make payment. "status": true, "message": "Authorization URL created", "data": { "authorization_url": "https://checkout.paystack.com/eddno1f6rf411p0", "access_code": "eddno1f6rf411p0", "reference": "bpozkels2v" def paystack(request): url = 'https://api.paystack.co/transaction/initialize' transaction_id = random.randint(100000000000, 999999999999) data = { "key": "PUBLIC_KEY", "ref": transaction_id, "amount": "000000000100", "callback": f"http://127.0.0.1:8000", "email": "email@me.com", } headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer SECRET_KEY', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers) response_data = res.json() print(response_data["authorization_url"]) redirect(response_data["authorization_url"]) The error i get is KeyError at /paystack 'authorization_url' -
SSL certificates and https for AWS hosted django site
I have a django site hosted on elastic beanstalk. I have obtained a AWS SSL certificate and this has been associated with the load balancer 443 HTTPS port. In my config file I have: MIDDLEWARE = [ ... "django.middleware.csrf.CsrfViewMiddleware", ] CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = True With this setup I am able to login to the site but the browser displays 'not secure' in the address bar, and if I prepend 'https://' to the urls I get a page stating the connection is not private. If I add SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Then it becomes impossible to login (the login page just reloads) or if I got to a incognito browser I get a 'CSRF verification failed. Request aborted.' message. It may be related but I am also receiving emails stating 'Invalid HTTP_HOST header: ’52.XX.X.XXX’. You may need to add ’52.XX.X.XXX’ to ALLOWED_HOSTS. The ip address relates to one of the ec2 instances running the site but my understanding was that only the address for the elastic beanstalk environment and my domain name needed to be added here. Apologies for the log question, I've just tried to include ay detail that may be relevant -
How do I get the an object by name and highest timestamp
I want to fetch the transaction belonging to external_id=1 and has the highest timestamp. I have tried this max_rating = Transaction.objects.aggregate(organisation_id_from_partner=organisation_id, highest_timestamp=Max('timestamp')) But I get TypeError: QuerySet.aggregate() received non-expression(s): 1. -
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) };