Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model with python-docx-template
I have two Models - ReportData and Report: class ReportData(models.Model): reportname = models.CharField(max_length=25) itemname = models.CharField(max_length=50) address = models.TextField() img1 = models.ImageField(default="default.jpg" ,upload_to="report_images") img2 = models.ImageField(default="default.jpg" ,upload_to="report_images") img3 = models.ImageField(default="default.jpg" ,upload_to="report_images") date_created = models.DateTimeField(default=timezone.now) preparedby = models.ForeignKey(User, on_delete=models.CASCADE) class Report(models.Model): report = models.OnetoOneField(ReportData, on_delete=models.CASCADE,primary_key=True) document = models.FileField(upload_to='reports/') I want to perform a function using all the fields of ReportData (except preparedby,date_created) which will return a file and store in document field of Report class. The function is here: doc = DocxTemplate('--default path of template file--') context = { 'rname' : ReportData.reportname,'iname':ReportData.itemname , 'addr': ReportData.address, 'img1': InlineImage(doc, ReportData.img1.url , width=Inches(7.1)), 'img2':InlineImage(doc, ReportData.img2.url, width=Inches(4.79)), 'img3':InlineImage(doc, ReportData.img3.url, width=Inches(1.91))} doc.render(context) doc.save('destination path') I dont know what will go in destination path as I want to store it in document field of Report class. Also have no idea how to get ReportData fields in context. -
how to arrange the template tags in django templates for Default user registration page with extra fields
I am beginner for django. When i am registering the details by using registration form which is not saving into database. Basically for this i am using the default User model for that with three extra fields such as firstname, lastname and confirm password. for that in registration template where can i use the template tags. Here is my forms.py: class UserRegisterForm(forms.ModelForm): email = forms.EmailField(label='Email Field') password = forms.CharField(widget=forms.PasswordInput) password1 = forms.CharField(widget=forms.PasswordInput) firstname = forms.CharField() lastname = forms.CharField() class Meta: model = User fields = [ 'firstname', 'lastname', 'email', 'password', 'password1', ] def clean_password(self): password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password1') if password != password2: raise forms.ValidationError('passwords must match') return password view.py file for registration code snippet def register_view(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save() password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, 'auth-register.html', context) template for auth-register.html <form method="POST">{% csrf_token %} <div class="row"> <div class="form-group col-6"> <label for="{{frist_name}}">First Name</label> <input id="{{frist_name}}" type="text" class="form-control" name="frist_name" autofocus=""> </div> <div class="form-group col-6"> <label for="{{last_name}}">Last Name</label> <input id="{{last_name}}" type="text" class="form-control" name="last_name"> </div> </div> <div class="form-group"> <label for="{{email}}">Email</label> <input id="{{email}}" type="email" … -
How to remove unnecessary characters from stdout in python?
I have this script: lec_name = request.POST['selected_name'] out = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) print(out.stdout) This script works fine. But I'm not getting the output properly. OUTPUT: b"Hello World\r\n" EXPECTED OUTPUT: Hello World How can I solve this? I found lot of answers about this, but none helped. I'm using Python 3.7.4, Django 3.0.1 -
how can i use my other app oauth authentication to authenticate my other app django rest frame work?
how can i use my other app oauth authentication to authenticate my other app Django rest frame work? i want to make several apps to use my authentication server to authenticate. is my thoughts in correct way? -
When I click to submit the registration form. Form submitted successfully but user data not added in db
I am trying to save the user registration form in django but when I clicked to save the user details in db. Form get submitted but data should not save in db and apart from this I am also not getting any error. But I can't get my submit to work. Anytime I submit, the page just reloads and nothing happens. I check my admin page to see if user is added but nothing seems to happens there too in django from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from webapp import models class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user -
Django_elasticsearch_dsl_drf not returning expected result
I was applying elastic search in one my django app, Below is my code snippets documents.py ads_index = Index("ads_index") ads_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"] ) @ads_index.doc_type class AdDocument(Document): id = fields.IntegerField(attr='id') title = fields.TextField( analyzer=html_strip, fields={ 'title': fields.TextField(analyzer='keyword'), } ) description = fields.TextField( analyzer=html_strip, fields={ 'description': fields.TextField(analyzer='keyword'), } ) category = fields.ObjectField( properties={ 'title': fields.TextField(), } ) class Django: model = Ad # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'price', 'created_at', ] related_models = [Category] def get_queryset(self): return super().get_queryset().select_related('category') def get_instances_from_related(self, related_instance): if isinstance(related_instance, Category): return related_instance.ad_set.all() serializer class AdDocumentSerializer(DocumentSerializer): class Meta: document = AdDocument fields = ( "id", "title", "description", "price", "created_at", ) viewset class AdViewSet(DocumentViewSet): document = AdDocument serializer_class = AdDocumentSerializer ordering = ('id',) lookup_field = 'id' filter_backends = [ DefaultOrderingFilterBackend, FilteringFilterBackend, CompoundSearchFilterBackend, SuggesterFilterBackend, ] search_fields = ( 'title', 'description', ) filter_fields = { 'id': { 'field': 'id', 'lookups': [ LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN, LOOKUP_QUERY_GT, LOOKUP_QUERY_GTE, LOOKUP_QUERY_LT, LOOKUP_QUERY_LTE, ], }, 'title': 'title.raw', 'description': 'description.raw', } ordering_fields = { 'id': 'id', } Below is my data I have When I hit http://127.0.0.1:8000/ads/search/?search=Tit it's not returning anything … -
Register several DRF views in urls.py
Please how to register 2 DRF views in urls.py? For now I do something like this below: class AcyVcsViewSet(viewsets.ModelViewSet): queryset = vcs_acymailing_subscriber.objects.all().order_by('subid') serializer_class = AcyVcsSerializer class AcyVcsEmail(viewsets.ModelViewSet): queryset = vcs_acymailing_subscriber.objects.all().order_by('subid') serializer_class = AcyVcsSerializer def get_queryset(self): email = self.request.query_params.get('email', None) return vcs_acymailing_subscriber.objects.filter(email=email) Then I register these views in urls.py: router = routers.DefaultRouter() router.register(r'first_view', views.AcyVcsViewSet) router.register(r'second_view', views.AcyVcsEmail) urlpatterns = [ path('', include(router.urls)), ] It works if I manually change the URLs in my browser. But "URLs" mentioned in my API are corrupted, maybe because I do not know this right syntax in urls.py. I searched for and tried a lot of syntax but ... No success Thanks -
Initialize a formset
I have two models connected by manytomany relationship and I am trying to use formset to create a dynamic form. I am able to save the form but the problem arise when I am trying to edit the saved instance, I don't know hoe to properly pass the instance to the formset such that it shows the instance data in form for editing Here are the details: Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.ModelForm): class Meta: model = Player fields = '__all__' PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.ModelForm): player= PlayerFormset() class Meta: model = Team fields = '__all__' exclude = ["player"] Views.py def team(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, 'packsapp/employee/new.html', {'form':form}) def updateTeam(request,pk): team = Team.objects.get(id=pk) form = TeamForm(instance=team) // something here to initialize the formset ?? if request.method == "POST": form = TeamForm(request.POST, instance=team) if form.is_valid(): form.save() context = {'form': form} … -
Facebook Webhook for Django
How can I post on the Facebook page from my Django website? I've created Facebook developer account but don't know to the public it as it is in developer mode -
Integrating Whatsapp in Django
How can integrate and send whatsapp messaged in django rest framework ? Basically i want to send messages to users to the whatsapp numbers they enter in the field. If any code references are available, i would request for sharing it. Thanks in Advance -
Not able see the image after uploading on admin panel
I am learning django but i am stuck at Imagefield. I am trying to rename the file and save the image to my media directory where exactly i am going wrong i am not able to understand. It was working fine till worked with filefield. after changing the filefield to imagefield i am getting an page not found. Not Found: /media/products/926045120/926045120.jpg above is the error from django.db import models import random import os def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): # print(instance) #print(filename) new_filename = random.randint(1,3910209312) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename ) # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) def __str__(self): return self.title def __unicode__(self): return self.title model.py of product import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z45+z23#cgk-fem6x&6i9_n@tz8p3)f^l+f1#8$e^n7(hv&dgz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application … -
django ajax POST 404 not found
Recently I learned ajax but now i am trying to implement in my fjango project but it is not working. signup.js $(document).ready(function(){ $(document).on('submit', '#signup', function(e){ e.preventDefault(); var email = $('input[name="email"]').val(); var name = $('input[name="name"]').val(); var password1 = $('input[name="password1"]').val(); var password2 = $('input[name="password2"]').val(); var url = '/signup' var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { if(req.responseText == 'true' ){ alert('account created') } } }; req.open("POST", url, true); req.send(); }) }); urls.py urlpatterns = [ path('',login_required(StockView.as_view(), login_url='login'), name='stock'), path('login/', LoginView.as_view(), name='login'), path('signup/', SignupView.as_view(), name='signup'), path('logout',LogoutView.as_view(), name='logout'), path('addproduct/', login_required(AddProduct.as_view(), login_url='login'), name='addproduct'), path('update/<int:pk>', login_required(EditProduct.as_view(), login_url='login'), name='editproduct'), path('delete/', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'), view.py class SignupView(TemplateView): template_name = 'stock/signup.html' def get(self, request): form = SignUpForm() args = {'form': form} return render(request, self.template_name, args) def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: args = {'form': form} return render(request, self.template_name, args) form.py class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'class':'form-control','name':'name'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),help_text='Password Should Match',label='Password') password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),label='Password Confirmation') class Meta: model = AppUser fields = ('username', 'email', 'password1', 'password2' ) template.html <form method="post" id="signup" > {% csrf_token %} {{ form.as_p }} <button … -
Getting error when updating a simple one to one relationship field in Django-rest-framework
I'm new to Django and have some basic knowledge of python. I'm trying to create and simple relationship between two models i.e user and profile. I have defined Django's user model and my profile model is ```python class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='defaultProfileImg.png', upload_to='_profile_img') first_name = models.CharField(max_length=60, blank=True) last_name = models.CharField(max_length=60, blank=True) description = models.CharField(max_length=60, blank=True) mobile = models.CharField(max_length=60, blank=True) current_location = models.CharField(max_length=60, blank=True) profile serializer is class ProfileSerializer(serializers.ModelSerializer): user_id = serializers.IntegerField(source='user.id') class Meta: model = Profile fields= ('user','image', 'first_name', 'last_name', 'description','mobile', 'current_location', 'user_id') def update(self, instance, validated_data): user_data = validated_data.pop('user') user = UserRegistration.create(UserSerializer(), validated_data=user_data) created, profile = Profile.objects.update_or_create(user=user, subject_major=validated_data.pop('subject_major')) return profile and my view is class ProfileViewSet(APIView): # to find if isAuthenticate then authentication_classes = (TokenAuthentication,) permission_classes = [permissions.IsAuthenticated] def get(self, request): serializer = ProfileSerializer(request.user.profile) return Response({ 'profile': serializer.data }) def put(self, request, pk, format=None): # update user profile saved_article = get_object_or_404(User.objects.all(), pk=pk) serializer = ProfileSerializer(data=request.data) print('request.data', request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) I'm getting the following error {"user": \["Incorrect type. Expected pk value, received dict."\]} -
Python pickle load very slow on python 3.7 for Django nested relations, taking almost 8ms
Why is pythons pickle.load so slow for nested Django objects? I need to retreive 1800 pickled objects from cache and load them. The objects consist of a Django model instance with a 2 layers deep related object (created using 'select_related' on the queryset and then getting the required model instance). There are only a few fields (approx 5) in each layer, making the total fields about 30. Still to pickle load all 1800 objects takes almost 1.3 seconds. If I create a cached_object in the database to store it there instead of in memory, and load it from the database, it takes only 13ms for all 1800 objects, because now it doesn't need to use pickle.load, but creates the related objects 'new' from the database. Is there any particular reason that pickle.load is so slow? I was storing the objects is memory cache for performance concerns, but it only made it worse. -
Automatically create Django Profile when creating user using signals.py
I have an issue in signals.py. Parameter 'sender' value is not used. and Parameter 'kwargs' value is not used.. In my previous project, this was working fine, But in this project User(AbstractUser) model was introduced in models.py then this issue began. SIGNALS.PY from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile, MedicalInfo @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_public = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) VIEWS.PY @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('public:profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'all_users/public/profile.html', context) -
How to show name in foreign key?
In Models: class ShopCategory(models.Model): category = models.CharField(max_length=100) class Meta: db_table = "tbl_ShopCategory" class Shop(models.Model): id_shop = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) slug = models.SlugField(max_length=250, blank=True, null=True) cover_img = models.CharField(max_length=250, blank=True) category = models.ForeignKey(ShopCategory, on_delete=models.CASCADE) avgscore = models.FloatField(default=0) I want to show the Category name? ........................................................... -
Got the ValueError when trying to print one of the fields in return string function __str__()
When I try to print(or to use in return string) one of the fields, I get the following ValueError: invalid literal for int() with base 10: 'topic_id' Here is my model class: from django.db import models from django.conf import settings from languageTests.signals import topic_viewed_signal from django.contrib.contenttypes.models import ContentType User = settings.AUTH_USER_MODEL Topic = settings.TOPIC_MODEL class TopicProgress(models.Model): user = models.ForeignKey(User, on_delete='CASCADE') # user instance instance.id topic = models.ForeignKey(Topic, on_delete='CASCADE') finished = models.BooleanField(default=False) started = models.BooleanField(default=False) class Meta: unique_together = ('topic', 'user',) def __str__(self): print("topic=<{}>".format(self.topic)) return "{}-{}".format(self.user,self.topic) Also this is the topic class: class Topic(models.Model): LEVELS = ( ('b', 'Beginner'), ('i', 'Intermediate'), ('e', 'Expert'), ) level = models.CharField( max_length=1, choices=LEVELS, blank=True, default='b', help_text='Tests level', ) title = models.CharField(max_length=200, help_text='Enter a Test Name (e.g. Test #1)') objects = TopicManager() def return_level_str(self): dict_levels=dict(self.LEVELS) return dict_levels[self.level] def __str__(self): return self.title def get_absolute_url(self): return reverse('topic', args=[self.id]) I have tried to debug and figured out that "id" appears as string in C:\Users\A\Anaconda3\lib\site-packages\django\db\models\query.py in get args (<Q: (AND: ('id', 'topic_id'))>,) kwargs {} self <QuerySet [<Topic: sel>, <Topic: Past Perfect>]> I have also tried to print other fields "finished" ,"started" , "user" and they all worked perfectly. Can someone shed light on this for me ? here is the … -
socket.gaierror: [Errno 10047] getaddrinfo failed
I searched a lot but didn't find a proper solution. Seems like nobody had this problem before. Note my socket.gaierror is [Errno 10047] which means "Address family not supported by protocol family" The error I'm getting is when I try to integrate SMTP in my project so I can send mails. File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 307, in _get_socket self.source_address) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\socket.py", line 705, in create_connection for res in getaddrinfo(host, port, 1, SOCK_STREAM): File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\socket.py", line 748, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 10047] getaddrinfo failed SERVER_EMAIL = 'abc@example.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'password_here' EMAIL_HOST_USER = SERVER_EMAIL EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER And when I use the send_mail() function in my view. I get this socket error. This error goes away if I change my email backend to "django.core.mail.backends.console.EmailBackend". -
When I collectstatic I also get rest_framework in static files
I have a django project with rest_framework in installed apps. When I run python manage.py collectstatic I get a rest_framework folder in my project/static/ directory. This rest_framework folder has many files including bootstrap.min.css , font-awesome-4.0.3.css etc. Is it a good practice to have all this in my static folder, or should I be filtering rest_framework when doing python manage.py collectstatic -
Django login does not show anything
I have sign in, sign up and log out in my home page. Sign up works fine but login does not work. when i run the server it works but does not show anything, any errors or anything in login page that prompts the user to enter username and password. views.py def userLogin(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username = username, password = password) if user is not None: login(request, user) return redirect('home') else: error = True return render(request, 'login.html', {'error': error}) return render(request, 'login.html',) login.html {% extends 'base.html' %} {% block content %} <h2>Sign in</h2> <form> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign in</button> </form> {% endblock %} urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/$', Home, name = 'home'), url(r'^product_upload', InsertProduct, name = 'product_upload'), url(r'^success', success, name = 'success'), path('productlist/', ShowProducts, name = 'productlist'), path('<int:product_id>/', product_detail, name='product_detail'), url(r'^signup/$', signup, name='signup'), url(r'^login/$', userLogin, name='login'), url(r'^logout/$', userLogout, name='logout'), ] You can see images below: Sign Up image Sign In image -
DJANGO CHECK CONSTRAINTS: SystemCheckError: (models.E032) constraint name 'age_gte_18' is not unique amongst models
I'm trying to connect Django with PostgreSQL, so far everything was going good, I created a model for female clients from django.db import models from django.db.models import CheckConstraint, Q class fml_tbl(models.Model): fml_id = models.CharField(primary_key = True, max_length = 10) first_name = models.CharField(max_length = 20, null = False) last_name = models.CharField(max_length = 20) age = models.PositiveIntegerField(unique = True) qualification = models.CharField(max_length = 50) profession = models.CharField(max_length = 50) officer = models.ForeignKey("officer", on_delete=models.CASCADE, null = False) class Meta: constraints = [ models.CheckConstraint(check=Q(age__gte=18), name='age_gte_18') ] I added a check constraint for checking the age of the client, when I migrate, I get the error... django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (models.E032) constraint name 'age_gte_18' is not unique amongst models: client.fml_tbl, client.ml_tbl. System check identified 1 issue (0 silenced). there is also a male clients table same as this one, i'm just trying to practice django model constraints because postgresql also uses constraints, but i can't understand what to do here. I'm using Django 3.0 and Python 3.7 I searched for different answers on stackoverflow and other places but i can't find anything, I used the django documentation and this site for understanding constraints but so far this is all what … -
Django UpdateView with ImageField
Form validation isn't passing for some reason when i try to update a image on my model. I've also tried updating it without using PIL library, still doesn't work. class UpdateProfile(UpdateView): template_name = 'dashboard/edit-profile.html' form_class = UserForm success_url = None def get_object(self, queryset=None): return User.objects.get(username=self.kwargs['username']) def form_valid(self, form): self.instance = form.save(commit=False) user = self.get_object() user.full_name = self.instance.full_name user.username = self.instance.username user.email = self.instance.email user.description = self.instance.description im = Image.new(self.instance.main_image) user.profile_image = im user.ig = self.instance.ig user.fb = self.instance.fb user.pinterest = self.instance.pinterest user.twitter = self.instance.twitter user.save() return render(self.request, self.template_name, self.get_context_data()) Model Image attribute profile_image = models.ImageField(upload_to=save_profile_image, default='/static/img/blog/avatars/user-01.jpg') def save_profile_image(instance, filename): if instance: return '{}/{}'.format(instance.id, filename) form data from html. <form action="" class="tm-edit-product-form" method="post" enctype="multipart/form-data"> <div class="custom-file mt-3 mb-3"> <input id="fileInput" type="file" name="main_image" style="display: none" accept="image/*"/> {{ form.profile_image }} </div> </form> Anyway, the POST request comes throgh but the object isn't updated. The problem resides in the ImageField. Why the hell isn't it working as it should? -
Django Static files cached
My site is in production and whenever I modify my static files it doesn't reflect changes as it seems to be cached somewhere, though I can see the see changes when fresh from network tab in "inspect". My question is how can I force Django to do it automatically for me on my user's system -
Django related model not updating related object in admin
I have 2 models that look like this: models.py class Client(models.Model): deal = models.ManyToManyField('Deal', related_name="clients") class Deal(models.Model): client = models.ManyToManyField(Client, related_name="deals") Then in the admin, I have inlined the related models to make it easy to make changes regardless of the object type you have open. admin.py class ClientInline(admin.TabularInline): model = Deal.client.through class ClientAdmin(admin.ModelAdmin): inlines = [DealInline] class DealInline(admin.TabularInline): model = Client.deal.through class DealAdmin(admin.ModelAdmin): inlines = [ClientInline] However, if you add a Client to a Deal and then open the Client detail page, the corresponding deal does not appear. Is there something I'm not connecting? -
How to trigger Python script from HTML input?
I'm struggling with one part of building a website. I'm using Vue for the front end and Python for the backend. These are the steps I need to take: Take a text input in a HTML text box: <div class="search-wrapper"> <input type="text" v-model="search" placeholder="Enter Stock Ticker"/> </div> Run a python script that uses that text to run a Tweepy API search: t = tweetObj.tweetObject({{ html input here }}) tweet_string = t.get_created_at() Do a bunch of sentiment analysis (which is already done) Fill in a bunch of charts on a website (which I already have a template for) What I don't understand is whether or not I need to use Django or Flask for the Python IO. Is this necessary to take the inputs or can I get by with just simple HTTP request modules? I do understand running everything in one server, but the front end part is very new to me and I'm confused. Would appreciate some guidance on this.