Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trigger image upload to s3 from django app when new account is created
When a user creates a new account on my website, an image is created(generated) and is supposed to be uploaded to s3. The image is successfully created(verified by running the ls command on the server in the media directory) but it's not getting uploaded to s3. However, when I try uploading an image for a user account from the admin panel, changes are correctly reflected in s3 (i.e newly uploaded image from admin panel is shown in s3 bucket's directory). I aim to auto-upload the generated image to the s3 bucket when a new account is created. views.py def signup(request): if request.method == "POST": base_form = UserForm(data=request.POST) addnl_form = AddnlForm(data=request.POST) if base_form.is_valid() and addnl_form.is_valid(): usrnm = base_form.cleaned_data['username'] if UserModel.objects.filter(user__username=usrnm).count()==0: user = base_form.save() user.set_password(user.password) user.save() #print(img) addnl = addnl_form.save(commit=False ) addnl.user = user img = qr.make_image() #create a qr code image, full code not included. img.save('media/qrcodes/%s.png'%usrnm) addnl.qr_gen = 'qrcodes/%s.png'%usrnm addnl.save() else: messages.error(request,base_form.errors,addnl_form.errors) else: base_form = UserForm() addnl_form = AddnlForm() return render(request,'app/signup.html',{'base_form':base_form,'addnl_form':addnl_form} ) models.py class UserModel(models.Model): . . . qr_gen = models.ImageField(upload_to='qrcodes',default=None,null=True,blank=True) settings.py DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage' storage_backend.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False Please help me find a solution to this problem. -
can't login with normal user account in django
I'm workin on an app where I have a personalized User model, I can use the superuser to login but when I try with a normal user I get error of wrong password and user name. when I look to data of the user I find that the password of normal users isn't hashed. The models definition models.py: from django.db import models from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.gis.db import models as gis_models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import EmployeeManager class Employee(AbstractBaseUser, PermissionsMixin): PERMANENT = 'Per.' TEMPORAIRE = 'Tem.' VIREMENT = 'Vir' ESPECES = 'Esp' TYPE_OF_CONTRACT = [ (TEMPORAIRE,'Temporaire'), (PERMANENT,'Permanent'), ] PAYMENT_MODE = [ (VIREMENT,'Virement'), (ESPECES,'Especes'), ] first_name = models.CharField(max_length=128, blank=False, null=False) last_name = models.CharField(max_length=128, blank=False, null=False) registration_number = models.PositiveSmallIntegerField(unique=True, blank=False, null=False) email = models.EmailField() driving_licence = models.PositiveIntegerField(blank=True, null=True) recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) phone = PhoneNumberField(blank=True, help_text='numéro de telephone', null=True) is_exploitation_admin = models.BooleanField(default=False) is_supervisor = models.BooleanField(default=False) is_controlor = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) USERNAME_FIELD = 'registration_number' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] objects = EmployeeManager() def __str__(self): return (self.first_name) class Supervisor(Employee): zone_name = models.CharField(max_length=128, blank=True) def __str__(self): return (self.last_name) the template of the login is: {% extends 'Drivers_App_Management/base.html' %} … -
Aldatılıyorum ne yapmalıyım?
Aldatılıyorum! Ne yapmalıyım? diyorsanız bu yazı tamda sizin için hazılandı. Ülkemizde aldatılan, ihaneti kanıtlamaya çalışan ve aldatıldığını ispat etmek isteyen insanlar yadırganamayacak kadar fazla. İhanete uğramak, aldatılmak dünyanın en kötü hislerinden biri olsa gerek. Sevdiğiniz ve güvendiğiniz insanlardan asla bir aldatılmayı beklemeseniz de; dünyada ne kadar çok sayıda insanın başına geldiğini bilseniz çok şaşırırdınız. Ne yazık ki aldatılan, ihanete uğrayan kişi, gerçekleri en son öğrenen oluyor. Aldatılan kişinin dünyası başına yıkılıyor, kendini ve ilişkisini sorgulamaya başlıyor. Sıklıkla suçluluk duyguları, öfke de hissedilen duygular arasında oluyor. Oysa ki aldatılmak herkersin yaşayabileceği bir olay. Aldatmanın güzeli çirkini, genci yaşlısı, kadını erkeği olmuyor. Her zaman her insanın başına gelebilir. Aldatılma nedeni ile boşanma istatistiklerine bakıldığında, geniş bir insan profilini kapsadığını daha iyi görebiliriz. O yüzden ben aldatıldım diye üzülmenize ve eksikliği kendinizde aramanıza gerek yok. Ancak gerçek olan bir şey var ki, o da herkesin hayatındaki gerçekleri bilme hakkı. Gerçekleri bildiğiniz zaman, hayatınızın bundan sonrasına nasıl ve kiminle devam edeceğinize karar vermeniz de kolaylaşır. Kanunlara göre evli iseniz sadakatsizliği öğrendiğiniz süreden 6 ay içinde, daha sonra öğrendiyseniz de 5 ay içinde boşanma davası açma hakkınız vardır. Siz de hayatınızdaki kişinin gizli gizli aldatıldığınızdan mı şüpheleniyorsunuz? İşinin ehli, profesyonel aldatma ispatı hizmeti için özel … -
chat socket closed unexpectedly
I'm truly sorry, I do not know how I share code here. Hello.. I watched the video of making chat application from youtube with django. Even though I follow the same procedures there, I am getting an error. When I try send a message... click button(message look like send but... no) and then message doesn't show up page.. and I click F12 , and consele say like this; Error Like; Chat socket closed unexpectedly.. Would anyone help me please? Thx <3 HERE CODES; Project = justchat (python manage.py startproject justchat) app = chat (python manage.py startapp chat) my setting.py ; (I'll just show the things I added) enter code here STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] WSGI_APPLICATION = 'justchat.wsgi.application' ASGI_APPLICATION = 'justchat.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } and of course I added APPLICATIONS.. 'chat' and 'channels' justchat/routing.py; enter code here import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'justchat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) }) justchat/asgi.py enter code here import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing … -
How do I parameterize the django url using router.register?
I am newbie in Django. So this might be a trivial question. I have been been building urlpatterns as following router = DefaultRouter() router.register('posts', views.PostViewSet) urlpatterns = [ path('', include(router.urls)) ] This creates URLs like api/posts and so on. Now, I am trying to add a voting model to this.. For which I want to create URL like api/posts/<id>/vote But I don't want to create a path like urlpatterns = [ path('', include(router.urls)), path('posts/<int:pk>/vote', views.SomeView) ] Is there a way to do this via router.register way? -
Update an order after POST method Django Rest Framework
I just started learning Django Rest Framework together with React and i am stuck on this problem for a couple of weeks now. Hope you guys can help me out.. Here's what i am trying to achieve: When a user clicks on 'Buy Now' there will be an order created with the status of the order set to open. This all works fine. My Orders model looks like this: class Orders(models.Model): userID = models.CharField(max_length=30) pakket = models.CharField(max_length=30) price = models.CharField(max_length=30) created_at = models.DateTimeField(default=one_hour_later) status = models.CharField(max_length=30) orderID = models.CharField(max_length=30) user = models.EmailField(max_length=120) def __str__(self): return self.user My serializer called OrdersSerializer looks like this: class OrdersSerializer(serializers.ModelSerializer): class Meta: model = Orders fields = '__all__' read_only_fields = ('user','status','orderID','userID') After the status of the order has changed (the user made the purchase or not) my webhook is called (a POST) and i am retreiving the order by the id which is POSTED to the webhook. This is all taken care of by using an API client (mollie_client). This all works fine too. My View looks like this: class OrderStatusView(ListCreateAPIView): serializer_class = OrdersSerializer queryset = Orders.objects.all() permission_classes = [AllowAny,] def post(self, request): data = request.data payment_id = data['id'] payment = mollie_client.payments.get(payment_id) if payment.is_paid(): return … -
How to add check on admin side actions in django?
Here i'm using django latest verion which is 3.1.4 and I just want to add condition in django admin side. I just wanted to return some text in terminal if i update my model from admin panel. In my case user submit kyc form admin person approved that form user will get notification on approval. (Right now I just want to print some message when admin update his kyc by updating his kyc form by updated approved boolean field. In short Just wanted to show message when admin updates any model in django admin side. admin.py class KycAdmin(admin.ModelAdmin): list_display = ['__str__','owner'] class Meta: model = KycModel def post(self,request): response = "i'm updated" print(vu) return vu admin.site.register(KycModel,KycAdmin) If more detail is require then you can just tell me in a comments. -
key error : command ,chatroom with django
i have i working chat room with django and jquery, but if i refresh the page i loose all messages, to prevent that i added a model (following a tutorial) and for this i start to modify in my consumers.py like class ChatConsumer(WebsocketConsumer): def get_messages(self, data): **print('you got the message')** pass def new_message(self, data): pass **commands** = { 'get_messages': get_messages, 'new_message': new_message } def connect(self): self.user = self.scope['user'] self.id = self.scope['url_route']['kwargs']['course_id'] self.room_group_name = 'chat_%s' % self.id # join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name) # accept connection self.accept() def disconnect(self, close_code): # leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name) # receive message from WebSocket **def receive(self, text_data):** **text_data_json = json.loads(text_data)** **self.commands[data['command']](self, data)** def send_chat_message(self, message): now = timezone.now() # send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': self.user.username, 'datetime': now.isoformat(), } ) # receive message from room group def chat_message(self, event): # Send message to WebSocket self.send(text_data=json.dumps(event)) just for the sake of seeing if my modifications are adding up, i runserver, if there is no problem i would see the message printing in my prompt (not the actual chat room, since its still not functionnal yet), but i get an error saying Errorkey: command, note! i test … -
Django - unable to pass user context to model form on class based Updateviews
Appreciate the help in advance guys. I am having some issues passing context from my class based UpdateView to django Model form. I am able to create new records and pass user context but when i try the same method for update view, it is failing. Note that my model has some Many-to-Many fields so in my forms, i am filtering the data on the dropdown based on specific criteria and using ajax in html to render it. #View class campaign_drive_update(SuccessMessageMixin, UpdateView): model = CampaignDrive form_class = campaign_drive_add template_name = 'campaignmanagement/campaign_drive_add.html' success_url = reverse_lazy('campaign_drive_add') success_message = "Record was created successfully" def get_form_kwargs(self): kwargs = super(campaign_drive_update, self).get_form_kwargs() kwargs['request']=self.request return kwargs form class campaign_drive_add(forms.ModelForm): def __init__(self, *args, **kwargs): """ Grants access to the request object so that only members of the current user are given as options""" self.request = kwargs.pop('request') super(campaign_drive_add, self).__init__(*args, **kwargs) self.fields['associated_location'].queryset = NonProfit_location.objects.filter( associated_nonprofit=self.request.user.user_nonprofit.id) self.fields['associated_company'].queryset = Company.objects.filter( linking=self.request.user.user_nonprofit.id) self.fields['associated_campaign_type'].queryset = CampaignType.objects.filter( associated_nonprofit=self.request.user.user_nonprofit.id) self.fields['existing_contact_id'].queryset = Contact.objects.filter( associated_nonprofit=self.request.user.user_nonprofit.id) self.fields['request_status'].queryset=RequestStatus.objects.filter(viewable_to_ops=True) # self.fields['associated_campaign_id'].queryset = Campaign.objects.none() -
Login probleme django 3
I have a problem to login to my app where I have a personalized User, the superuser can login with no probleme, but when I try with a normal user I get an error. I'm using Django 3. the code for my app: admin.py from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from .forms import EmployeeCreationForm, EmployeeChangeForm, ControlorCreationForm, ControlorChangeForm from .models import * class EmployeeAdmin(UserAdmin): add_form = EmployeeCreationForm form = EmployeeChangeForm model = Employee list_display = ('registration_number', 'first_name', 'last_name', 'email', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver', 'is_staff',) list_filter = ('registration_number', 'email', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver',) fieldsets = ( (None, {'fields': ('registration_number', 'email', 'password')}), ('Permissions', {'fields': ('is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver', 'is_staff')}), ('Personal', {'fields': ('city_id', 'region_id')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('registration_number', 'first_name', 'last_name', 'email', 'password', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver', 'is_staff')} ), ) search_fields = ('email','registration_number', 'first_name','last_name') ordering = ('registration_number', 'last_name') admin.site.register(Employee, EmployeeAdmin) admin.site.register([Controlor, Driver, Supervisor, Vehicle, Region, City, GazStation]) and the manager.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class EmployeeManager(BaseUserManager): def create_user(self, email, first_name, last_name, password, registration_number, **extra_fields): if not last_name: raise ValueError(_('Le nom est … -
Why I can't print the session variable in this Django example application?
I am following this Mozzilla's articles related about how to build a Django application and I am finding the following problem related to session, this is the specific article: https://developer.mozilla.org/it/docs/Learn/Server-side/Django/Sessions Into my Django portal I have: I have enabled sessions into locallibrary/locallibrary/settings.py file, infact I have set: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog.apps.CatalogConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Then this is my index view function code defined into the view.py file: def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) As you ca see I defined these linese related to session: # Number of visits to this view, as counted in the session variable. … -
Remove wagtail from django app, and wagtail db tables from postgres
How do I go about removing an errant wagtail install from a django project. Actually, I just want to remove the postgres tables. I accidentally was pointing to a wrong secrets file and used a database for another django project, so I have wagtail tables. I can easily drop the wagtail tables, but are there other things I need to drop? I'm thinking my django_migrations table has info I shouldn't have. -
Why the 'post' method is not working in my django app?
I am using Django to develop a blog and when I wanted to get the contact informations, the post request seems not working at all. In the contacts view I don't do much I just wanted to make sure that the post request is working but it returns a Get request instead and the get method is working really fine the javascript file //CONTACT FORM $('#contactform').submit(function(){ var action = $(this).attr('action'); $("#message").slideUp(750,function() { $('#message').hide(); $('#submit').attr('disabled','disabled'); $.post(action, { name: $('#name').val(), email: $('#email').val(), comments: $('#comments').val() }, function(data){ document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#submit').removeAttr('disabled'); if(data.match('success') != null) $('#contactform').slideUp('slow'); $(window).trigger('resize'); } ); }); return false; }); view.py from django.http.response import HttpResponse from contact.forms import ContactForm from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt @csrf_exempt # Create your views here. def contacts(request): if request.method == "POST" and request.is_ajax: print('hello!!') return render(request, 'contact/contact.html') forms.py from django import forms from .models import Contact class ContactForm(forms.Form): class Meta: model = Contact fields = ['cont_name', 'cont_email', 'cont_message', 'cont_date'] models.py from django.db import models from datetime import datetime class Contact(models.Model): cont_name = models.CharField( max_length = 10) cont_email = models.EmailField() cont_message = models.TextField(blank=False) cont_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.cont_name contact.html <div class="container"> <div class="row"> <div class="col-md-6"> <p class="lead">Sold old ten are … -
Django/Python unable to find GDAL Library
I have installed GDAL in a virtual environement with the following commands: $ brew install gdal $ pip3 install gdal When trying a python manage.py makemigrations or python manage.py runserver (or whatever) on the website code for which I installed it, I'm running into the following error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I'm struggling to find good information on how to solve it. I'm using MacOS Catalina. I have no experiences with GDAL, at this stage I just need to install it properly to make the website run on my machine and start contributing to the code. Any help would be appreciated. -
how can I access Django rest framework using ajax
I am trying to get a form from the rest framework using ajax I already tried the ajax get method on other thing and it worked for me now I am trying to use the POST method to grab the form but i am facing difficulties my current HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="NONE,NOARCHIVE" /> <title>Create a Recipe</title> </head> <body class=""> </body> {%endblock%} </html> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script> var data = {title:'title',tags:'tags',ingredients:'ingredients',time_minutes:'time_minutes'} $.ajax({ type: 'POST', data: data, url: '/api/recipe/recipes/', success: function(res){ for (const i in res) { console.log(res[i].) } }, error: function(error) { callbackErr(error,self) } }) </script> this is my current attempt on ajax form serializers.py class RecipeSerializer(serializers.ModelSerializer): """Serialize a recipe""" ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all() ) tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) class Meta: model = Recipe fields = ( 'id', 'title', 'ingredients', 'tags', 'time_minutes', 'price', 'link' ) read_only_fields = ('id',) class RecipeDetailSerializer(RecipeSerializer): """Serialize a recipe detail""" ingredients = IngredientSerializer(many=True, read_only=True) tags = TagSerializer(many=True, read_only=True) class RecipeImageSerializer(serializers.ModelSerializer): """Serializer for uploading images to recipes""" class Meta: model = Recipe fields = ('id', 'image') read_only_fields = ('id',) Models.py def recipe_image_file_path(instance, filename): """Generate file path for new … -
How to pass dictionry in view using django
i begin to learn django i woud like to pass dictionry in view.py but in browser i get this AttributeError at /accuiel/ 'list' object has no attribute 'get' enter image description here -
DRF Could not resolve URL for hyperlinked relationship using view name on PrimaryKeyRelatedField
I have a frustrating problem with POST requests on a DRF serializer - DRF is, for some reason, going to an incorrect view name, and view_name is not a settable property on PrimaryKeyRelated Field. Models: (the class with the issue) class Section(models.Model): teacher = models.ManyToManyField(Teacher) (a class that works, using the same pattern) class Assessment(models.Model): standards = models.ManyToManyField(Standard) Serializers: (doesn't work) class SectionInfoSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="gbook:section-detail") teacher = BasicTeacherSerializer(many=True, read_only=True), teachers_id = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Teacher.objects.all(), many=True, source='teacher', allow_empty=False) class Meta: model = Section fields = '__all__' read_only_fields = ['sendEmails', 'teacher', 'course'] (works) class AssessmentSerializer(serializers.HyperlinkedModelSerializer): pk = serializers.PrimaryKeyRelatedField(read_only=True) url = serializers.HyperlinkedIdentityField(view_name="appname:assessments-detail") standards = serializers.PrimaryKeyRelatedField(read_only=True, many=True) standards_id = serializers.PrimaryKeyRelatedField(queryset=Standard.objects.all(), source='standards', write_only=True, many=True, allow_empty=False) class Meta: model = Assessment fields = '__all__' urls: router.register(r'teachers', teacher_views.TeacherViewSet, basename='teacher') router.register(r'sections', course_views.SectionViewSet) router.register(r'standards', gbook.views.standard_views.StandardViewSet, basename='standards') router.register(r'assessments', AssessmentViewSet, basename='assessments') I'm using the _id fields during POST and PUT to send the id's of the related obejcts, then serializing them. This worked great with AssessmentSerializer (and several others), but is failing for a reason that I can't figure out. Certainly, the appname is missing from the view returned in the error, but I don't know why that's happening, and why it didn't happen before. Stack trace: Internal Server Error: /appname/sections/ … -
Updating related objects django rest framework
In my django project, I have 2 relevant models: class User(AbstractUser): email = models.EmailField( verbose_name='e-mailaddress', max_length=255, unique=True) # other props not important class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #other props not important For both creating and retrieving, it is convenient to have User as a nested object in the serializer: class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.save() # because of reasons, an empty profile is created on initial save. This works, trust me d, _ = Profile.objects.update_or_create(user=user, defaults=validated_data) d.save() return d HOWEVER. One action that I want to be possible as well is to update both properties of the Profile and the User at the same time. When doing this with my serializer, serializer.is_valid() fails as the provided email is already present in the database. This also indicates that, even if the validation passes (i.e. because of an updated email address), a new User object will be created and coupled to the Profile. So my question is: How do I update properties of the profile and its related user without creating a new user? -
Django - Remove currently displayed image link In An Image Edit Form
I am using Django 2.2 for a project, I want to remove the currently displayed image link from the user update form as shown in the image below, how do I do this? image forms.py from .models import Profile class CreateUserForm(UserCreationForm): class Meta: model = get_user_model() fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] help_texts = { 'username': None, } class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['profile_pic'] -
django 3 redirect with pk in form verification
@MODS- Although it has been asked on here before I can not find a suitable answer in Django 3, please read through all I have tried before deleting Preamble: I am working through This Tutorial that is taught in Django 1, I am following it but making necessary changes for Django 3. QUESTION: I receive an error when loading my page with a form on it. HTML for the form page: {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} Base HTML: {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} urls.py from django.contrib import admin from django.urls import path , re_path #uses path and re_path for regex … -
How to update dictionary value in inside for loop using Django template
This my scenario. I have 1000 dictionaries on the list. So, I will pass the list in the Django template. In the Django template, I will iterate the list and get the dictionaries one by one. In dictionaries inside, I have an image path. So, I need to assign an empty string in the image path inside the forloop. Is it possible how to achieve this scenario?. My code {%for contact in contacts%} {{c.image}} = '' <p>{{c.image}}</p> {% endfor %} In views I will achieve this scenario. but I need to handle the Django template page. -
How can I run different projects for the same domain address?
I know very little about the deployments of projects. I want to run different projects for the same domain address. Maybe these projects can be web, desktop, etc. I use Django and Python technologies for these projects. Examples: www.companyname.com/project1/... www.companyname.com/project2/... www.companyname.com/project3/... How should I go about a problem like this in Python? I have no experience with deploy stages. What structure can be used for such a thing? How can I make this system more effective. Docker and aws are enough for such a problem? How should I go about this challenge? Thank you for replies. -
Django Elastic Search: Elastic returns nothing
I have been studying the documentation and third resources for 2 days, but I cannot solve the problem with the information output. my code: models.py: class Course(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField() owner = models.ForeignKey(UserAccount, related_name='courses_created', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True) created = models.DateTimeField( auto_now_add=True) cover = models.ImageField(upload_to='courses/', null=True, blank=True) video = models.URLField(null=True, blank=True) class Meta: verbose_name = 'Course' verbose_name_plural = 'Courses' search_indexes.py: from elasticsearch_dsl import analyzer from django_elasticsearch_dsl.registries import registry from django_elasticsearch_dsl import Document, Index, fields from courses import models as courses_models course_index = Index('courses') course_index.settings( number_of_shards=1, number_of_replicas=0 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) class CourseDocument(Document): id = fields.IntegerField(attr='id') name = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) description = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) owner = fields.IntegerField(attr='owner_id') category = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) created = fields.DateField() class Django: model = courses_models.Course serializers.py: from django_elasticsearch_dsl_drf.serializers import DocumentSerializer from courses import search_indexes as courses_documents import json from rest_framework import serializers class CourseDocumentSerializer(serializers.Serializer): id = serializers.SerializerMethodField() name = serializers.CharField() description = serializers.CharField() owner = serializers.IntegerField() created = serializers.DateField() class Meta: fields = ( 'id', 'name', 'description', 'owner', 'created', 'category' ) views.py: from django_elasticsearch_dsl_drf.constants … -
Django: Adding object using a reverse relation in ManyToMany relationship
I'm new to Django and trying to Understand the Many To Many Relationship. I've created two models Movie and Actor. One movie can have many Character and One Character can have many Movies. class Movie(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Actor(models.Model): name = models.CharField(max_length=100) movies = models.ManyToManyField(Movie) def __str__(self): return self.name Using the Relationship I can add Multiple Movies to an Actor like this : avengers = Movie(name='Avengers') avengers.save() sherlock_holmes = Movie(name='Sherlock Holmes') sherlock_holmes.save() robert_downey_jr = Actor(name='Robert Downey Jr') robert_downey_jr.save() robert_downey_jr.movies.add(avengers) robert_downey_jr.movies.add(sherlock_holmes) Now, in some cases I would like to add Actors to a Movie avengers but failing to do so. I'm doing the following : chris_evans = Actor(name='Chris Evans') chris_evans.save() avengers.actor.add(chris_evans) The error is throws : Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Movie' object has no attribute 'actor' I Understand there is not property in Movie Model called Actor I though it will work like in OneToMany Relationship but it is not. -
Rolling 12 months regardless of year in Django
How would I go about setting up a rolling 12 month period in Django without any year. I am trying to plot the academic year but the problem I am finding mainly due to my lack of knowledge is that I have to set the year in datetime The academic year runs from beginning of April to the End of March the following year, therefore the easiest way for me to calculate this I guess is to provide a rolling 12 months or to set the date regardless of the year. As always, thank you for the help.