Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I override __str__ in models.py?
Apologies if this is a silly question, I am pretty new to python and django. I am following along with a django tutorial, and we are creating a fake movie site that lists movies by genre, title, etc. I am currently trying to override the __str__ function in the models.py file, so rather than displaying Genre (1), it displays the actual genre (ex. "Action"). Here's how my models.py looks currently: from tkinter import CASCADE from django.db import models from django.utils import timezone # Create your models here. class Genre(models.Model): name = models.CharField(max_length=255) def __str__ (self): return self.name class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) However, vscode is underlining the def __str__ (self): When I hover over it, it tells me: str does not return str pylint(E0307: invalid -str- returned I tried looking at other solutions, but I could not find one that seemed to match my scenario, so I do apologize if this has been solved elsewhere, and I am too incompetent to understand the problem. Thanks for your patience! -
In django, views here i ran into a problem that my varible called created{"created" is not accessed} so plz see my code and tell me answer
I am just showing my views.py because problem is just here after at third line after order. def cart(request): customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() context = {'items':items} return render(request, 'store/cart.html', context) Here ,i also dont know that why we use a word like created, what is its purpose.Thanks. Blockquote -
Link Customer Django user to group and give them permission
I customized the Django user model, now I can't link my users to Django groups to give them permissions from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db.models.signals import post_save from django.contrib.auth.models import Group USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$' class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) if group is not None: group.user_set.add(user) return user # user.password = password # bad - do not do this def create_superuser(self, username, email, password=None): user = self.create_user(username, email, password=password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) if group is not None: group.user_set.add(user) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=300, validators=[ RegexValidator(regex=USERNAME_REGEX, message='Username must be alphanumeric or contain numbers', code='invalid_username')], unique=True) email = models.EmailField(max_length=255, unique=True, verbose_name='email address') is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username def get_short_name(self): # The user is identified by their email address return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to … -
DJANGO REST + DJOSER /api/auth/users/activation get invalid user or token wrong error
I should create a auth get method, but /auth/users/activation get error { "uid": [ "Invalid user id or user doesn't exist." ] } This error appeared after errors like "this token not valid for this user". In email userid field is string like "MTE", "Mw"... User activation signal not working Djoser params DJOSER = { "LOGIN_FIELD": "email", "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, 'PASSWORD_RESET_CONFIRM_URL': 'api/users/users/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'api/users/users/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'api/users/users/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { "user_create": "restapi.app.serializers.RegistrationSerializer", "user": "restapi.app.serializers.UserSerializer", "current_user": "restapi.app.serializers.UserSerializer" }, 'PERMISSIONS': { 'user_list': ['rest_framework.permissions.AllowAny'], } } restapi/app/serializers.py from rest_framework import serializers from restapi.app.models import * from .docs import * from django.contrib.auth.models import User class PioneerProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PioneerProfile fields = ["elo", "max_elo", "min_elo"] class UserSerializer(serializers.HyperlinkedModelSerializer): description = serializers.CharField(source="profile.description") pioneer = PioneerProfileSerializer() class Meta: model = User fields = ["id", "username", "first_name", "last_name", "description", "email", "date_joined", "pioneer"] class RegistrationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["email", "username", "first_name", "last_name", "email", "password"] def validate_username(self, value): check_query = Genre.objects.filter(name=value) if self.instance: check_query = check_query.exclude(pk=self.instance.pk) if self.parent is not None and self.parent.instance is not None: genre = getattr(self.parent.instance, self.field_name) check_query = check_query.exclude(pk=genre.pk) if check_query.exists(): raise serializers.ValidationError('A Genre with this name already exists.') return value restapi/app/signal.py from django.dispatch import receiver from djoser.signals import user_activated from .models … -
Django:no module named app_name
I am watching a djano rest framework tutorial, and I am doing the same but ,I don't know why it gives 'No module named 'api' error', I included app in settings, and tried many things on internet so far but it did not work. What is the reason for that error? I have always worked like that with no problem. urls.py from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path, include from api import views urlpatterns = [ path('admin/', admin.site.urls), path('api/',views.api_home) ] views.py from django.http import JsonResponse from django.shortcuts import render def api_home(request): return JsonResponse({'message':'it is your json response'}); settings.py """ Django settings for cfehome project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-x9upz#&nqh!m=^rb^ozgrbi=!6*3t$3ucml^0c@s^^fjb=dp-j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
update a field in all records of a table through a single form Django 4
I have the following model 'ARTICULO', which I have created and templates to edit it individually # MODEL class Articulo(models.Model): id = models.AutoField(primary_key=True, verbose_name='codigo') nombre = models.CharField(max_length=100, verbose_name='nombre elemento') cantidad = models.PositiveSmallIntegerField(verbose_name='cantidad total') cantidad_disponible = models.PositiveSmallIntegerField(verbose_name='cantidad disponible', default=5) UNIDAD = 'und' KILO = 'kg' LITRO = 'L' UNIDADES_BASE = [ (UNIDAD, 'unidades'), (KILO, 'Kilogramos'), (LITRO, 'litros'), ] unidades = models.CharField(max_length=3, choices=UNIDADES_BASE, default=UNIDAD, verbose_name='unidad base') area = models.CharField(max_length=100, verbose_name='tipo inventario', default='primaria') persona_asignada = models.CharField(max_length=100, default='almacen', verbose_name='persona asignada') def __str__(self): trama = "articulo: " + self.nombre return trama #form to edit individually class ArticuloEditarForm(forms.ModelForm): class Meta: model = Articulo fields = ['nombre', 'cantidad', 'unidades'] # view for generate form of individual article def editar(request, id): articulo = Articulo.objects.get(id=id) formulario = ArticuloEditarForm(request.POST or None, instance=articulo) if formulario.is_valid() and request.POST: formulario.save() return redirect('inventario_inicio') return render(request, 'inventario/editar.html', {'formulario': formulario}) but additionally I would like to create a page where I can perform an update of all the records of the table as a whole (as in the following image) When clicking on the button, all records with the checkbox activated are updated in the database according to the value indicated in their text box. From what I have investigated so far, I think I understand … -
Using django channels, graphene, DjangoChannelsGraphqlWs, cant get loggedin user info in subscriptions
Im building a simple chat application losely based on kimutaiRop implementation, using Django channels and graphene using DjangoChannelsGraphqlWs, for logging in im using social_django Problem being in all queries and mutations I am getting current logged in users info in the info variable. But in subscription i am unable to get current logged in user info. It is working on site, when logged into django, but on https://studio.apollographql.com/ using authorization token, signed in with google, the subscription function does not have any info on the current logged in user. this is my schema.py file. User = get_user_model() class ChatUserType(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = User fields = ["last_name", "first_name",'username', "email", "id", "isOnline"] interfaces = (relay.Node,) class MessageFilter(FilterSet): class Meta: model = Message fields = ("content", "read", 'timestamp',) order_by = ('timestamp', "id") class MessageType(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = Message fields = '__all__' interfaces = (relay.Node,) class RoomType(DjangoObjectType): id = graphene.ID(source='pk', required=True) unread = graphene.String() class Meta: model = Room fields = '__all__' interfaces = (relay.Node,) class Query(MeQuery, graphene.ObjectType): messages = DjangoFilterConnectionField( MessageType, filterset_class=MessageFilter, id=graphene.ID()) @staticmethod def resolve_messages(cls, info, id, **kwargs): user = info.context.user if user is None or not user.is_authenticated: raise Exception("You need to … -
Django: How to download a file on client after an Ajax request
I have a django app where users can save their contacts. I am not building a flow to allow users to download their contacts locally. To do so, I built a CTA ("download") that if clicked Gets the id of the contact selected Triggers an Ajax request to my views In the view I get the contact id, retrieve the data from my DB and create a VCF card out of it. (A contact card - basically a text file) Now I would like to have such file downloaded on the client's machine but I don't know how to do it. I managed to do it if I redirect to a new url where the view does exactly what my view below does, I want to allow users to download the file without being redirected to a new page. Also, trying to avoid storing the contact ids in the URL. That's why I am trying to use ajax but I think that's creating problems because and Ajax request waits JsonReponse from the view. I tried both a GET or POST but it's not working. This is my view currently: def get(self, request, *args, **kwargs): #Get the ids ids = request.GET.getlist('contact_ids[]') … -
How do I get the name of the container to show instead of the id?
So I am trying to figure out how to display the ForeignKey name in the view I have thought about using map method and get the object from the ID and getting the name from said ID, but that doesn't seem to work. I could be doing it wrong but I am not quite sure. JSON Response [ { "id": 3, "name": "Coke", "description": "Cocaine Drink", "container": 3 }, { "id": 4, "name": "Another One", "description": "Dj Khaled Drink", "container": 3 }, { "id": 5, "name": "Testy", "description": "Westy", "container": 4 } ] View class ListDrinks(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): drinks = Drink.objects.all() serializer = DrinkSerializer(map(DrinksId, drinks), many=True) return Response(serializer.data) def post(self, request, format=None): serializer = DrinkSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Models class Container(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Drink(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) container = models.ForeignKey( Container, on_delete=models.CASCADE, null=True) def __str__(self): return self.name -
how do I add an item to the cart without the page reloading?
So I wanna add an item to the cart without the page reloading every time, I've used ajax in a previous project and the response time wasn't pretty, so is there a better way to go about this, that won't be slow? if so, how would I fix this? also not the best with javascript so if u can explain stuff a bit, I would really appreciate your help, thx! link to the rest main code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 template: {% load static %} <link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < … -
How to have associated models to be directly linked to a ModelAdmin in the admin panel?
how do I make it better for the website operator to process the order, can we have each orderitem and shippingaddress associated with the order to be under each "Order" in the admin panel? for example when someone clicks on an Order, he sees the Order data and he's able to scroll and also see the orderitem, and shipping address, would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) date_added = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=40, choices=STATUS_CHOICES, default="Order Placed") tracking_no = models.CharField(max_length=300, null=True, blank=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=300) zipcode = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) what it looks like rn: admin.py admin.site.register(Order, OrderAdmin) admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(ShippingAddress, ShippingAddressAdmin) -
Django Gitlab CI/CD Problem with WEB_IMAGE=$IMAGE:web
I am new to Gitlab CI/CD. I have a django project running on my local machine in docker. I want to configure Gitlab CI/CD with my django project (database is postgres, proxy server is nginx). Here are my config files. .env DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] DATABASE=postgres SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=foo SQL_USER=foo SQL_PASSWORD=foo SQL_HOST=db SQL_PORT=5432 POSTGRES_USER=pos POSTGRES_PASSWORD=123456 POSTGRES_DB=foo Dockerfile: FROM python:3.9.6-alpine ENV HOME=/web ENV APP_HOME=/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles WORKDIR $APP_HOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /web/entrypoint.sh RUN chmod +x /web/entrypoint.sh COPY . /web/ RUN python manage.py collectstatic --no-input --clear ENTRYPOINT ["/web/entrypoint.sh"] docker-compose.yml version: '3.8' services: web: build: . command: gunicorn pos.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/web/ - static_volume:/web/staticfiles ports: - 8000:8000 env_file: - ./.env db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env nginx: build: ./nginx ports: - 1337:80 volumes: - static_volume:/web/staticfiles depends_on: - web volumes: postgres_data: static_volume: entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py … -
Using Header Referer risk to hold needed values for endpoint
I want to use the header referer to communicate between Authenticated URLs in my app. Normally the end point URLs comes like this: appsite.com/editor/UUID-39929922 My plan is to present this view without the UUID-39929922 param. So the url end point should be as below, if I use the referer header to carry the UUID: appsite.com/editor My question is, Is there any downside to doing this? -
Django: Will large uploads hang the server?
I’m using: Django Django rest framework Django Storages with s3 I’m wondering if large (50mb+) uploads to a RestFramework FileField will hang the server from processing requests while the upload completes. Is this a concern? Should uploads be done somehow else? -
adding bind attribute to django cirspy form field
I was trying to add an alpine js directive which is x-bind:attr to a crispy form field but I couldn't find a solution that works, I know that attributes with a dash are handled by using an underscore, I tried to do the same by replacing double underscore with the double colon but It didn't work and no replacement is made. class ChildFormSetHelperUpdate(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.include_media = False self.layout = Layout( Div( Div(Field('model', x_bind__disable="disableInput"), css_class='col-md-6'), Div(Field('model_option'), css_class='col-md-6'), Div(Field('DELETE', css_class='input-small'), css_class="delete_row"), HTML( '<div class="row mt--2"><div class="col-md-6"><button type="button" class="btn btn-danger btn-sm text-white" x-on:click="hideForm($el,target)">Delete</button></div></div>'), css_class=f"row formset") ) self.attrs.update(dict( [((k.replace('__', ':')), conditional_escape(v)) for k, v in kwargs.items()])) self.render_required_fields = True``` -
django filter __contains returns no value on a list while __in does
am essentially trying to perform a select * from xyxtable where col like '%value%' on a list of alphanumeric values from another dataframe column(prev_df['VendorPartNumber]. I thought the filter __contains= should do the trick. but this returns nothing product_df=pd.DataFrame(Product.objects.filter(legacy_productid__contains=prev_df['VendorPartNumber']).values('id','legacy_productid')) however using the __in to filter works (just that the result is not what I want since __in tests for equality) product_df=pd.DataFrame(Product.objects.filter(legacy_productid__in=prev_df['VendorPartNumber']).values('id','legacy_productid')) I tried a couple of things such as product_df= Product.objects.all() for search_term in perv_df['VendorPartNumber']: product_df = product_df.filter(legacy_productid__contains=search_term) or product_df=pd.DataFrame(Product.objects.filter(reduce(operator.and_, (Q(legacy_productid__contains=x) for x in prev_df['VendorPartNumber']))).values('id','legacy_productid')) what am I missing? -
Static file are not working in Django "js/jquery.magnific-popup.min.js" 404
All static file is probably working but 2 files are not working. I want results like this in my HTML file. **My Code ** <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> <script src="{% static 'js/asyncloader.min.js' %}"></script> <!-- JS bootstrap --> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/owl.carousel.min.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/jquery.counterup.min.js' %}"></script> <!-- popper-js --> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/swiper-bundle.min.js' %}"></script> <!-- Iscotop --> <script src="{% static 'js/isotope.pkgd.min.js' %}"></script> <script src="{% static 'js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'js/slick.min.js' %}"></script> <script src="{% static 'js/streamlab-core.js' %}"></script> <script src="{% static 'js/script.js' %}"></script> ** Getting Cmd error** [17/Apr/2022 02:54:56] "GET / HTTP/1.1" 200 55322 [17/Apr/2022 02:54:56] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 160392 [17/Apr/2022 02:54:56] "GET /static/css/style.css HTTP/1.1" 200 154139 [17/Apr/2022 02:54:56] "GET /static/css/all.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:56] "GET /static/css/fontawesome.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:56] "GET /static/js/swiper-bundle.min.js HTTP/1.1" 200 140317 [17/Apr/2022 02:54:56] "GET /static/css/ionicons.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:56] "GET /static/css/owl.carousel.min.css HTTP/1.1" 304 0 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-6.jpeg HTTP/1.1" 200 315755 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-5.jpeg HTTP/1.1" 200 248498 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-4.jpeg HTTP/1.1" 200 340003 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-1.jpeg HTTP/1.1" 200 179687 [17/Apr/2022 02:54:57] "GET /static/css/flaticon/fonts/ionicons.ttf HTTP/1.1" 200 188508 [17/Apr/2022 02:54:57] "GET /static/images/background/asset-3.jpeg HTTP/1.1" 200 … -
A user just can a one comment, What will be the logic?
I already made a review form where user can give their feedback on the service. The form works perfectly, and data is also stored in the database. There is a rating star options as well. Now I just want to make a system where the user just can do one review. If a user did a review the review form won't show to the user. Now, what should I do? and What'll be the logic? models.py: class Frontend_Rating(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="frontend_rating") Rating = models.IntegerField(null=True) Feedback = models.TextField(max_length=250, null=True) template: <form action="frontend_ratings/" class="mt-3" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="radio-toolbar d-flex justify-content-center "> <input type="radio" id="one_star" name="frontend_ratting" value="1" checked> <label for="one_star" class="mx-1">1 <i class="fas fa-star"></i></label> <input type="radio" id="two_star" name="frontend_ratting" value="2"> <label for="two_star" class="mx-1">2 <i class="fas fa-star"></i></label> <input type="radio" id="three_star" name="frontend_ratting" value="3"> <label for="three_star" class="mx-1">3 <i class="fas fa-star"></i></label> <input type="radio" id="four_star" name="frontend_ratting" value="4"> <label for="four_star" class="mx-1">4 <i class="fas fa-star"></i></label> <input type="radio" id="five_star" name="frontend_ratting" value="5"> <label for="five_star" class="mx-1">5 <i class="fas fa-star"></i></label> </div> <!-- feedback area--> <div class="d-flex justify-content-center"> <textarea style="font-size: small;" maxlength="250" name="frontend_feedback" placeholder="Share your experience in 250 charecters...." class="col-10 mt-2 hireme_textarea btn montserrat text-left d-block" required rows="5"></textarea> </div> <div class="d-flex justify-content-center mt-3"> <button type="submit" class="btn singUpBtn col-10 submit_btn_sing_up_in sing_up_js1" id="message">Save</button> </div> … -
How to get and display data from database without refresh page using ajax and django
I want to get and display data from database to my page using django and ajax. This is my view : def getMessages(request, sender_id, receiver_id): if request.user.profile == 'A': chat = Chat.objects.filter(Q(sender_id=sender_id) | Q(receiver_id=sender_id)).all() elif request.user.profile == 'C': chat = Chat.objects.filter(Q(sender_id=sender_id,receiver_id=receiver_id) | Q(sender_id=receiver_id,receiver_id=sender_id)) return JsonResponse({"chat":list(chat.values())}) And This is my javascript: $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'getMessages/{{request.user.id}}/to/{{receiver_user.id}}'}", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.chat) { var temp='<div class="msg-box {% if request.user == msg.sender %} right {% else %} left {% endif %}"><div class="details"><p class="msg">{{ msg.message }}</p><p class="date">{{ msg.msg_time }}</p></div></div>'; $("#display").append(temp); } }, error: function(response){ console.log('An error occured') } }); },1000); }); And this is my urls.py: urlpatterns = [ path('<int:sender_id>/to/<int:receiver_id>',views.chat), path('send/', views.send, name='send'), path('getMessages/<int:sender_id>/to/<int:receiver_id>', views.getMessages, name='getMessages'), ] I try these codes but it doesn't work. -
django-bootstrap-modal-forms additional data in trigger
Using the following JQuery to trigger a modal: $("#view-large").modalForm({ modalID: "#fullscreen", formURL: "{% url 'view-fullscreen' ID %}" }); The 'ID' i formURL is is what I'm missing. It's from a subset of a query set (double foreach) and it prints a data-id="" into a html tag. How do I get that ID into the Jquery -
HTMX pass button value from selected list
I'm trying to make an application with Django using htmx. I have created a dropdown list as: <select class="custom-select mb-4" name="fields" hx-get="{% url 'select_field' %}" hx-trigger="change" hx-target="#Wells"> <option selected>Select a field</option> {% for Field in TFTFields %} <option ue="{{Field.Perimeter}}">{{Field.Perimeter}}</option> {% endfor %} </select> Now I want to take the selected value from this list and pass it to a button to excite another function called "plotlybar", I did something like this: <button class="btn btn-primary" hx-get="{% url 'plotlybar' %}" hx-target="#plotlybar">Plot the bar Well Serv</button> So now I didn't know how to pass this selected items? any hints or solution? All my best -
Getting correct data order from queryset python
I have a problem, then when I'm trying to get specific values from query set its giving me this in alphabet order. Example: account_data = Account.objects.all() [<Account: Merchant: ID: 267 (google@gmail.com), Currency: RUB, Brand: Brand NEWW (google@gmail.com)>, <Account: Merchant: ID: 265 (goole@gmail.com), Currency: EUR, Brand: Brand new (google@gmail.com)>, <Account: Merchant: ID: 264 (google@gmail.com), Currency: USD, Brand: Brand new2 (google@gmail.com)>, <Account: Merchant: ID: 266 (google@gmail.com), Currency: TRY, Brand: Brand new 3 (google@gmail.com)>, <Account: Merchant: ID: 269 (google@gmail.com), Currency: BGN, Brand: Brand new 4 (google@gmail.com)>] currency = ', '.join(sorted(list(account_data.values_list('currency__code', flat=True)))) Out[66]: 'BGN, EUR, RUB, TRY, USD' And this issue appears for all values, need to get currency connected to a specific account, not random or alphabet order. -
no such column error when trying to retrieve data in raw() Query in Django
I have the following classes in my models.py class Users(models.Model): username = models.CharField('User Name', null=False, max_length = 50) password = models.CharField('User Password', max_length=50) def __str__(self): return self.username def get_filepath(filename): old_filename = filename ts = time.time() timeNow = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y_%H-%M-%S') filename = "%s%s" % (timeNow, old_filename) return filename class Photo(models.Model): name = models.CharField(max_length=100, default="Image") id = models.AutoField(primary_key=True) uploader = models.ForeignKey(Users, default=None, on_delete=models.CASCADE) def __str__(self): return self.name class Photo_History(models.Model): image = models.ImageField(upload_to="media/results") upload_time = models.DateTimeField(auto_now_add=True, blank=True) photo_id = models.ForeignKey(Photo, null=True, blank=True, on_delete=models.CASCADE) What I am trying to access is, a user is logged in. I need to get the Photo History Objects along with the "name" from the Photo model of the user who's currently logged in. I tried to search a way to write a command using filter function to get this but I couldn't find any results that showed how you can get data from two different tables in a single query. And instead, people mentioned I should be using raw() query. So I used the raw query which I believe is totally fine, but I am getting a weird error (which you get if you haven't done in your migrations, but my migrations were done long ago and the column … -
Create Image Gallery accessble by a pin number
I'm trying to create an Image Gallery. I'm wanting the ability to upload multiple images at once and have them accessible to the customer by a pin number. I'm using Django and have tried a few different ways but can't seem to come up with something that works for the desired result I'm after. Any ideas or leads on the best way to accomplish this? Thank you! Jared -
apache2 throws the 500 error every time I restart the server (Python Django project)
I have a problem with my apache 2 server. Apparantly the problem was in the wsgi.py file connection because when I changed the DEBUG variable to true ,nothing changed. Here is my .conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the …