Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can I get the location of a user app from another user of same app
I’m trying to build a simple pick up and delivery app. I want a user to submit a pickup location and delivery location. Then as soon as the user submits I want to be able to get the locations of the riders’ apps but I don’t know how to go about it. It’s just like a normal for example uber app that searches the drivers locations and calculates the nearest one. Calculating the nearest one is not the issue as I can do that with google maps api, but how can I get the riders app location from the backend.? Thank you in advance. -
Inline Boostrap Cards using Django For Loop
I am using Bootstrap to make my website loop better, but I am having trouble organizing my cards in a horizontal line since I am using Django For loop to render information: html <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Coaches</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <div class="container"> {% for programas in programas_entrenamiento %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{programas.foto_programa.url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{programas.programas}}</h5> <p class="card-text">{{programas.descripcion|truncatechars:50}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> {%endfor%} </div> models.py class ProgramasEntrenamiento(models.Model): programas = models.CharField( choices=EXERCISE_CHOICES, max_length=200, null=True) descripcion = models.TextField() foto_programa = models.ImageField(upload_to='pics/programas', null=True) def __str__(self): return self.programas Current output Expected output (sorry for bad editing) -
DjangoCMS carousel slider doesn't fit to fullscreen
i am working on a project in Djangocms. In frontage i want to put a background carousel. When i put the image sliders on it through edit, it doesn't fit to screen. i try use fluid container but it shows padding/space around it. Besides i tried to use style row column along with alignment through edit in toolbar, padding grows bigger. Should i have to do manual coding? is there any document on Djangocms carousel plugin? what is the way to edit the carousel design in Djangocms? -
Django runserver shows just blank page
I am currently trying to setup the Django web app from https://github.com/fiduswriter/fiduswriter. When I run python manage.py runserver localhost:8000 I do not receive any errors when accessing localhost:8000, but there is no page coming up. However, when I build the Docker image resp. pull the one from https://hub.docker.com/r/moritzf/fiduswriter/, I can start it and it shows the starting page. How is this phenomenon explicable? -
send_mail only works in terminal in django
I'm trying to get my website to send a email when a button is pressed. However, it only sends a email when I use send_mail in the shell and does nothing when the button is pressed. I currently have the following in my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = '#' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = '#' The # is of course only there for this question In my html file I have <form method="post"> {% csrf_token %} <button type="submit" name="place_order" class="btn btn-success"> Place Order</button> </form> the place_order links up with my views.py which checks whether or not the button is clicked checkout = request.POST.get('place_order') if checkout: send_mail('Django test mail', 'this is django test body', '#', ['#'], fail_silently=False,) messages.info(request, f'Your order has been placed!') -
Django Index not took in account for existing table
I use existing mysql table with Django Rest Framework. On a big mysql table, a simple select request in phpmysql tooks 10 seconds without index. With an index on a field, it tooks 3ms. So I added manualy the index with phpMysql, but Django still takes 10 seconds to execute the request and dosn't see the new index. I added db_index=True in my field in models.py. But make migration didn't see any update on my already existing models, and the speed is still 10s. (Any updates on tables created by django work very well) I decided to remove my index manualy with phpmysql, and I created by my self a 0002_initial.py file with this code : from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tutorials', '0001_initial'), # or last mig ] operations = [ migrations.RunSQL("CREATE INDEX idx_last_name ON crm_users (us_last_name(64))") ] I ran migrate, and django creates the index in the table. But Django still takes 10s to perform one select on the indexed field and dosn't use the mysql index. My question : Where and how can I say to django to use indexes for existing table not created by Django ? Thank you very much ! -
Django serializer error expected number but got [28]
I'm new to Django and Python, I'm using Django-rest-framework for building RESTfull API. I have a view like this class ProfileViewSet(APIView): # to find if isAuthenticate then authentication_classes = (TokenAuthentication,) permission_classes = [permissions.IsAuthenticated] def post(self, request): user_id = request.data['user_id'] request.data.pop('user_id') request.data['user_id'] = int(user_id) serializer = ProfileSerializer( context={'request': request}, data=request.data) if serializer.is_valid(): serializer.create(validated_data=request.data) return Response(serializer.data) return Response(serializer.errors) and my serializer goes something like this class ProfileSerializer(serializers.ModelSerializer): # id = serializers.IntegerField(source='profile.id') user_id = serializers.IntegerField(source='user.id') user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault()) profile = Profile # depth=2 class Meta: model = Profile fields = ('id', 'user', 'image', 'first_name', 'last_name', 'description', 'mobile', 'current_location', 'user_id') read_only_fields = ('user', 'user_id') from my frontend, I'm sending user_id as a string so I'm parsing it to number. error:- TypeError: Field 'id' expected a number but got [28]. -
receiving updates from server in multi user environment
So I'm currently working on an application with react frontend and django backend. My application is a multi user application ,i.e, at max 20 users would be connected for a single task. Now, UserA makes some updates and calls the REST API, how to tell UserB,C,D ..etc that a change has happened? One way would be to create another rest api which all users will hit in some setIntervalto get updates but I don't think that is a good idea. What are the best ways to this in the scenario? Also, I would have a chat room for this , should I go for xmpp or rather use django channels? -
Updating content without refreshing page in django
Can someone give me a code for django template for updating time without refreshing the page? Currently ive stored time in a variable in views and im passing it dynamically to the html, but it does not update without reloading. People suggest ajax but im new to all this and idk much, so please provide the easiest ans😅. Thanks in advance :) -
how to read and process doc files in Django to count words inside the file
I'm trying to let the user add a .doc file using a form in Django, but it keeps giving me the error : a bytes-like object is required, not 'str' Here is my code : def upload_quota(request): upload_file_form = FileReplaceForm(request.POST , request.FILES) if request.method == 'POST': if upload_file_form.is_valid(): file = upload_file_form.cleaned_data['file'] data = file.read() word = data.split(" ") print(len(word)) -
Problemas con login Pagina de incio Django 3.0
Estoy tratando de aplicar mi pagina de inicio con contraseña, pero me dice que la orden no funciona, y he podido encontrar por que. este es el error que me mustra: mis urls del propyecto: from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path("empleado/", include("apps.empleado.urls")), path("liquida/", include("apps.liquida.urls")), path("usuario/", include("apps.usuario.urls")), path("login/", views.LoginView.as_view(),{'template_name':'index.html'}), ] esta es mi template para el login: % extends 'base/base.html' %} {% block title %} {% endblock %} {% block navbar%} {% endblock %} {% block content %} <br> <h1>Iniciar sesión - Login</h1> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-md-8 col-md-offset-3"> <div class="form-group"> <label for="username">Nombre de usuario:</label> <input class="form-control" type="text" name="username"> </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-3"> <div class="form-group"> <label for="username">Contraseña:</label> <input class="form-control" type="password" name="password"> </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-3"> <div class="form-group"> <a href="#">Olvidé mi contraseña</a> <input class="btn btn-primary" type="submit" value="Ingresar"> </div> </div> </div> </form> Mi settings: #LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = reverse_lazy('empleado:empleado_listar') Cuelaquier ayuda lo agradeceria, no logro poder aplicar el login, no me genera la plantilla de inicio y contraseña. -
I am trying to add an image in html using django framework, image does not appear
{% extends "basic_app/base.html" %} {% load staticfiles %} {% block body_block %} <div class="card text-center"> <div class="card-body" style="background-color:#F22A00"> <h5 class="card-title" style="color:black;text-align:center;">TSEC CODESTORM</h5> <p class="card-text" style="color:black;text-align:center;">A campus chapter of codecheff</p> </div></div> <img src="{% static "basic_app/images/hckathon.jpg" %}" alt="Uh Oh, didn't show!"> {% endblock %} This is the code ive used in extended index file however after trying different browsers the image is not visible. Here is a screenshot of my webpage -
How can I set up my unread message counter with my models?
So I am attempting to set up an unread message counter through a simple tag and get that in my template. Now, I'm running into a problem where a message that's sent to another user is showing up as 'unread' from my user even though it's being sent to the other user. I obviously only want messages that are sent to only MY user to be shown as unread. I'm not sure if I need to add another field to my InstantMessage model such as 'receiver' or if there's someway I can check user against request.user in my unread_messages_counter.py. unread_messages_counter.py register = template.Library() @register.simple_tag def unread_messages(user): return user.sender.filter(viewed=False).count() models.py/InsantMessage and Conversation class Conversation(models.Model): members = models.ManyToManyField(settings.AUTH_USER_MODEL) class InstantMessage(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) message = models.TextField() date = models.DateTimeField(verbose_name="Data creation",default=timezone.now(), null=False) viewed = models.BooleanField(default=False, db_index=True) def __unicode__(self): return self.message -
authentication with google in django graphql app
I have a Django web application and I am using graphql APIs with graphene_django. I have my own authentication system with django_graphql_jwt. I want to have an authentication system with google too and It would be better if I can customize it Do you have any idea that what modules or libraries I can use? -
Get a correct path from random data
my index page,i have image galary when some one click one of ithome page, it shoud show more information with more photos in another page.all are loading from MySQL database with forloop. I'm unable to get the detail of clicled image information from my data base.i am very new for programing. please help mesource cord of my images galley -
Django, how to set inline formset factory with two ForeingKey?
I have create a code that works perfectly except for one little problem. I have created an inline formset factory utilizing two models: Lavorazione and Costi_materiale. class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, ) numero_lavorazione=models.IntegerField() class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) prezzo=models.DecimalField() After I have created the inline formset facotry as the following: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", exclude=('codice_commessa',), can_delete=True, extra=1 ) But I have in Costi_materiale two ForeignKey, instead in the form the formset recognise only numero_lavorazione and not also codice_commesse. I want that the formset set in the first model the codice commesse and lavorazione fields and subsequently in the inline formset the other fields. In other word: How can I set two ForeignKey in a inline formset factory? -
Django all-auth - Social login - Facebook - Pass without requesting email
So I must be missing something, I've looked for similiar questions and tried their solutions like overhere (Django allauth, require email verification for regular accounts but not for social accounts) I would like to let users interact with my webapp without requesting their e-mailadres after logging in with their social account, in this case with their facebook account. I have the following set up; settings.py ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'optional' SOCIALACCOUNT_EMAIL_REQUIRED = False SOCIALACCOUNT_EMAIL_VERIFICATION = 'optional' At the moment, whenever someone tries to login with their facebook account, they get redirected to the signup form requesting for their email address. Even though I'm using email as a authentication method for regular signups, this should not be necessary for social signups am I right? Best regards, Kevin -
No module named 'users.urls'
This is my urls.py: from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path( route='', view=TemplateView.as_view(template_name='posts/index.html'), name='index' ), path( route='post/my-post.html', view=TemplateView.as_view(template_name='posts/detail.html'), name='detail' ), path( route='sobre-mi', view=TemplateView.as_view(template_name='about.html'), name='about' ), path('', include(('users.urls', 'users'), namespace='users')), ] And this is the error I get when running python3 manage.py runserver: ModuleNotFoundError: No module named 'users.urls' -
Passing a dictionary to Ajax
I have an Ajax call on a on('click',) event. The data passed from my HTML is value= '{{y.id }} {{ y.id }}'. Ajax passes it to my views.py in python server side as a str . Is there a way to get it straight as a list or dictionary? Or do I have to extract it and convert it in my views.py? -
Django create profile for user signal
im trying to create profile for user account using signals but after writing the codes is not creating at all Django 3.0.5 users/models.py from django.db import models from django.contrib.auth.models import User from PIL import Image# class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.profile_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.profile_image.path) users/signals.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() users/apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals i check all the option on internet , but cant make this work , can any one help, maybe i missing something in my codes settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'courses', 'crispy_forms', ] -
How can I unittest get_context_data() of a ListView in Django?
I tried to write a unittest for a ListView in Django 3.0.5. I need to check the data included in the context. The Application is running for this view, so error in implementation is not likely. But what did I missed when setting up my test? Here parts of my source: urls.py: app_name = 'gene' urlpatterns = [ path('persons/', views.PersonList.as_view(), name='person-list'), ... ] views.py from django.views.generic.list import ListView from gene.models import Person class PersonList(ListView): model = Person def get_context_data(self, **kwargs): context = super(PersonList, self).get_context_data(**kwargs) # this is line 11 ... return context tests.py: from django.test import TestCase, RequestFactory from django.urls import reverse from gene.models import Person from gene.views import PersonList class PersonListTest(TestCase): def setUp(self): person1 = Person.objects.create(name="Person 1") person2 = Person.objects.create(name="Person 2") def test_context(self): request = RequestFactory().get(reverse('gene:person-list')) view = PersonList() view.setup(request) context = view.get_context_data() # this is line 20, Error here self.assertIn('environment', context) I followed the guides from official documentation. But when I run this test I get following on console: Error Traceback (most recent call last): File "/home/macbarfuss/PycharmProjects/Genealogy/gene/tests.py", line 20, in test_context context = view.get_context_data() File "/home/macbarfuss/PycharmProjects/Genealogy/gene/views.py", line 11, in get_context_data context = super(PersonList, self).get_context_data(**kwargs) File "/home/macbarfuss/PycharmProjects/Genealogy/venv/lib/python3.8/site-packages/django/views/generic/list.py", line 115, in get_context_data queryset = object_list if object_list is not None … -
Discord.py - 'NoneType' object has no attribute 'voice_state'
Thought this was going to be fairly simple but clearly not, the guild I'm passing into join_guild is a Django Model Object. In _join_guild I'm trying to get the first VoiceChannel for the guild and simply connect the bot to it. However, been getting the following error for ages. Any help on where I'm going wrong or what's happening here would help. Error: Traceback (most recent call last): File ".../env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File ".../env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File ".../env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File ".../soundboard/sound/views.py", line 41, in play_guild_sound join_guild(guild) File ".../soundboard/sound/discord.py", line 38, in join_guild loop.run_until_complete(_join_guild(guild)) File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete return future.result() File ".../soundboard/sound/discord.py", line 32, in _join_guild await first_channel.connect() File ".../env/lib/python3.8/site-packages/discord/abc.py", line 1066, in connect await voice.connect(reconnect=reconnect) File ".../env/lib/python3.8/site-packages/discord/voice_client.py", line 219, in connect await self.start_handshake() File ".../env/lib/python3.8/site-packages/discord/voice_client.py", line 152, in start_handshake await ws.voice_state(guild_id, channel_id) AttributeError: 'NoneType' object has no attribute 'voice_state' Code: import asyncio from discord import Client, VoiceChannel client = Client() def voice_channels(channels): r = [channel for channel in channels if isinstance(channel, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r async def _join_guild(guild): await client.login(token=settings.BOT_TOKEN) disc_guild = await client.fetch_guild(guild.guild_id) channels = … -
i stuck with these error in django there all command work but if i want start server these error occur
Unable to create process using 'C:\Users\Bunty Waghmare\Desktop\env_site\Scripts\python.exe manage.py runserverenter image description here -
Django TabularInline with custom inner formset
In the Django admin I have a TabularInline (WhitholdingModel) form that has three attributes, one of them is a Model itself (CIIUModel). I want to have three different choiceFields mapping an attribute of the CIIUModel. If the user selects one field, the other should be filtered to the ones that have that attribute value. So, for example, if the first choiceField is city, and I select X city, the second choiceField must only contains values whose city is X. Besides that, I'm trying the choicefields to be stacked one below other. I have tried with formset but with no luck by now. How can I accomplish this? This is the layout I'd like to have. P.S: I'm trying not to have to handle html, so if it can be accomplished with only Python would be excelent! -
disable weasyprint django
I am working on django python and i am new to this. I just want to disable rendering pdf because it is causing trouble to me and I just want to render a normal html. How would i edit this current code I have to just let it render html instead of weasyprint pdf? from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML from tests.models import Test from users.models import Sponsor from datetime import datetime def generate_report(request, test_id): test = Test.objects.get(pk=page_id) page_type = get_type(test.type) html = render_to_string(f'pdf_templates/{report_type}/pdf_{language}.html', { 'sometext': text.user.name, }) html = HTML(string=html) result = html.write_pdf() timestamp = datetime.now().isoformat(' ', 'seconds') # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = f'attachment; filename={text.user.name} {timestamp}.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response