Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if a Django arrayfield has data
I have a Django model for articles with an array field that sometimes has ids. id_list = ArrayField(models.CharField(max_length=10000), blank=True, null=True) I want to write a query that finds all the article objects that have data in the id_list. I tried the following, but it did not work. Article.objects.filter(id_list__isnull=False) What is the correct way to write this? Thank you. -
How can I make a button pull a specific piece of data from the database?
I am creating a restaurant web app using Django and Python. I am trying to use buttons to select menu items to be added to the order, and displayed in a text area along with their prices. Thanks! Here is the code for this section: HTML: <div class="row"> {% for Product in show_menu %} <div class="col-sm-5" style= "color:#EAEAEA"> <button type = "submit" class="btn btn-info btn-md" onclick = "input()">{{ Product.name }}: ${{ Product.price }}</button> <br><br><br> </div> {% endfor %} </div> <label for="order"><h2 style= "color:#EAEAEA"><u>Order Details</u></h2></label> <br> <form> <textarea readonly class="fixed-right" id="order" name="order" rows="10" cols="80"> </textarea> </form> Views.py: class HomeView(ListView): model = Product template_name = 'mis446/home.html' context_object_name = 'show_menu' Models.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() def __str__(self): return self.name -
Second image not saving with serializer
I have 2 models that looks like this: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to='some-path/') A serializer for the ChoiceImage that looks like this: class ChoiceImageSerializer(serializers.ModelSerializer): img = Base64ImageField() class Meta: model = ChoiceImage fields = ('img',) And a ChoiceSerializer that looks like this: class CreateChoiceSerializer(serializers.ModelSerializer): choiceimage = ChoiceImageSerializer(many=False, required=False) class Meta: model = Choice fields = ('choice', 'choiceimage') def create(self, validated_data): image_uploaded = validated_data.get("choiceimage") if not image_uploaded["img"]: q = validated_data.get("question") if not q.choice_set.exists(): raise APIException("You must upload either an image or a cover.") else: img = q.choice_set.all()[0].choiceimage.img img2 = slice_image(img) validated_data["choiceimage"]["img"] = img2 image_validated_data = validated_data.pop('choiceimage') choice = Choice.objects.create(**validated_data) image_serializer = self.fields['choiceimage'] image_validated_data['choice'] = choice image_serializer.create(image_validated_data) Basically, the intention is this: A user creates 2 choices. If the user provides no image to the choices, then return an error. Else if the user provides only one image, split the image in half. Save one half to the first choice and the second half to the second choice. Lastly, if two images are uploaded then ignore the split image logic. My logic works fine with no image and two images. However, when I submit only one image, the … -
running user input through python script and returning output on django site
new python/django user here. i'm trying to set up a webpage that takes user input (e.g., an address) into a form, then passes it through a python script (in a separate.py file) before returning an output to the same webpage (e.g., the nearest traffic light). how would i go about making the connection between my views.py file and my script.py file in django? simplified code: views.py file input = form.cleaned_data.get('enter_address') script.py file print(input) -
Traversing a ManyToMany relationship to add to context in a Django DetailView
I asked a similar question recently about a different project. In that case (see Traverse multiple foreign keys in Django DetailView), I was able to follow the flow of Foreign Keys to make the needed connection when defining the view. In this case I need to traverse through a ManyToMany junction table, and I'm stymied. Here's an ER diagram of the relevant portion of my model. ┌────────────┐ ┌────────────┐ ┌───────────────┐ ┌────────────┐ │ │ ╱│ │ ╱│ │╲ │ │ │ Company │─────┼──│ Product │────┼──│ PersonProduct │──┼────│ Person │ │ │ ╲│ │ ╲│ │╱ │ │ └────────────┘ └────────────┘ └───────────────┘ └────────────┘ The purpose of this web site is to connect professional archers with the equipment and companies that sponsor them and display those connections. In this particular case, I have a detail view for a company. I've successful set it up for display all the products that the company sells. Now I want to display a list of all the archers that use one or more products from that company. I can't figure out how to span all the way from the company to the individuals who use those products. Here's the model, view, and template I'm working with. # models.py from … -
Django fetch firebase User UID
I'm using Pyrebase to fetch data from firebase in Django and so far it seems to be able to do everything but for some reason, I can't fetch the User UID from the authentication page in firebase. This is necessary for me to be able to do as all my user database nodes are save under the User UID from here. Here is my current attempt but the idToken doesn't return the User UID token = user['idToken'] print(token) -
Trying to use JQuery to fill out a form
I am working on a django project that shows a list of meals on the home page. Below each meal I want to include an order button that pulls up a popup field to enter the amount of orders for that meal you would like to place and then on clicking 'OK' submits a form that creates an order object. Image of List of Meals Currently, if you click on the button it creates an order where the number of meals ordered is 1. View def add_order(request, meal_slug, meal_restaurant, amount): meal = Meal.objects.get(slug=meal_slug, restaurant_slug=meal_restaurant) user = UserProfile.objects.get(user=request.user) order = Order.objects.create(meal=meal, customer=user, amount=amount, date=datetime.now()) order.save() return index(request) Html <ul class="list-group"> <li class="list-group-item">{{ meal.meal_name }}</li> <li class="list-group-item">{{ meal.description }}</li> <button class="order"><a href="{% url 'food_cloud:add_order' meal.slug meal.restaurant_slug %}">Order</a></button> </ul> JQuery $(document).ready(function() { $(".order").click(function() { var amount = parseInt(prompt("Please enter amount of orders" ,"0")) if (amount <= 0) { alert("Please enter integer greater than 0") } else { $.ajax({ url: "{% url 'food_cloud:add_order' meal.slug meal.restaurant_slug amount %}", type: "POST", }) } }) }) -
Uploading a signature with Django
I'm trying to create a signature field that will relate back to a model in django. I scoured everywhere and was finally able to get a jquery signature canvas within my project. But being that I know very little about jquery, I'm not sure how to get the created signature instance to tie to the model and upload directly to the media cdn. Right now I can upload a file, and I can save a signature to my local machine. But I can't do them together. Current html output GUI with form and signature class SigninForm(forms.ModelForm): class Meta: model = Attendance fields = ('schedule', 'time_punch', 'signature', ) // using <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script> var clockinSignature = "{{ schedule.date|date:"ydm"}}{{ schedule.kid.account }}{{ schedule.kid|cut:" " }}-in.jpg" var clockoutSignature = "{{ schedule.date|date:"ydm"}}{{ schedule.kid.account }}{{ schedule.kid|cut:" " }}-out.jpg" var wrapper = document.getElementById("signature-pad"); var clearButton = wrapper.querySelector("[data-action=clear]"); var saveJPGButton = wrapper.querySelector("[data-action=save-jpg]"); var canvas = wrapper.querySelector("canvas"); var signaturePad = new SignaturePad(canvas, { backgroundColor: 'rgb(255, 255, 255)' }); function resizeCanvas() { var ratio = Math.max(window.devicePixelRatio || 1, 1); canvas.width = canvas.offsetWidth * ratio; canvas.height = canvas.offsetHeight * ratio; canvas.getContext("2d").scale(ratio, ratio); signaturePad.clear(); } window.onresize = resizeCanvas; resizeCanvas(); function download(dataURL, filename) { if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") === -1) { window.open(dataURL); … -
Error loading psycopg2 module: No module named 'psycopg2'
I am working on window 10. enter image description hereI am facing "psycopg2 module finding error" I install "pip install psycopg2" and "pip install psycopg2_binary" But when i run server i got this error "Error loading psycopg2 module: No module named 'psycopg2'" -
Python - How can we speed this up without modifying the body of the get_resource_identifier function
Suppose the get_resource_identifier function interrogates some cloud infrastructure to resolve the resource identifier from its name. Note that it takes a long time for the call to finish resolving the name. Now imagine that we need to resolve the resource by its name multiple times during deployment of infrastructure. How can we speed this up without modifying the body of the get_resource_identifier function? Remember, you have no control over how quickly the cloud provider can respond to your API call. import time def get_resource_identifier(name): time.sleep(1)#simulate the delay if name is 'foo': return 'L9UKvnomjq' if name is 'bar': return '7U9eyOv7M' return 'Not found' for _ in range(0,100): print(get_resource_identifier('foo')) print(get_resource_identifier('bar')) print(get_resource_identifier('foo')) print(get_resource_identifier('zoo')) print(get_resource_identifier('bar')) -
Django Rest FrameWork Add Model With User Foreign Key
I'm using Django version 3 and the Rest Framework, i have a model with a user foreignkey. so every time a model is saved the user also need to be saved. To be able to add or to edit a model via rest you need to be authenticated using token authentication. I'm using ClassBasedViews, the problem is that i can't find a way to add a model because in my serializer the field user is excluded because i don't want it to be editable. models.py: class Chambre(models.Model): local_id=models.PositiveIntegerField(unique=True) nom=models.CharField(max_length=255) user=models.ForeignKey(User,on_delete=models.CASCADE,blank='true') class Meta: unique_together = ('local_id', 'user',) serializers.py: class ChambreSerializer(serializers.ModelSerializer): class Meta: model = Chambre exclude =['user',] views.py: class ChambreListApi(APIView): """ List all chambres, or create a new chambre. """ authentication_classes=(TokenAuthentication,) permission_classes=(IsAuthenticated,) def get(self, request, format=None): chambres = Chambre.objects.filter(user=request.user) serializer = ChambreSerializer(chambres, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ChambreSerializer(data=request.data) if serializer.is_valid(): serializer.save(commit=False) serializer.user=request.user serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Email for verification before login or create a new account
I need help with a django code that I am developing for django webapp. I need to create a code so that on the login page a box appears where we put the email and it sends an account verification email before logging in or a new registration. Does anyone have any idea how this code is developed? Below I send an example that I try to explain what I need. thanks enter image description here -
I get "TypeError: __init__() got an unexpected keyword argument 'attrs' " when I execute the below code
I get a type error when my form tries to execute username = forms.CharField(label='User name', max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(widget=forms.EmailField(attrs={'class': "form-control my-input"}), label="Enter Email") password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control my-input"}), label="Enter Password",) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control my-input"}), label="Confirm Password") -
Displaying objects by categories in Django
I'm building an ecommerce app and I'd like to make a section that shows some featured items by category. I'm using three sliders that display those items; Each slider is a featured category and each item in the slider is a featured item. The problem is that I can't figure out how to assign the item to the proper slider. For example: I want to assign a JeansJacket to "Clothes and accesories" and display it. I tried this: {% for cat in categories %} <h1>{{ cat.cat_name }}</h1> <!--(carousel code in between)--> <div class="carousel-inner" role="listbox"> {% for item in featured_items %} {% if item.Categoría in cat.cat_name %} {{ item }} {% endif %} This is a simplified version of what I have, without the rest of the content. I just can't figure out how to iterate though the featured items and display them in the corresponding category. -
how can i slice a list with override save models.py [:2]
how can i slice a list with override save models.py i also used this code in models.py field this code is working but slicing [:2] def save(self, *args, **kwargs): if self.featured == True: Article.status_objects.filter(featured=True).update(featured=False) self.featured = True super(Article, self).save(*args, **kwargs) when i try to slice list with override save method my server get error 'int' object is not subscriptable i want something like this models.py def save(self, *args, **kwargs): if self.featured == True: Article.status_objects.filter(featured=True).update(featured=False)[:2] self.featured = True super(Article, self).save(*args, **kwargs) views.py articles = Article.status_objects.filter(tags__exact='1', featured=True)[:2] articleslist = Article.status_objects.filter(tags__exact='1').exclude(featured=True)[:4] -
Adding a user through Django Admin: "Please correct the error below" validation error on the E-mail field
I have tried the solutions in the other 2 questions that I found on stackoverflow, but they did not work, so I have to post the same questions again with my code: admin.py from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserProfileChangeForm add_form = UserProfileForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'is_admin', 'is_staff',) list_filter = ('englishinterest_id', 'planchoice_id', 'is_staff',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, {'fields': ('email', 'password1', 'password2')}), ('Personal Information', {'fields': ( 'is_active', 'english_interest', 'plan_choices', 'first_name', 'last_name', 'age', 'location')}), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () Managers.py class UserProfileManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given email, and password. """ if not email: raise ValueError('The given email must be … -
Django Firebase check if user is logged in
I'm trying to check if the user is logged into firebase in Django by requesting the session_uid in the home.html file. Which seems not to be working. How can I check if the firebase user is logged in? def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): # form.save() email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = auth.sign_in_with_email_and_password(email, password) session_id = user['idToken'] request.session['uid'] = str(session_id) messages.success(request, f'Account created for {email}!') return redirect(request, 'blog-home') else: form = UserLoginForm() return render(request, 'users/login.html', {'form': form, 'title': 'Login'}) home.html {% extends "home/base.html" %} --> {% block content %} {% if request.session.session_id %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted }}</small> </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% else %} <h2>You need to login</h2> {% endif %} {% endblock content %} -
Uploading files in Django using jQuery
I am trying to upload multiple files for a blog post object, however, it seems that my Ajax form is not working properly and I cannot see the files uploading. Since there is no post object at the time of creating the images, I am trying to upload the files then get them in my view and after saving the post I am trying to save those files by assigning the id of that post to them. Currently, my issue is it seems my files are not uploading and I cannot get them at all. I am not getting any error and therefore, I cannot find an issue. Below is my file upload and post create view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() for image in request.FILES.getlist('file'): instance = Images(post=Post.objects.get(post.id),image=image) instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) class PostImageUpload(LoginRequiredMixin, View): def get(self, request): images = Images.objects.all() return render(self.request, 'home/posts/post_create.html', {'images':images} ) def post(self, request): data = dict() … -
How to modify an uploaded file in a django model
I have a model that accepts a file to upload. I need to do some processing on the file before it is saved: 1. generate a thumbnail image and save that in another file field 2. create an image of a certain size and type and save that image in another file field 3. optionally save the original image in a third file field I have accomplished 1 & 2, but not 3, and I get an unexpected result. My model: class Document(Model): document_id = models.AutoField(primary_key=True) storage_file_name = models.FileField('File name', upload_to=unique_file_path_2) thumb_file = models.FileField("thumb", upload_to=settings.DOCUMENT_FOLDER_THUMB, default=settings.DEFAULT_THUMBNAIL) xxxlarge_file = models.FileField('xxxlarge', upload_to=settings.DOCUMENT_FOLDER_XXXLARGE, default=settings.DEFAULT_THUMBNAIL) and the upload_to function: def unique_file_path_2(instance, filename): temp_image = BytesIO() image = None default_thumb = None default_file = None f = None try: #fred = 3/0 # to test the exception path pages = wImage(blob = instance.storage_file_name) first_page = pages.sequence[0] image = wImage(first_page) image.transform(resize=settings.DOCUMENT_XXXLARGE_WIDTH.split("px")[0]) image.format = "png" image.save(temp_image) temp_image.seek(0) file_name, extension = os.path.splitext(filename) instance.xxxlarge_file.save(file_name + ".png", ContentFile(temp_image.read()), save=False) # make a thumbnail image_processing_utils.make_thumb(instance, filename) except: # save default images instead of the uploaded image logger.exception("unique_file_path_2 Exception") default_image = settings.DEFAULT_IMAGE_NAME.replace("size", "xxxlarge") default_image_path = os.path.join(settings.DEFAULT_IMAGE_PATH, default_image) f = open(default_image_path, 'r+b') default_file = File(f) instance.xxxlarge_file.save(default_image, default_file, save=False) f = open(settings.DEFAULT_THUMBNAIL, 'r+b') default_thumb … -
Loop Through API with Djano
I am trying to loop through this data via Django. The data was able to show using {{ globaldata.data }} in my Django Template. By then, I can view details as per the Date. data.json {"data":[{"1/22/20":{"confirmed":555,"deaths":17,"recovered":28}},{"1/23/20":{"confirmed":654,"deaths":18,"recovered":30}},{"1/24/20":{"confirmed":941,"deaths":26,"recovered":36}},{"1/25/20":{"confirmed":1434,"deaths":42,"recovered":39}},{"1/26/20":{"confirmed":2118,"deaths":56,"recovered":52}},{"1/27/20":{"confirmed":2927,"deaths":82,"recovered":61}},{"1/28/20":{"confirmed":5578,"deaths":131,"recovered":107}},{"1/29/20":{"confirmed":6166,"deaths":133,"recovered":126}},{"1/30/20":{"confirmed":8234,"deaths":171,"recovered":143}},{"1/31/20":{"confirmed":9927,"deaths":213,"recovered":222}},{"2/1/20":{"confirmed":12038,"deaths":259,"recovered":284}},{"2/2/20":{"confirmed":16787,"deaths":362,"recovered":472}},{"2/3/20":{"confirmed":19881,"deaths":426,"recovered":623}},{"2/4/20":{"confirmed":23892,"deaths":492,"recovered":852}},{"2/5/20":{"confirmed":27635,"deaths":564,"recovered":1124}},{"2/6/20":{"confirmed":30794,"deaths":634,"recovered":1487}},{"2/7/20":{"confirmed":34391,"deaths":719,"recovered":2011}},{"2/8/20":{"confirmed":37120,"deaths":806,"recovered":2616}},{"2/9/20":{"confirmed":40150,"deaths":906,"recovered":3244}},{"2/10/20":{"confirmed":42762,"deaths":1013,"recovered":3946}},{"2/11/20":{"confirmed":44802,"deaths":1113,"recovered":4683}},{"2/12/20":{"confirmed":45221,"deaths":1118,"recovered":5150}},{"2/13/20":{"confirmed":60368,"deaths":1371,"recovered":6295}},{"2/14/20":{"confirmed":66885,"deaths":1523,"recovered":8058}},{"2/15/20":{"confirmed":69030,"deaths":1666,"recovered":9395}},{"2/16/20":{"confirmed":71224,"deaths":1770,"recovered":10865}},{"2/17/20":{"confirmed":73258,"deaths":1868,"recovered":12583}},{"2/18/20":{"confirmed":75136,"deaths":2007,"recovered":14352}},{"2/19/20":{"confirmed":75639,"deaths":2122,"recovered":16121}},{"2/20/20":{"confirmed":76197,"deaths":2247,"recovered":18177}},{"2/21/20":{"confirmed":76819,"deaths":2251,"recovered":18890}},{"2/22/20":{"confirmed":78572,"deaths":2458,"recovered":22886}},{"2/23/20":{"confirmed":78958,"deaths":2469,"recovered":23394}},{"2/24/20":{"confirmed":79561,"deaths":2629,"recovered":25227}},{"2/25/20":{"confirmed":80406,"deaths":2708,"recovered":27905}},{"2/26/20":{"confirmed":81388,"deaths":2770,"recovered":30384}},{"2/27/20":{"confirmed":82746,"deaths":2814,"recovered":33277}},{"2/28/20":{"confirmed":84112,"deaths":2872,"recovered":36711}},{"2/29/20":{"confirmed":86011,"deaths":2941,"recovered":39782}},{"3/1/20":{"confirmed":88369,"deaths":2996,"recovered":42716}},{"3/2/20":{"confirmed":90306,"deaths":3085,"recovered":45602}},{"3/3/20":{"confirmed":92840,"deaths":3160,"recovered":48228}},{"3/4/20":{"confirmed":95120,"deaths":3254,"recovered":51170}},{"3/5/20":{"confirmed":97886,"deaths":3348,"recovered":53796}},{"3/6/20":{"confirmed":101801,"deaths":3460,"recovered":55865}},{"3/7/20":{"confirmed":105847,"deaths":3558,"recovered":58358}},{"3/8/20":{"confirmed":109821,"deaths":3802,"recovered":60694}},{"3/9/20":{"confirmed":113590,"deaths":3988,"recovered":62494}},{"3/10/20":{"confirmed":118620,"deaths":4262,"recovered":64404}},{"3/11/20":{"confirmed":125875,"deaths":4615,"recovered":67003}},{"3/12/20":{"confirmed":128352,"deaths":4720,"recovered":68324}},{"3/13/20":{"confirmed":145205,"deaths":5404,"recovered":70251}},{"3/14/20":{"confirmed":156101,"deaths":5819,"recovered":72624}},{"3/15/20":{"confirmed":167454,"deaths":6440,"recovered":76034}},{"3/16/20":{"confirmed":181574,"deaths":7126,"recovered":78088}},{"3/17/20":{"confirmed":197102,"deaths":7905,"recovered":80840}},{"3/18/20":{"confirmed":214821,"deaths":8733,"recovered":83312}},{"3/19/20":{"confirmed":242500,"deaths":9867,"recovered":84975}},{"3/20/20":{"confirmed":272035,"deaths":11299,"recovered":87420}},{"3/21/20":{"confirmed":304396,"deaths":12973,"recovered":91692}},{"3/22/20":{"confirmed":336953,"deaths":14651,"recovered":97899}},{"3/23/20":{"confirmed":378235,"deaths":16505,"recovered":98351}},{"3/24/20":{"confirmed":418045,"deaths":18625,"recovered":108000}},{"3/25/20":{"confirmed":467653,"deaths":21181,"recovered":113787}},{"3/26/20":{"confirmed":529591,"deaths":23970,"recovered":122150}},{"3/27/20":{"confirmed":593291,"deaths":27198,"recovered":130915}},{"3/28/20":{"confirmed":660706,"deaths":30652,"recovered":139415}},{"3/29/20":{"confirmed":720117,"deaths":33925,"recovered":149082}},{"3/30/20":{"confirmed":782365,"deaths":37582,"recovered":164566}}],"dt":"2020-03-30 22:58:55","ts":1585609135.0} -
Django send_mail raising error " 'ascii' codec can't encode characters"
Created web app with Django and one of the functions is to send notifications through email to people who pass the test.So in my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'did****@gmail.com' DEFAULT_FROM_EMAIL = 'did****gmail.com' EMAIL_HOST_PASSWORD = '*************' EMAIL_USE_TLS = True Here in my views.py I have a method for sending notifications through email def recrutesdetails(request, id, Pid): ... if request.method == "POST": sith.resrutesShadowing.add(recruter) sith.save() message = 'duck' subject = 'duck' safe_str = smart_str(message) safe_sub = smart_str(subject) recipientlist = smart_str(recruter.planetRecruteEmail) send_mail(safe_sub, safe_str, from_email = smart_str(settings.DEFAULT_FROM_EMAIL),recipient_list=[recipientlist,] , fail_silently=False) return HttpResponseRedirect(reverse( 'recruters', args=[Pid])) return render(request,'app/recrutdetail.html', {'recruter': recruter, 'recrList': recrList, 'wrongList': wrongList}); I've tried to encode messages and email adresses with: message.encode("ascii", errors="ignore") message.encode('utf-8') smart_str() But nothing seems to work and error raised by my send_mail() function which envokes other django lib functions: C:\Users\user..\__init__.py in send_mail return mail.send() ... C:\Users\user...\message.py in send return self.get_connection(fail_silently).send_messages([self]) ... C:\Users\user...\smtp.py in send_messages new_conn_created = self.open() ... C:\Users\user...\smtp.py in open self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) ... C:\Users\user...\smtplib.py in starttls self.ehlo_or_helo_if_needed() ... C:\Users\user...lib\smtplib.py in ehlo_or_helo_if_needed if not (200 <= self.ehlo()[0] <= 299): ... C:\Users\user..\lib\smtplib.py in ehlo self.putcmd(self.ehlo_msg, name or self.local_hostname) ... C:\Users\..\Python\Python35\lib\smtplib.py in putcmd self.send(str) ... and I tracked it till: C:\Users\user\AppData\Local\Programs\Python\Python35\lib\smtplib.py in send **s = s.encode(self.command_encoding) … -
Django formset creates multiple inputs for multiple image upload
I am trying to create a simple post sharing form like this one. I'm using formset for image upload. But this gives me multiple input as you can see. Also each input can choose single image. But I'm trying to upload multiple image with single input. views.py def share(request): ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=3) # 'extra' means the number of photos that you can upload ^ if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if postForm.is_valid() and formset.is_valid(): post = postForm.save(commit=False) post.author = request.user post.save() for form in formset.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form: image = form['image'] photo = Images(post=post, image=image) photo.save() return redirect("index") else: print(postForm.errors, formset.errors) else: postForm = PostForm() formset = ImageFormSet(queryset=Images.objects.none()) return render(request, "share.html", {"postForm": postForm, 'formset': formset}) share.html <form method="POST" id="post-form" class="post-form js-post-form" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} </form> if you need, forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content"] def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'input'}) self.fields['content'].widget.attrs.update({'class': 'textarea'}) class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images … -
Is there a way to test Django project creation with pytest/Django test suite?
I created a Django plugin system which creates some boilerplate code. It can be used in any Django project (GDAPS), and provides a few management commands. What is the best way to test this whole suite? I mean, I can create bash scripts that setup fake Django projects which include my project, and then call all the management commands like makemigrations, migrate etc. to set it up fully, call my special commands (./manage.py initfrontend) and check if the results created the right files correctly. Now bash scripts are not my favourite testing suite, I'd keep with python and pytest if possible. Is there a way to test things like that? How can I start here - I can't wrap my head around this. I have already written plenty of unit tests for various features of the framework, but these tests are alike integration tests. Thanks for your help. -
Django WSGI Apache/WAMP on Windows - ACCESS DENIED
I am facing a strange 403 while accesing my app, [authz_core:error] [pid 11736:tid 1328] [client ::1:55552] AH01630: client denied by server configuration: .../mysite/mysite/wsgi_windows.py, referer: http://localhost/mescarator. My conf quite straight forward; ServerName localhost DocumentRoot "D:/DevRoot/py/MescaratorReconcilator/mysite" WSGIPassAuthorization Off ErrorLog "D:/DevRoot/py/MescaratorReconcilator/mysite/apache.error.log" CustomLog "D:/DevRoot/py/MescaratorReconcilator/mysite/apache.access.log" combined WSGIScriptAlias / "D:/DevRoot/py/MescaratorReconcilator/mysite/mysite/wsgi_windows.py" Require all granted I am surely missing something basic, tried disabling auth from apache. But without any sucess. Thank you for your help/ BR Es/ -
When I try to migrate I get this : django.db.utils.DataError: integer out of range ? Django 1.11.28
I did makemigrations in my Django project then tried to migrate. I got this. I don't know where it is coming from. Applying shop.0002_auto_20200302_2309... OK Applying shop.0003_auto_20200304_1458... OK Applying shop.0004_auto_20200331_1522...Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 88, in database_forwards field, File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 445, in add_field self.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 136, in execute cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: integer out of range I don't know how to solve this error. Anyone?