Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms : How to show objects in a dropbox based on the user's group(in the Django admin)
I have a list of all categories mentioned in the models.py. I'm trying to filter categories based on the group defined in django admin. Can somebody suggest me how to get this done. Please let me know if you need anymore info. Thanks in advance for your inputs. models.py class Post(models.Model): # No Role Required WATCHLIST = "Watchlist" LESSON = "Lesson/Review" GENERAL = "General" # Blogger Role Required ANALYSIS = "Analysis" MILESTONE = "Milestone" FEATURES = "Features" TUTORIALS = "Tutorials" CAREERS = "Careers" COMMUNITY = "Community" # Founder Role Required # FOUNDER = "Founders Journey" CATEGORY_CHOICES = [ # No Role Required (WATCHLIST, "Watchlist"), (LESSON, "Lesson/Review"), (GENERAL, "General"), # Blogger Role Required (ANALYSIS, 'Analysis'), (MILESTONE, "Milestone"), (FEATURES, "Features"), (TUTORIALS, "Tutorials"), (CAREERS, "Careers"), (COMMUNITY, "Community"), ] forms.py class Meta: model = Post fields = [ "title", # "slug", "category", "associated_portfolios", "body", # "created_on", # "allow_comments", ] exclude = ('allow_comments',) # widgets = { # 'symbol': autocomplete.ModelSelect2Multiple(url='symbol-autocomplete'), # } def __init__(self, *args, **kwargs): super(PostCreateForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): if field.widget.attrs.get("class"): field.widget.attrs["class"] += " form-control" else: field.widget.attrs["class"] = "form-control" -
Write django query to select users and order users by latest conversation they had?
My models: class User(models.Model): id = models.UUIDField(primary_key=True) first_name = models.Charfield() class Conversation(models.Model): id = models.UUIDField(primary_key=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Message(models.Model): id = models.UUIDField(primary_key=True) conversation = models.ForeignKey(Conversation, on_delete=models.PROTECT, null=False) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, blank=True) I tried to to order by adding annotate and adding order by. Can some body help me to select all users and order them by the latest message they had. I need user with latest message at to and then accordingly. -
Django - Different user types in a DetailView
I have two user types: Buyer and Merchant and I want to display in a page details of the selected user but a detail view can only use one model My models class User(AbstractUser): is_buyer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_moderator = models.BooleanField(default=False) pgp = models.CharField(max_length=150, blank=True) date_created = models.DateTimeField(default=timezone.now) class Merchant(models.Model): # items user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return f'{self.user.username}' class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pin = models.CharField(max_length=6, blank=True) def __str__(self): return f'{self.user.username}' My views class ProfileDetailView(DetailView): model = User template_name = 'users/profile.html' slug_field = 'username' slug_url_kwarg = 'username' My template and url {% extends 'base.html' %} {% block content %} <article> <div> <p>{{ object.pgp }}</p> </div> </article> {% endblock %} path('profile/<str:username>', usersViews.ProfileDetailView.as_view(), name='user-profile'), The only thing that seems to work on the template is object.username, if I try using other names it wont show. What should I do? Create another model Profile? Change my current view or model? -
How can we merge two BytesIO buffer of video and audio into a single BytesIO object
I am using pytube which helps to download YouTube videos. It downloads videos with audio up to 720px after this resolution, it splits audio and video files separately to maintain quality. I want to merge those bytes objects into a single bytes object which can be downloaded. I have tried this from another StackOverflow question. import ffmpeg from io import BytesIO from pytube import YouTube def download_video(request): buffer=BytesIO() yt_test = YouTube(video_url) video = yt_test.streams.get_by_itag(137) input_video = ffmpeg.input(video) audio = yt_test.streams.get_by_itag(137) input_audio = ffmpeg.input(audio) combined = ffmpeg.concat(input_video, input_audio, v=1, a=1) combined.stream_to_buffer(buffer) buffer.seek(0) but this gives an error. Error: AttributeError: 'FilterableStream' object has no attribute 'stream_to_buffer' SO, I want to ask if there is any way that I can directly merge those audio and video bytes buffer using FFmpeg only or by another method so that I can further use that for download and other things according to my use case. -
Custom button in Django Admin page, that when clicked, will change the field of the model to True
I have a sample model in my Django App: class CustomerInformation(models.Model): # CustomerInformation Schema name=models.CharField(max_length=200, verbose_name="Name",default="Default Name") login_url=models.URLField(max_length=200, verbose_name="Login URL",default="") is_test=models.BooleanField(default=False,verbose_name="Test") I have to create a button on the Django Admin page for each entry of the model (which I have) that says "Test Integration", like this: [Screenshot of admin page Now once I click the button, the 'is_test' value for that specific CustomerInformation model, should be True. I haven't been able to do that so far. Here's what I have tried so far, thanks to Haki Benita's blog postBlog here: # admin.py class CustomerAdmin(admin.ModelAdmin): list_display = ( 'name', 'username', 'account_actions' ) def get_urls(self): urls = super().get_urls() custom_urls = [ url( r'^(?P<account_id>.+)/test_integration/$', self.admin_site.admin_view(self.test_integration), name='test-integration', ) ] return custom_urls + urls def test_integration(self, request, account_id, *args, **kwargs): return self.process_action( request=request, account_id=account_id ) def process_action(self,request,account_id): pass def account_actions(self, obj): return format_html( '<a class="button" href={}>Test Integration</a>', reverse('admin:test-integration', args=[obj.pk]), ) account_actions.short_description = 'Account Actions' account_actions.allow_tags = True I realize that I have to do something with the process_action and test_integration methods in this class to execute what I am wanting to do, but as a Django Beginner, I'm kinda lost. Any suggestions? Thank you so much!! -
sending scheduled emails over django
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) and I want to send an email to all Users who have joined a particular Group 30 minutes before the start_time. For example: if a Group has a start_time of 1:00 PM, I want to send an email to all the joined Users at 12:30 PM, letting them know the group will be meeting soon. I've used the send_mail() function for other types of email notifications (like when a User joins or creates a Group) but I can't figure out how to send an email based on the start_time of Group. I've seen people say Celery is a way to do this, but I'm having trouble figuring out how to implement it in my django project. Will it conflict with the other email settings I already have? # Email settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = NOTIFICATION_EMAIL EMAIL_HOST_PASSWORD = NOTIFICATION_PASSWORD EMAIL_USE_TLS = True Is there a specific function I need to write and then call it in my Group model? Or do I call it in a view? … -
User bookings not appearing when logged in
me again. I still can't seem to get my user bookings to appear when the user is logged in. I know it is probably something super basic but I am just not seeing it. Here is the code I have written so far. I feel like a new set of eyes on this might help as I have been staring at it for days now. Thank you in advance for any help you can give. HTML: {% extends "base.html" %} {% block content %} <section id="booking" class="book_a_table"> <div class="booking_container"> <h2>My Bookings:</h2> <p>To edit or cancel a booking please click on the buttons below.</p> <div class="row"> <div class="col-md-3 mt-5 offset-md-3"> {% for booking in bookings %} <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <h4 class='card-title text-uppercase text-center'>{{ booking.date }} at {{ booking.time }}</h4> <h6 class="text-uppercase">{{ booking.name }}</h6> <div class='card-text'> <p><i class="fas fa-phone"></i> {{ bookings.phone }}</p> <p><i class="far fa-envelope"></i> {{ bookings.email }}</p> <p>Number of People: {{ bookings.number_of_people }}</p> {%endfor%} </div> </div> </div> </section> View.py: class ListBookingView(generic.ListView): """ This is the view that will bring up the list of bookings for a particular users so that they can be edited or deleted """ model = Booking template_name = 'my_bookings.html' def get(self, request, *args, … -
Demo user accounts with dj-rest-auth
I need to have a demo account for my app. I'm using the stock views from dj-rest-auth to handle login, registration etc. How would I go about doing this? I want the user to click a button on the front end and sign in to this account without inputting credentials. -
Calling ModelViewset create() from another python file?
I would really appreciate some advice on this particular challenge I'm facing. I am using IMAP to receive emails ( on emails.py) and need to have some of the data in the email messages to be posted on an existing API endpoint (using DRF) and saved in my database. so far, I have come up with two ideas. Call the ModelViewSet create() method from emails.py. But I'm assuming that I would need to make sure that the request object is exactly the same as the one that is generated when an HTTP post request is made from the frontend. I'm afraid the metadata can get too complicated and leave room for messy errors. class RequestView(viewsets.ModelViewSet): serializer_class = RequestSerializer def get_queryset(self): queryset = Request.objects.all().select_related('user_id') user_id = self.request.query_params.get('user_id') if user_id is not None: queryset = Request.objects.filter(user_id=user_id).order_by('id') return queryset def create(self, request): # enter code here return super().create(request) Or I can make an HTTP request from emails.py. Does it make sense to have HTTP client code in a server-side framework? Per my research, I can use Python's requests library. Any input/advice would be greatly appreciated! -
I getting an error, 'QueryDict' object has no attribute 'user'
I've made a form to store customer feedback, It's working fine. Now my motive is that, create a update feedback form so that a user can be able to update their feedback. I also have made a feedback form, but it's not working perfectly. It shows an error😢. Please check the UpdateFeedback view. Where did the actual problem occur? Please give me the relevant solution... views.py: It's working fine made for storing the feedback. def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK'), ) messages.success(request,"Thanks for your feedback.") return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) but the problem is here. It's not working perfectly. def UpdateFeedback(request, id): feedback = ProductREVIEWS.objects.get(pk=id) product_id = feedback.product.id reviewers = feedback.user if request.method == "POST": form = UpdateFeedback(request.POST) if form.is_valid() and reviewers.id == request.user.id: UpdateFeedback(request.POST) feedBACK = form.cleaned_data.get('UpdateFeedBACK') feedback.feedBACK = feedBACK feedback.save() messages.success(request, "Comment updated") return redirect('quick_view', product_id) forms.py for UpdateFeedback: class UpdateFeedback(forms.ModelForm): class Meta: model = ProductREVIEWS fields = ('feedBACK') labels = { 'feedBACK':'Change Your View' } widgets = { 'rating':forms.NumberInput(attrs={'class':'form-control', 'style':'font-size:13px;'}), 'feedBACK':forms.Textarea(attrs={'class':'form-control', 'style':'font-size:13px;'}) } models.py: class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) urls.py: path("feedBack/<int:quick_view_id>/", … -
How can I redirect users to different pages based on session data in python
I'm new to django and wanted some guidance on my project. I want to create a web application for managing traffic violations. Where do I have to start?enter image description here Here is an example of analysis generated with windev. -
How to create Workspaces and manage them for all the users in Django?
I have a complete Login and Registration system in my Django app, that lets me register users, log in users, logout users, change passwords, reset passwords, invite users. I have all the basic functionality. I want now to have Workspaces for users, as per following points: There will be a workspace admin of each workspace. Workspace admins can only add/remove (register/delete) users to his own workspaces. Users can react to (log in to) only those workspaces to which they have been added. A superuser (main admin) can manage all workspaces, all workspaces-admins and all users. How do I accomplish this? You can say this is similar to a Slack thing. I just need a guidelines/roadmap and I will implement it myself. I have already created a Workspace Model, which looks like below: class Workspace(models.Model): name = models.CharField(max_length=254) created_at = models.DateTimeField(auto_now_add=True) def make_admin(self, user): user.is_workspace_admin = True user.save() def remove_admin(self, user): user.is_workspace_admin = False user.save() and my User model has following two attributes beside other default Django fields: class User(AbstractBaseUser, PermissionsMixin): is_workspace_admin = models.BooleanField(default=True) workspaces = models.ManyToManyField(Workspace) Is this approach correct? If not please guide me to the proper way. BTW, using this approach, I can add/assign workspaces to any user, … -
Show An Alert message Before Submitting the Page Django
I want to create a alert message before submitting the page , my admin py class NameAdmin(MasterDataBaseAdmin): form = forms.NameForm inlines = [AddressInline, RegistrationTypeInline] queryset = models.Name.objects.prefetch_related( "names", "name__id", "registrationstype" ) views.py class NameViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Country.objects.supported().prefetch_related("names", "registrationstype") serializer_class = serializers.NameSerializer I want to just add this meesage in the Message Box "Are You Sure You Want To Save The Page!" -
How to make Django messages framework play nicely with i18n?
Using django 4.0.6 I was using the messages framework to display messages when users successfully completed a form. Then I added i18n: When the default language is selected, messages are shown on the second screen after the form is submitted, not the first. When the not-default language is active, untranslated messages are shown, on the first screen after the message is created (as expected). I've tried using both gettext_lazy and gettext and it didnt help. Its an unusual bug and Im not sure what I've done wrong? views: from django.utils.translation import gettext_lazy as _ from django.views.generic.edit import CreateView ... class ContactView(SuccessMessageMixin, CreateView): template_name = "contact-form.html" form_class = ContactForm success_url = reverse_lazy("base:home") success_message = _("Thanks for contacting us.") def form_valid(self, form): if contact_form_filter(form): create_and_send_contact_form_email(form) return super().form_valid(form) def form_invalid(self, form): """If the form is invalid, render the invalid form.""" return self.render_to_response(self.get_context_data(form=form)) settings: TIME_ZONE = "CET" LANGUAGE_CODE = "en" USE_I18N = True WAGTAIL_I18N_ENABLED = True USE_L10N = True # Deprecated in Django 4, but still used in Wagtail I believe USE_TZ = True WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [ ("en", _("English")), ("nl", _("Dutch")), ] INSTALLED_APPS = [ ... "django.contrib.messages", ... ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.cache.UpdateCacheMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.cache.FetchFromCacheMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", … -
How Do I design my Model and Serializer for Api?
I got this image as an UI Here there is the question topic, below there is a question and the user needs to provide the answer. There could be around 5-6 questions and user need to fill all question else validation error or incomplete form error is raised. I have thought of this way. class ModelQuestions(BaseModel): MODEL_CATEGORY_CHOICES = ( ('Circumstances', 'Circumstances'), ('Thoughts', 'Thoughts'), ('Feelings', 'Feelings'), ('Action', 'Action'), ('Result', 'Result')) model_subcategory = models.CharField(max_length=50, choices=MODEL_CATEGORY_CHOICES) questions = models.CharField(max_length=200) def __str__(self): return self.model_subcategory class ModelAnswer(BaseModel): questions = models.ForeignKey( to=ModelQuestions, on_delete=models.CASCADE ) answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.questions} - by {self.user.fullname}' is the database design correct? how do I write my serializer in order to validate that all forms are filled? any hint will be very special. -
Django rest framework - generate TOTP and serialize it?
I am not sure how to do this: I want create an end point where an authenticated user can click to get a TOTP. The function which I have used as a separate file: # gen_totp.py import hmac, base64, struct, hashlib, time def get_hotp_token(secret, intervals_no): key = base64.b32decode(secret, True) msg = struct.pack(">Q", intervals_no) h = hmac.new(key, msg, hashlib.sha1).digest() o = h[19] & 15 h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000 return h def get_totp_token(secret): return get_hotp_token(secret, intervals_no=int(time.time())//30) Then to serialize: from re import U from rest_framework import serializers # totp serializer class totp_serializer(serializers.Serializer): totp = serializers.IntegerField(get_totp_token()) I am stumped on how to provide secret to get_totp_token() in the totp_serializer. -
Is there any way to encrypt the URL that is shown to the user in the browser to prevent link sharing?
I am looking for a way to encrypt the URL that is displayed to the user to prevent link sharing between users. This way I would be forcing the user to go through certain steps to access a certain path. I am using the Django Framework and everything I have seen so far for encrypting the URL is in regards to hiding paths, however the URL is still valid and can be shared. In my case I want to show the user an invalid URL in the browser after the request with the valid URL has already been made. Any suggestions for this? -
Need help in django model
I have written a model for my django project. This is my model from django.utils.translation import ugettext_lazy as _ from django.db import models from django.utils.crypto import get_random_string from django.db import models from django.contrib.auth.models import( BaseUserManager, AbstractBaseUser, PermissionsMixin, ) def generate_vid(): """Generates a vid for the users""" not_unique = True while not_unique: vid = get_random_string(10, 'abcdefg0123456789') if not User.objects.filter(v_id = vid).exists(): not_unique=False return vid class UserManager(BaseUserManager): """Model for user manager""" def create_user(self, username, password, **params): """Create and return a user""" u_type = params.pop('usertype','v') params.update({'usertype':u_type}) p_username = params.pop('parent_username', 0) if(u_type=='v'): pass else: parent_id = User.objects.filter(username = p_username).values_list('v_id') params.update({'parent_id': parent_id}) user = self.model(username=username, **params) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **params): """Create and return a user""" params.setdefault('is_staff',True) params.setdefault('is_superuser',True) params.setdefault('is_active',True) if params.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if params.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(username, password, **params) class User(AbstractBaseUser, PermissionsMixin): """Models for user""" v_id = models.CharField( max_length=10, default=generate_vid, primary_key = True, ) username = models.CharField(max_length=20, unique=True) email = models.EmailField(blank=True, unique = True) parent_id = models.ForeignKey('User', on_delete=models.SET_DEFAULT, default=0) usertype = models.CharField(max_length=1, choices=[('f', 'family'), ('v', 'veteran')]) REQUIRED_FIELDS = ['usertype'] is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'username' objects = UserManager() def __str__(self): return self.username Now I … -
Error in postgresql from sqlite during django project creation
I got an error when I changed sqlite to postgresql while making an app with django. Shows the error that occurred. conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } -
DJANGO REST KNOX EXPIRED
I use django rest knox I would not like my session to expire when using my app 'SECURE_HASH_ALGORITHM': 'cryptography.hazmat.primitives.hashes.SHA512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=0.0166667), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': True, # 'EXPIRY_DATETIME_FORMAT': api_settings.DATETME_FORMAT }``` -
how do I run a beta and production version of a django-project alongside each other?
What is the recommended way to run a "beta server" alongside the production server for a django project? I think about setting up a beta.mydomain.com alongside mydomain.com... Can I just make a second project folder, git pull the beta branch there and run it somehow in nginx? Is it possible to divide the nginx requests this way to two "different" projects? -
Populating django m2m field with another model's id
I'm trying to add a new m2m field in my model's serializer but i want the ids to be from another model. voting_members = serializers.PrimaryKeyRelatedField(queryset=Person.objects.all(), many=True) However this throws an assertion error: The field 'voting_member' was declared on serializer NccnPanelSerializer, but has not been included in the 'fields' option. Is there a way to assign another model's ids to a different model serializer's field? -
Id instead of String when displaying foreign key field in DRF
I'm trying to return the name of the "pricing" field but all i get is its foreign key id instead. What am i doing wrong here? Any information on this would be greatly appreciated. I looked at some similiar issues on here but i didn't find anything that resembled my situation. class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ( "assignedteams", "agent", "facility", "organisor", "avatar", ) class UserSubscriptionSerializer(serializers.ModelSerializer): class Meta: model = Subscription fields = ( "user", "pricing", "status", ) class UserSerializer(UserDetailsSerializer): profile = UserProfileSerializer(source="userprofile") subscription = UserSubscriptionSerializer(source="usersubscription") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('profile', 'subscription',) def update(self, instance, validated_data): userprofile_serializer = self.fields['profile'] userprofile_instance = instance.userprofile userprofile_data = validated_data.pop('userprofile', {}) usersubscription_serializer = self.fields['subscription'] usersubscription_instance = instance.usersubscription usersubscription_data = validated_data.pop('usersubscription', {}) # update the userprofile fields userprofile_serializer.update(userprofile_instance, userprofile_data) usersubscription_serializer.update(usersubscription_instance, usersubscription_data) instance = super().update(instance, validated_data) return instance -
django template html how to use filter with a context value as a string argument of that filter
i'm try to do smthing like this: {% for i in list %} <td style="background-color: {{color_rule|get_item:i}}">{{i}}</td> {% endfor %} where: def get_item(dictionary, key): return dictionary.get(key) please help -
How to convert between models in django-polymorphic?
I'm using django-polymorphic to model a simple relationship like this: from polymorphic.models import PolymorphicModel class Base(PolymorphicModel): pass class DescendantA(Base): pass class DescendantB(Base): pass I would like to find a way to convert an instance of DescendantA to an instance of DescendantB while keeping the data of its Base part (specifically the primary key). Setting the appropriate __class__ and polymorphic_ctype attributes on the instance (see this answer) works mostly but predictably results in inconsistent data: The database row for DescendantA will not be deleted and continues pointing to the Base row. Is there a clean(er) way to achieve this conversion? I'm inclined to just create a new instance and copy the original data but I hope there's a better way.