Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
The custom domain in my django app deployed with heroku doesn't work well
I deployed my first django application with heroku. I followed the procedure to add a custom domain ( example.com) inserting it in settings in ALLOWED_HOSTS and adding the custom domain in the heroku page. If I use the custom domain I can see the page but if I go in the subpages ( for example with the heroku domain app.herokuapp.com/subpage1) it doesn't add nothing to the URL but remains always example.com instead of example.com/subpage1. How can I fix it? -
Dango-rest-auth: no password set in admin panel
I am using rest-auth. I have create an custom RegisterSerializer and a custom user model. Registration is working properly but when I check password of user in admin panel it shows 'no password set' and when try to login it is showing { "non_field_errors": [ "Unable to log in with provided credentials." ] } models.py class CustomUserManager(BaseUserManager): def _create_user(self,username, email, password, is_staff,is_admin, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, username=username, is_staff=is_staff, is_active=True, is_admin=is_admin, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,username, email, password=None, **extra_fields): return self._create_user( username, email, password, False, False, False, **extra_fields) def create_staff(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, False, False, **extra_fields) user.save(using=self._db) return user def create_admin(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser): username = CharField(_('username'), max_length=100,unique=True) email = EmailField(_('email address'), unique=True) is_staff = BooleanField(default=False) is_admin = BooleanField(default=False) is_active = BooleanField(default=True) is_superuser = BooleanField(default=False) last_login = DateTimeField(auto_now=True) date_joined = DateTimeField(auto_now_add=True) … -
Django model: join and group by first element
I have two models in Django. Columns A | ------------ id name address B ------------ ------------ Columns B | ------------ id ref name date ------------ ------------ If I would have data like this: id | name | address | B -------------------------------- 1 | one | ad. | 1 id | ref | name | date ---------------------------- 1 | 1 | one_ | 1.1.2020 2 | 1 | two_ | 1.2.2020 3 | 1 | thr_ | 1.3.2020 4 | 1 | fou_ | 1.7.2020 and I would do a join I would have (join is B to ref) id_a | name | address | B | id_b | ref | name | date --------------------------------------------------------- 1 | one | ad. | 1 | 1 | 1 | one_ | 1.1.2020 1 | one | ad. | 1 | 2 | 1 | two_ | 1.2.2020 1 | one | ad. | 1 | 3 | 1 | thr_ | 1.3.2020 1 | one | ad. | 1 | 4 | 1 | fou_ | 1.7.2020 Now I would like to group by either id_a or ref and get 'last' element (either by id_b, or date) so the end results should be: … -
for object in objects add foreignkey field bulk django
So I have this AppUser model and I want to create a send_notification function that after sending a notification to mobile via firebase SDK I want it to be added to every AppUser object as ForeignKey. Think of it like every user has notification history. The main question is how do I implement it? Which path would you take if you would write this? class AppUser(TimeStampedModel): ....... notifications = models.ForeignKey( "UserNotifications", on_delete=models.CASCADE, null=True, blank=True ) ........ I tried to write something like this for test purpose from django.utils import timezone def send_notifications(request): notification = { "title": "test title", "data": "test body", "read_date": timezone.now, "date": timezone.now, } AppUser.objects.all().update(notifications?????) -
Repeate same data in different tables OR colect data from different tables in a database
What is the best practice while coding with Django: repeate same data in different tables in a database OR do not repeat and collect them in different tables? See the example below: table1 categories column0 id column1 category table2 register column0 id column1 category.table1 column2 sales_price column3 photo table3 purchases column0 id column1 id.table2 column2 photo.table2 I'm wondering what is the best: a) Include column2 in table3 and be able to extract all information from this table b) Do not include column2 in table3 and get the photo information from column3 in the table2. Thank you! -
Django template loader cannot find template after moving to another app
I'm sure you've solved a lot of similar problems already. I decided to split old_app to new_app, so: old_app will keep Models and will be handling REST (new feature) new_app will display 'regular' views (which are all class-based btw) AND will continue to utilize old_app.models for that. In order to do that I've: splitted urls.py fixed .htmls, so now they're pointing to new_app:all_items added an entry to INSTALLED_APPS moved (and renamed) whole old_app/templates/old_app directory to new_app/templates/new_app And now, I'm getting TemplateDoesNotExist because it tries to find it in new_app/templates/old_app/modelname_list.html instead of new_app/templates/new_app/modelname_list.html What I noticed is that it works, when I add option in class derived from ListView, by explicitly giving the directory: template_name = 'new_app/modelname_list.html' (new_app.views) Why it keeps tracking old directory instead of new? -
How to change the elements of navbar of User Change Page in Django Admin with Custom User model?
Below is the picture of a User Change Page of Django Admin in which the navbar of the page is marked with red color. The name of the app under which the Custom User Model is defined is : Users And the name of the Custom User model is : Custom User So the question is how to change all 4 elements (i.e. Home,Users,Custom users,custom user) of the navbar of the User Change Page of Django admin?? -
How do we print django models object value?
Hello, everyone! So, I create models in models.py file of my django project and controllers in views.py . I wrote a function called register(request) that add a new user to my database and another called login(request) that verifies if the datas sent by the user are in my db to log him in. Brief, the problem is when I want to print the user's first name in my template, it shows to me the object in string ... Here is the login(request) function: def login(request): title = 'Connexion' if request.method == 'POST': email_sent = request.POST['email'] password_sent = request.POST['password'].encode('utf-8') global isConnected user = Users.objects.filter(email = email_sent) if user and bcrypt.checkpw(password_sent, user[0].password): if isConnected in request.session: isConnected = request.session['isConnected'] return redirect('http://localhost:8000/', {'isConnected':isConnected, 'first_name':user[0].first_name, 'last_name':user[0].first_name}) else: request.session['id'] =user[0].first_name request.session['first_name'] = user[0].first_name request.session['last_name'] = user[0].first_name request.session['phone'] = user[0].first_name isConnected = True return redirect('http://localhost:8000/', {'isConnected':isConnected, 'first_name':user[0].first_name }) else: print('Something went wrong') return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) else: return render(request, 'login.html', {'title':title, 'isConnected':isConnected }) Here is what I represent the user's first_name variable in my template: <span class="initials" style="position: relative; top: 7px; color: white;">{{ first_name }}</span> And that is it prints to me: <django.db.models.query_utils.DeferredAttribute object at 0x0000017850EE7A00>