Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter by polygon draw in geodjango
Lets say user draw polygon and request to backend for filtration. As I can filter by bounding box but Can geodjango queryset filter within the draw area ? For instance, I have object with data in multilinestring field. class Datasets(models.Model): name = models.CharField(max_length=100) multipoint = models.MultiPointField(blank=True, null=True, srid=4326) multilinestring = models.MultiLineStringField(srid=4326, blank=True, null=True) multipoly = models.MultiPolygonField(blank=True, null=True, srid=4326) objects = GeoManager() -
Custom Django Channels middleware not finishing processing before Websocket connects
I have an existing WSGI application which I'm adding Django Channels to to give websocket functionality. I created a consumer using WebsocketConsumer, added the custom middleware into the routing file, and implemented a basic version of pulling the token from the incoming connection request. I can successfully print the token that's in the database, so I know the correct information is passing. I can connect to the socket, but it always comes back as being an anonymous user within the scope. It seems that the get_user_from_token function is not getting a chance to execute before the connect function executes, because all of the prints within the __call__ function of the TokenAuthMiddleware class are printed and none of the prints from the get_user_from_Token are printing. I tried switching the consumer to an async consumer, but that opened up a whole other set of problems that I couldn't figure out. I tried putting async in front of the __call__ and await in front of the function call, but that didn't work either. The current error I'm getting is: Exception inside application: 'coroutine' object has no attribute '_wrapped' File "C:\Users\PC\Envs\p3\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\PC\Envs\p3\lib\site-packages\channels\middleware.py", line 40, in … -
Python rest api without frameworks
Can we create Rest API using python without flask, django or any other frameworks? Which means Rest api using core python. -
How to resolve the error type object 'numpy.flatiter' has no attribute 'home'
I try running Jupyter from Pycharm on a Django application to be precise (I used pip install to install Jupyter)m but anytime I run my code I keep on getting the error message 'type object 'numpy.flatiter' has no attribute 'home' '. Please would really need help on how to resolve this issue -
Django AllAuth 'NoneType' object has no attribute 'append'
I'm using Django (3.0.2) and django-allauth (0.41.0) and am getting this error when a user enters the wrong password. I've got both django and all auth running on a different project and this doesn't happen. Internal Server Error: /account/login/ AttributeError at /account/login/ 'NoneType' object has no attribute 'append' Request Method: POST Request URL: https://www.podpage.com/account/login/ Django Version: 3.0.2 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages', '/app/.heroku/src/redwoodlabs', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf'] Server time: Tue, 31 Mar 2020 19:13:05 -0700 csrfmiddlewaretoken = 'Jr4mBrAGlS6dPzADgrj4HaOA2iNtwTG2HQVbL1pTyK1L4lnCSl5mMwkiXDEhKesP' login = '[removed]' password = '********************' FILES: No FILES data I dont even know where to start with troubleshooting this. -
Django custom form not loading in modelformset_factory on html template
I am trying to use my custom form in modelformset_factory but when I set the 'form' attribute in modelformset_factory to my custom form nothing is being displayed. I looked at the documentation and I cannot find what is causing my custom form not to load. this is view: @login_required def post_create(request): data = dict() ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4) if request.method == 'POST': form = PostForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() for f in formset: try: i = Images(posts=post, image=f.cleaned_data['image']) i.save() except Exception as e: break 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 formset = ImageFormset(queryset=Images.objects.none()) context = { 'form':form, 'formset':formset, } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) this is my custom form: class ImageForm(forms.ModelForm): image = forms.FileField( label='', widget = forms.FileInput( attrs={ 'style':'display: none;', 'class':'form-control', 'required': False})) class Meta: model = Images fields = ('image', ) And this is what im using to load the formset: {{ formset }} Appreciate all the help in advance! -
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 …