Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profile has no user
Im trying to use context processor to show profile page and when I use it the website show Profile has no user context processor: from .models import Profile `def get_profile (request): profile = Profile() return{'information':profile}` models.py" `class Profile(models.Model): user = models.OneToOneField(User, verbose_name=_("user"), on_delete=models.CASCADE) slug = models.SlugField(blank=True, null=True) image = models.ImageField(_("image"), upload_to='profile_img', blank=True, null=True) country = CountryField() address = models.CharField(max_length=100) join_date = models.DateTimeField(_("join date"),default = datetime.datetime.now)` also i made primary url for profile so when i want to go to profile page i write on url accounts/profile/mohammad account is the name of apps profile is the name of page mohammad is user name hints: i want to use profile.html on dropdown menu -
How to pass a js-function to django template with include?
I'm trying to include another template with a js function as variable. {% include "einkaufsliste/components/unorderedlist.html" with items=friends clickAction="see_friend()" %} <script> function see_friend(){ var x = $(this).attr("the_item") console.log(x) } </script> I get $(this), but not $(this).attr("the_item") (returns undefined) <div class="col-12 col-md-11"> <ul> {% for i in items %} <li {% if clickAction %} onclick="{{ clickAction }}" {% endif %} the_item="{{ i }}" >{{ i }}</li> {% endfor %} {% if not items %} <li>keine</li> {% endif %} </ul> </div> Maybe that's also not the proper way to pass a function? Any suggestions? Thanks in advance! -
How to organase smothly Redirect in Django for new Url-name princip
I wanna change url forming system in my site. The old URLs (that was indexed by Search Engines and link-build sites) have type: https://<hostname>/<old_site_section_name>/<id>/ I want change to: https://<hostname>/<new_site_section_name>/<product_brand-name>/ So, indexed url now is like: https://allgid.ru/Mnt/4149 and must be in future as like: https://allgid.ru/Monitor/acer-v227qabmix how make redirect in urls.py in Django: Now there: urlpatterns = [ path('<slug:cat_>/<slug:product_>', views.page_new_Product, name='product'), ... ] Can i use some regular expression directly in urlpattern like this: path(r'^\+\/\d+$', RedirectView.as_view(url='<new_url>', permanent=True)) But how can i get this re r'^\+\/\d+$' and pass it as an argument to some function; that function will connect to my Database, and get <new_site_section_name> by r'^\+ part of re and <product_brand-name> by \d+ part of re, so it 'id' of the Model (Table in db) and compute right new url like: /Monitor/acer-v227qabmix to put it in the place of <new_url> in RedirectView. Can i do it like: path(r'^\+\/\d+$', My_Function()) and this My_Function return RedirectView.as_view(url='<new_url>', permanent=True)? Does this will works? Or there is some enothe way to do this? -
get city from postal code using Geonames service
I am trying to create an API Rest in Django. I have created the models and the endpoints. The next step I have to perform is to retrieve the username' city from the postal code using the Geoname service: www.geonames.org. I have never used this service, I have seen something similar but in Java but haven't managed to make it work. This is my code if it is helpful: models.py: class UsuarioMaster(models.Model): nombre = models.CharField(max_length=50) class UsuarioDetalle(models.Model): usuario = models.ForeignKey(UsuarioMaster, on_delete=models.CASCADE, null=True) codigo_postal = models.CharField(max_length=5) ciudad = models.CharField(max_length=50) views.py: class UsuarioMasterListView(View): def get(self, request): if('name' in request.GET): u_list = UsuarioMaster.objects.filter(name__contains=request.GET['name']) else: u_list = UsuarioMaster.objects.all() return JsonResponse(list(u_list.values()), safe=False) class UsuarioDetailView(View): def get(self, request, pk): usuario = UsuarioDetalle.objects.get(pk=pk) return JsonResponse(model_to_dict(usuario)) -
why getting 'WSGIRequest' object has no attribute 'data' error?
I am trying to use card payment through stripe in react Js and Django. I am following https://betterprogramming.pub/how-to-integrate-django-react-app-with-stripe-payments-95709b3f23e5 this tutorial. frontend const handleSubmit = async (event) => { event.preventDefault(); const card = elements.getElement(CardElement); const {paymentMethod, error} = await stripe.createPaymentMethod({ type: 'card', card: card }); ApiService.saveStripeInfo({ email, payment_method_id: paymentMethod.id}) .then(response => { console.log(response.data); }).catch(error => { console.log(error) }) } export const api = axios.create({ baseURL: API_URL, headers: { "Content-type": "application/json" } }); export default class ApiService{ static saveStripeInfo(data={}){ return api.post(`${API_URL}/payments/save-stripe-info/`, data) } } server @api_view(['POST']) def test_payment(request): test_payment_intent = stripe.PaymentIntent.create( amount=1000, currency='pln', payment_method_types=['card'], receipt_email='test@example.com') return Response(status=status.HTTP_200_OK, data=test_payment_intent) def save_stripe_info(request): print('this => ',request.data) data = request.data email = data['email'] payment_method_id = data['payment_method_id'] # creating customer customer = stripe.Customer.create( email=email, payment_method=payment_method_id) return Response(status=status.HTTP_200_OK, data={ 'message': 'Success', 'data': {'customer_id': customer.id} } ) but whenever I click the submit button it given me following error AttributeError: 'WSGIRequest' object has no attribute 'data' [12/Dec/2021 21:55:57] "POST /payments/save-stripe-info/ HTTP/1.1" 500 71355 for full code please visit https://betterprogramming.pub/how-to-integrate-django-react-app-with-stripe-payments-95709b3f23e5 -
Django CBV - How to test get_context_data with uuid in url?
I use the UUID in the url instead of the primary key. I assume, but am not sure, that this is the cause of my problem in testing my CBVs. my view for user profile : class ProfileView(DetailView): slug_url_kwarg = 'uuid' slug_field = 'uuid' model = User template_name = 'users/profile.html' context_object_name = 'user_profile' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['uuid'] = self.kwargs.get("uuid") return context My url : path( route='profile/<uuid:uuid>', view=views.ProfileView.as_view(), name='profile', ), I can't test get_context_data, Django tells me that my view has no "object" attribute. Maybe I need to override get_object, but my search didn't find anything. My test : class BaseTest(TestCase): def setUp(self): # Set up non-modified objects used by all test methods self.factory = RequestFactory() self.user2 = User.objects.create_user( email='caroline.dupont@free.fr', password='fhh456GG455t', status='VALIDATED', ) return super().setUp() def profile_view_instance(self, test_user): request = self.factory.get(reverse('profile', args=(test_user.uuid,))) request.user = test_user view = ProfileView() view.setup(request) return view class ProfileViewTestCase(BaseTest): def test_get_context_data(self): self.client.force_login(self.user2) context = self.profile_view_instance(self.user2).get_context_data() self.assertIn('uuid', context) The error : ERROR: test_get_context_data (tests.appusers.test_views.ProfileViewTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\Developpement\projet13\tests\appusers\test_views.py", line 75, in test_get_context_data context = self.profile_view_instance(self.user2).get_context_data() File "D:\Developpement\projet13\users\views.py", line 66, in get_context_data context = super().get_context_data(**kwargs) File "D:\Developpement\projet13\venvp13\lib\site-packages\django\views\generic\detail.py", line 94, in get_context_data if self.object: AttributeError: 'ProfileView' object has no attribute 'object' -
How to check email verification code equality in django rest framework?
I am trying to build a email verification for my website with django rest framework. The mechanism is like this: User enters his email and presses continue button He gets a 6 digit verification code He enters the 6 digit code that he received If the code is valid he goes to next step and else an error occurs My problem is in step 4. I don't know how to check the verification code equality, because I can't get it from step 2. My codes are below. I'd be so happy if anyone can help me through this problem:) serializers.py class CodeSerializer(serializers.Serializer): code = serializers.IntegerField() class EmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', ] methods.py import random from django.conf import settings from django.core.mail import send_mail def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) def send_verification_mail(email): generated_code = generate_activation_code() subject = 'Sinjim verification code' message = f'Your verification code:\n{generated_code}\nThanks for using sinjim.' from_email = settings.EMAIL_HOST_USER recipient_list=[email, ] send_mail(subject, message, from_email, recipient_list) views.py class EmailView(APIView): def post(self, request, format=None): serializer = EmailSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] methods.send_verification_mail(email) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CodeView(APIView): def post(self, request, format=None): serializer = CodeSerializer(data=request.data) code2 = methods.generate_activation_code() if serializer.is_valid(): if … -
How do i get all the objects which is in ManyToMany field in Django models
I have two models and in the second model, i created a ManyToMany field class Listing(models.Model): title = models.CharField(max_length=50) name = models.CharField(max_length=100) description = models.TextField() starting_bid = models.IntegerField() category = models.CharField(max_length=50, blank=True) image = models.TextField(blank=True) posted_by = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.title class Catagories(models.Model): category = models.CharField(max_length=100) listings = models.ManyToManyField(Listing, blank=True, related_name="cat") Now let's assume i have created a category "Electronics" and I had saved 3 listings in this category with title "Mobile, laptop, microwave". Now i want to get all the listings inside this category and I'm not getting it. Now Questions is: How do i get all of the listing items inside this category? -
How to change the content of navbar after user registration in django
I want to change the content of my django home page from Login,Register to Logout when the user gets redirected to the home page after successful registration. I was able to achieve the following change when the user logs in by using the user.is_authenticated but unable to do the same when user registers and gets redirected without the need to log in. views.py: from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if(request.method=='POST'): form=UserRegisterForm(request.POST) if(form.is_valid()): form.save() username=form.cleaned_data.get('username') messages.success(request,f'Account created for {username} , you can now login') return redirect('blog-home') else: form=UserRegisterForm() return render(request,'users/register.html', {'form':form}) @login_required def profile(request): return render(request,'users/profile.html') home.html: {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav … -
How do i test for authentication in django
def authenticate(username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(raw_password=password): return user return None except User.DoesNotExist: return None def authenticate(username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(raw_password=password): return user return None except User.DoesNotExist: return None -
RelatedObjectDoesNotExist at /profile/ User has no customer
I have created the user Customer model. I migrated the model to syn with the database. However I am getting an error of User has no customer. click to profile page through http://127.0.0.1:8000/profile But after adding profile code for every user I am getting the below error Here is my code from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) full_name = models.CharField(max_length=200, null=True) address = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.full_name class CustomerProfileView(TemplateView): template_name = "app/CustomerProfile.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = self.request.user.customer context['customer'] = customer orders = Order.objects.filter(cart__customer=customer).order_by("-id") context["orders"] = orders return context -
Pass kwargs to model save method
I am stuck in weird situation i have this kwarg['device_id'] which i need to access in my save method , it there any way i can achieve this, the reason i want to avoid overriding update method because i have kept my external API calls in model save method , help is needed thanks def save(self, *args, **kwargs): device_uid = (getattr(self,'device_id')).upper() device_name = getattr(self,'device_name') device_profile_name = getattr(self,'device_profile_name') app_id = getattr(self,'device_profile_name') # check whether model is getting saved or updated if self._state.adding: device_status, error_remarks = add_device(app_id,device_profile_name,device_uid,device_name) else: print(device_name,device_uid,device_profile_name,app_id) device_status, error_remarks = update_device(app_id,device_profile_name,device_uid,device_name) <<-- API call if device_status == 200 : super(DeviceSubscription, self).save(*args, **kwargs) schedulars.check_device() else: print(error_remarks) raise RequestException('err:{}'.format(er #update device @api_view(['PUT']) def update_device(request,*args,**kwargs): if kwargs['device_id']: try: device_ins = DeviceSubscription.objects.get(device_id = kwargs['device_id']) serialized_data = DeviceAdditionSerializer(device_ins,request.data,partial = True) if serialized_data.is_valid(raise_exception=True): serialized_data.save() return Response({'data':serialized_data.data},status=200) except Exception as e: return Response({'err':str(e)},status=400) else: return Response({'status':'bad request'},status=400) -
Django rest framework serializer Got AttributeError when attempting to get a value for field `field` on serializer. Try to nest serializers
AttributeError: Got AttributeError when attempting to get a value for field vesting_choice_id on serializer VestingLocationRateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'vesting_choice_id'. Model class VestingChoice(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) participant = ForeignKey('Participant', on_delete=CASCADE, related_name="participants_id") vesting = ForeignKey('Vesting', on_delete=CASCADE, related_name="vestings") class VestingLocationRate(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) vesting_choice_id = ForeignKey('VestingChoice', on_delete=CASCADE, related_name="vesting_choice") country_id = ForeignKey(Country, on_delete=CASCADE, related_name="country_id") Serializers class VestingChoiceSerializer(serializers.ModelSerializer): class Meta: model = VestingChoice fields = "__all__" class VestingLocationRateSerializer(serializers.ModelSerializer): vesting_choice_id = VestingChoiceSerializer(many = False) country_id = CountrySerializer(many = False) class Meta: model = VestingLocationRate fields = "__all__" -
Add multiple "Place of Interest" model to a "Tour" model in Django and allow one "Place of Interest" to be in multiple "Tour" model
What is the best way to represent this situation: I want to create a tour app that consists of "Tour" and "Place of Interest" The "Tour" model would have multiple "Place of Interests". One "Place of Interest" should be able to be added to multiple "Tour". I can't wrap my head around this. So far, I can only add one "Place of Interest" to one "Tour" Here's my model: class PlaceOfInterest(models.Model): name = models.CharField(max_length=255) tour = models.ForeignKey("Tour", on_delete=models.CASCADE, related_name="tours", blank=True, null=True) class Tour(models.Model): title = models.CharField(max_length=255) Any pointer would be greatly appreciated. Thanks in advanced. -
Script returns an empty list data with 200 response, fetching data from django backend
I am working on an autocomplete app that I want users be able to make address search through the backend of Django but somehow the Api doesn't fetch data through the script, why is the payload show any data in the log console but rather an empty list?, I have tried calling the data from the browser as in example http://127.0.0.1:8000/search/?address=val , which fetches the json data response with a payload of data of addresses that match my search, but when i pass the url in my javescript it returns an empty data list with a 200 response. My experience in Js is mediocre, since I'm a novice. <script> new Autocomplete('#autocomplete',{ search : input => { console.log(input) const url = "/search/?address=${input}" return new Promise(resolve => { fetch(url) .then( (response) => response.json()) .then( data => { console.log(data) resolve(data.data) }) }) }, onSubmit : result => { console.log(result) window.open('/search/?address=${result}') } }) </script> my view for search def search_address(request): address = request.GET.get('address') playload = [] if address: fake_address_objs = Address.objects.filter(address__icontains=address) for fake_address_obj in fake_address_objs: playload.append(fake_address_obj.address) return JsonResponse({'status':200 , 'data': playload }) Returned empty data in the console log Returned data in browser using http://127.0.0.1:8000/search/?address=v -
DRF - lack of JWT when creating user instance
I'm struggling with jwt. When I create user's instance, there is not jwt. When I try to obtain jwt with registered credentials I receive info that provided credentials are not correct. It works fine when I create superuser via cmd. serializers: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User write_only_fields = "password" read_only_fields = ('id',) fields = ["email", "password", "first_name", "last_name"] for field in fields: extra_kwargs = {field: {'required': True,'allow_blank': False}} def create(self, validated_data): validated_data["username"] = f'{validated_data["first_name"]}_{validated_data["last_name"]}_{User.objects.count()}' return User.objects.create(**validated_data) signals: from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) views class CreateUserView(CreateAPIView, GenericViewSet): model = User permission_classes = [ permissions.AllowAny ] serializer_class = UserSerializer response = {} def create(self, request): validation_selializer = UserRegistrationSerializer(data=request.data) if validation_selializer.is_valid(): final_selializer = self.get_serializer(data=validation_selializer.data) if final_selializer.is_valid(): self.response = { "info":{ "status":"created", "email":validation_selializer.data["email"] } } return Response(self.response, status=status.HTTP_200_OK) self.response = validation_selializer.errors return Response(self.response, status=status.HTTP_400_BAD_REQUEST) -
Django Form Dropdown List Won't Display
I want to create a dropdown list in a form. I followed this approach here. If I use {{ form.as_p }}, the dropdown list renders just fine. But rendering the form using as_p looks terrible. Instead, I loop through the form fields and access their parameters so I can stylize the inputs. I try to catch the field of the dropdown list using an if-statement with condition field.widget.input_type == "select". When the page renders, I should see "This is where my dropdown goes" where my dropdown list field is supposed to be. But that doesn't happen, the field gets rendered as a text input like every other field, so my if-statement is not working. I debugged my view function and confirmed that the field corresponding to the dropdown list does have parameter .widget.input_type == "select". What am I doing wrong? <form action="{% url 'myapp:newrecord' %}" method='post'> {% csrf_token %} {% for field in form %} <div class="form-group row"> {% if field.widget.input_type == "select" %} <p>This is where my dropdown goes.</p> {% else %} <label for="{{ field.id_for_label }}" class="col-sm-2 col-form-label">{{ field.label }}</label> <div class="col-sm-10"> <input type="text" name="{{ field.html_name }}" class="form-control" id="{{ field.id_for_label }}" placeholder="{{ field.label }}" required> </div> {% endif %} … -
Can we combine multiple exists() queryset API calls into a single DB call using annotate?
I have a decorator.py function to check if a logged user has permission to access a view. def allow_only_admins_authors_coauthors_reviewers_specialists(view_func): def wrapper_func(request, *args, **kwargs): email_of_logged_user = request.user.email book_id = kwargs['pk'] # Get the book id if (request.user.is_admin or \ (Coauthors.objects.filter(paper=book_id, email=request.user).exists()) or \ (Book.objects.filter(Q(id=book_id, author=request.user) | Q(id=book_id, author__email__in=request.user.get_secondary_emails_flat_list)).exists()) or \ (Token.objects.filter( Q(book=book_id, email=email_of_logged_user) | Q(book=book_id, email_which_was_actually_used_to_retrive_token__emails__icontains = email_of_logged_user) # 'email_which_was_actually_used_to_retrive_token' contains the actual email which was used by the reviewer to retrieve the token. Its different than the email to which the token was originally sent. ).exists() # Sometimes, the token might be deleted. In such case, system shall check if the logged user is the reviewer within the Review model. ) or \ (Review.objects.filter(paper=book_id, user__email = email_of_logged_user).exists()) or \ (SpecialistAssignment.objects.filter(raw_book=book_id, user=request.user).exists())): return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorised to view this page!') return wrapper_func This function would make multiple DB calls due to multiple the exists() API checks. Is there any way we can combine these multiple exists() into a single DB query using annotate? Secondly, is this approach faster than using django-rules? -
Django can't find my DetailView with Primary Key
I'm trying to make a simple page with Django where posts are being displayed using primary keys. However, the DetailView page with my posts can't be displayed. This is my model: class Post(models.Model): author = models.CharField(max_length=100) title = models.CharField(max_length=100) posted_date = timezone.now() text = models.TextField() def get_absolute_url(self): return reverse("postdetail", kwargs={"pk": self.pk}) def __str__(self): return self.title and here is my url pattern list: urlpatterns = [ url(r'^posts/(?P<pk>\d+)$', views.PostDetail.as_view(), name="postdetail"), url(r'^$', views.index, name="index"), url(r'^thanks/$', views.Thanks.as_view(), name="thanks"), url(r'^postlist/$', views.PostList.as_view(), name="postlist"), ] Here is the DetailView: class PostDetail(DetailView): context_object_name = 'post_details' model = Post I can't see where I might have a mistake. I have a ListView that shows my posts including the primary keys. But when I try to open the URL http://127.0.0.1:8000/posts/1/ I get: `Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/posts/1/ Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order: admin/ ^posts/(?P<pk>\d+)$ [name='postdetail'] ^$ [name='index'] ^thanks/$ [name='thanks'] ^postlist/$ [name='postlist'] The current path, posts/1/, didn’t match any of these. Do you have a clue why the URL cannot be found? Thank you very much.` -
Getting an error of "<Team: jaja>" needs to have a value for field "id" before this many-to-many relationship can be used
I'm trying to add team to the database but i get this error. Took a look at similar questions but none of them solved my issue. (I am new with Django) My code looks like: forms.py from django.forms import ModelForm from .models import Team class TeamForm(ModelForm): class Meta: model = Team fields = ['title', 'team_country', 'team_logo'] def __init__(self, *args, **kwargs): super(TeamForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) models.py from django.db import models # Create your models here. from django.contrib.auth.models import User from django_countries.fields import CountryField from .validators import validate_file_size class Team(models.Model): # # Status ACTIVE = 'active' DELETED = 'deleted' CHOICES_STATUS = ( (ACTIVE, 'Active'), (DELETED, 'Deleted') ) # # Fields title = models.CharField(max_length=255) team_country = CountryField(blank=True, null=True) team_logo = models.ImageField( null=True, blank=True, upload_to='logos/', default="logos/logo.png", validators=[validate_file_size]) members = models.ManyToManyField(User, related_name='teams') created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=CHOICES_STATUS, default=ACTIVE) class Meta: ordering = ['title'] def __str__(self): return self.title views.py from django.shortcuts import render from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from .models import Team @login_required def add(request): profile = request.user.profile form = TeamForm() if request.method == 'POST': form = TeamForm(request.POST, request.FILES) if form.is_valid(): team = form.save(commit=False) … -
how can I auto scroll down - chat app with django
hello I want to auto scrolldown because whenever I refresh the page I see always the top of conversations I mean the start-conversation , this is my code <div class="card-body height3 scrollbar" style="margin-bottom: -60px;" id="card-body"> <ul class="chat-list" id="chat-list-id"> <p class="start-conversation">&nbsp;</p> {% for chat in chats %} {% if chat.from_user == user.username %} <li class="out"> <div class="chat-img"> <img alt="avatar" style="height: 48px;width: 48px;" src="{{here.image.url}}"> </div> <div class="chat-body"> <div class="chat-message"> <h5>Me</h5> <p>{{chat.messag_body}}</p> </div> </div> </li> {% else %} <li class="in"> <div class="chat-img"> <img alt="avatar" src="{{here.image.url}}"> </div> <div class="chat-body"> <div class="chat-message"> <h5>{{ chat.from_user }}</h5> <p>{{ chat.messag_body }}</p> </div> </div> </li> {% endif %} {%endfor%} </ul> </div> -
reading text file from user pyttsx3 python
I have a program that read text from the keyboard and convert that text into an audio, also the program could take a text file (docx, pdf, txt, etc...) from user and convert it to audio. I am having hard time to convert the file. every time I run the code the [Errno 2] No such file or directory: 'file_name. (I am using python, Django, and pyttsx3) def convert_Two(request): #taking iput from user value = request.GET['file'] with open(value, 'r') as file: data = file.readlines().replace('\n', '') obj = pyttsx3.init() obj.say(data) obj.runAndWait() return redirect('/') -
Displaying names of the DB tables that contain specific data
I was able to get the names of the tables of DB with specific data in Python like this: r = list(conn.cursor().execute('''select m.name from sqlite_master m where m.type = 'table' and exists (select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_id')''')) print('Names of the tables that contain customer data:\n','\n'.join(map(str, r))) The output is: "actor" and "film actor" Is there any way to get the same output in Django website? I just can't think of any way to do that. DB that I'm using is Sakila. I've generated model objects for every table already. -
How to solve the No module named bootstrap_date_picker_plus error?
I am using Django 3.2.3 and I would like in my app to use date picker using the package bootstrap_datepicker_plus. I have installed it and added it following the steps in the link https://pypi.org/project/django-bootstrap-datepicker-plus/. However, when I run the app, I am getting the error ModuleNotFoundError: No module named 'bootstrap_datepicker_plus. When I checked in the installed packages, I noticed that the bootstrap_date_picker_plus package is installed as it is shown in the attached image -
Django S3: The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256
I'm following a course and I believe I'm doing everything the guy says step by step, however, I'm running into a problem where I cant output images to my django website from Amazon buckets. i get <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>FBT5M3QQ69AF3QNB</RequestId> <HostId>L8MYNGNFtHoMzCIn8zQZLaIIzrtWpSE31tG4zeIr1o/XqdudSvvPhV9fUEBB5EiNvuWHtM+WqQc=</HostId> </Error> These are my setting.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') # user uplaoded content STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '********' AWS_STORAGE_BUCKET_NAME = 'mybucket-name' The files are getting uploaded to the bucket successfully, but they won't show on the web page...