Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django best practice to show other related models in a view
I'm trying to loop over a related model and show other properties in that model, which includes other relationships, but am having trouble showing that in a view. Any tips would be much appreciated. # model.py class Model1(models.Model): entry = models.TextField(default='') class Model2(models.Model): info = models.TextField(default='') class Model3(models.Model): model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) model2 = models.ForeignKey(Model2, on_delete=models.CASCADE) value = models.TextField(default='') # views.py class IndexView(View): def get(self, request, *args, **kwargs): q = 'lorem' results = Model1.objects.filter(model3__value__icontains=q).distinct('id') context = { 'results': results, } return render(request, 'index.html', context=context) # index.html {% for result in results %} <div> <p>{{ result }}</p> {% for m1 in result.model1.all %} <p> // Tripped up over here. {{ m1.entry }}: {{ m1.model2.info}} </p> {% endfor %} </div> {% endfor %} Sample data for Model3: id | model1 | model2 | value 1 | 1 | 1 | lorem 2 | 1 | 2 | ipsum 3 | 2 | 1 | foo 4 | 3 | 1 | bar Sample preferred output assuming q = o 1 1:1 1:2 2 2:1 What actually happens assuming q = o 1 1: 1: 2 2: This is a simplification of the actual dataset but hopefully there's enough there. Let me know … -
How to Display subcategory under specific Category in Django admin?
All the subcategories are displaying after selecting the main category. But I want to display only the specific categories belongs to the main category. Here is the code: class All_Requests(models.Model): title = models.CharField(max_length=255) categories = models.ForeignKey('Category', on_delete=models.CASCADE, null=True) sub_category = models.ForeignKey('SubCategory', blank=True, on_delete=models.CASCADE, null=True) description = models.TextField(max_length=5000) Here is the category code: class Category (models.Model): name = models.CharField(max_length=150, blank=False, null=False) slug = models.SlugField(max_length=250, unique=True, null=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name Here is subcategory code: class SubCategory(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, null=True) parent = models.ForeignKey('Category', on_delete=models.CASCADE) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def get_all_sub_categories(self): if self.parent: return self.all() return [] def __str__(self): return self.name -
S3 Boto Install Generates ModuleNotFoundError: No module named 'django.utils.six' in Django 3
I have been reading that Django3 has removed access to libraries that use "Six". I use S3 Boto which I installed with: pip3 install boto3 I now get the error: from storages.backends.s3boto3 import S3BotoStorage File "/venv/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 14, in <module> from django.utils.six import BytesIO ModuleNotFoundError: No module named 'django.utils.six' Is there an Django 3 compatible version of boto3 and how can I install it? -
Ajax post call not reaching Django view
In my django site i have an API view that is supposed to increment an integer field when called. However, the ajax call says the view is an invalid url. I have tried changing the url multiple times and changing the view. Here's the error message from console Here's my javascript ajax call function post_(amount){ return $.ajax({ url: '127.0.0.1:8000/increment/', type: "POST", data: { "amount": amount, "user": "{{ user.username }}", }, dataType: "json", success: function (data) { console.log(data); }, error: function (error) { console.log("Error Message: "); console.log(error); } }); } Here's the django view this ajax function is supposed to call @api_view(['POST']) def Increment(request): amount = request.data['amount'] #username_m = request.data['user'] #profile = Profile.objects.filter(user=username_m) profile = get_object_or_404(Profile, user=request.user) print(profile) profile.coins += amount profile.save(update_fields=['coins']) return Response({"message": "Got some data!", "data": request.data}) And here is my urls.py urlpatterns = [ path('increment/', views.Increment, name='increment'), ] Thanks -
how to add model field to object after serialization
I have a CartItem object that I am passing from Angular to Django. I am using DRF to serialize the object. My issue is the CartItem has a Foreignkey relationship to a Cart. If a cart does not exist I am creating the cart at that time. But then I want to add that Cart to the CartItem before I save it, I think I am close but cant figure it out.. views.py @csrf_exempt @api_view(['POST']) def addtocart(request): serializer = CartItemSerializer(data=request.data) customer_id = request.user.id cart_qs = Cart.objects.filter(customer_id=customer_id, placed=False) if serializer.is_valid(): if cart_qs.exists(): existing_cart = cart_qs[0] new_cartitem = CartItems.objects.create(serializer, cart = existing_cart) new_cartitem.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: new_cart = Cart.objects.create(subtotal=0, placed=False, order_total=0, customer=request.user) new_cart.save() serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) model.py class Cart(models.Model): placed = models.BooleanField(default=False) customer = models.ForeignKey(CustomUser, related_name='customuser', on_delete=models.CASCADE) class CartItems(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) It is this line i need help on: new_cartitem = CartItems.objects.create(serializer, cart = existing_cart) Also as a side thing, is this line serializer = CartItemSerializer(data=request.data) creating a CartItem object named serializer?? -
Getting No module named 'storages.backends.s3boto' when boto is installed
I recently upgraded to Django 3 and installed a new virtual environment. I installed all the dependent modules until I got to boto. I installed django storages with the following command: pip3 install django-storages I still received the error: File "custom_storage.py", line 2, in <module> from storages.backends.s3boto import S3BotoStorage ModuleNotFoundError: No module named 'storages.backends.s3boto' Here is what my custom_storages.py looks like: from storages.backends.s3boto import S3BotoStorage class StaticStorage(S3BotoStorage): location = settings.STATICFILES_LOCATION class MediaStorage(S3BotoStorage): location = settings.MEDIAFILES_LOCATION I then tried to install boot directly with the following command: pip3 install boto3 I still get the above error. Is there anything else needed to be installed to get past this error? -
Convert csv to json with django admin actions
Register a csv in django-admin and through an action in django-admin to convert to json and store the value in a JSONField However, in action django-admin I'm getting this error and I can't convert it to json... admin.py (....) def read_data_csv(path): with open(path, newline='') as csvfile: reader = csv.DictReader(csvfile) data = [] for row in reader: data.append(dict(row)) return data def convert(modeladmin, request, queryset): for extraction in queryset: csv_file_path = extraction.lawsuits read_data_csv(csv_file_path) Error: TypeError at /admin/core/extraction/ expected str, bytes or os.PathLike object, not FieldFile -
django web scraper beautiful soup and urllib
iam using scraper to get some data for my database iam adding products from the other site using this code def scrape(): path='' counter=0 session= requests.Session() session.headers={ "User-Agent":"my user agent" } url='some url' content=session.get(url,verify=False).content soup=bs4.BeautifulSoup(content,'html.parser') result=soup.find_all('div',{'class':'column column-block block-list-large single-item'}) for i in result: counter+=1 name=i.find_all('h1',{'class':'itemTitle'})[0] price=i.find('h3',{'class':'itemPrice'}) image=i.find('img',{'class':'img-size-medium imageUrl'})['data-src'] path=f'pics/{counter}.jpg' img=path barcode=f'name{counter}' description='this is my product' urllib.request.urlretrieve(image,path) cat=category.objects.get(id=140) br=branch.objects.get(id=8) products.objects.create(name=name.text,Barcode=barcode,branch=br,image=img, description=description,price=price,category=cat) scrape() its downloading the image of the product but iam getting an error after this value = value.resolve_expression(self.query, allow_joins=False, for_save=True) TypeError: 'NoneType' object is not callable -
how to add a friend system to django
I have been trying to add a friend system to django in which the user can add and remove friends, in the process I found a Friend matching query does not exist error and shows that this part of the code is bad: friend = Friend.objects.get(current_user=request.user) now here I will leave the complete code. views.py def profile(request, username=None): friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() if username: post_owner = get_object_or_404(User, username=username) user_posts=Post.objects.filter(user_id=post_owner) else: post_owner = request.user user_posts=Post.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'friends': friends, } return render(request, 'profile.html', args1) def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friends(request.user, friend) elif operation == 'remove': Friend.lose_friends(request.user, friend) return redirect('profile') models.py class Friend(models.Model): users = models.ManyToManyField(User, default='users', blank=True, related_name='users') current_user = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE, null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) if the profile.html is neede please let me know:) -
There any tutorial for smartcontact with web3.py and django
I want to integrate Smart contact with django project. I know little bit about web3.py but i cannot understand how could a integrate with django. -
Retrieve All Records Which Only Have Children Records
If I have the following two models: class Blog(models.Model): title = models.CharField(max_length=160) text = models.TextField() class Comment(models.Model): blog = models.ForeignKey(Blog) text = models.TextField() As you can see, a Blog may have many Comments, but a Comment may only have one Blog. How can I get all of the Blogs which only have Comments? Thanks How -
Unifying the communication flows in a small/mid sized web project?
I have a project containing those components: 2 clients (SPA) A backend server, using Django framework A REST API, built with Django Rest Framework An additional nodeJS websocket server (to handle full duplex communication between browsers and my SPA) A distributed task tool using Celery, and Redis as message broker. And this works, but don’t you think I’m using too many different tools, for basically just sending data from one component to another? I’d like to simplify it as possible, by removing protocols, technologies, etc. This article about JSON-Pure was a revelation to me. Basically, it consists on building an RPC API on a single endpoint, using JSON messages only, and any transport layer (it could run synchronously over HTTPs, or asynchronously over websocket for example). (By the way, I’m absolutely not a fan of REST, and to be honest my API isn’t RESTful at all and looks like more RPC calls) So, correct me if I’m wrong, but in theory, I could: get rid of my complex REST API over HTTPs + websocket for other messages architecture. replace it with JSON messages sent over websocket for all use cases. Let’s assume I’m plenty of time, and absolutely want to … -
How to effectively deploy a Mezzanine 4.3 blog with django 3 on AZURE, AWS Or Digital Ocean
I've made a mezzanine blog and i'm facing challenges deploying it in AZURE cloud. Everything goes well but, when bind the blog with Engine X it requires me to Update Django for static files (css, js, images to show). When i update django I have the worst problems. It needs me to change lots of file settings some of which i dont even understand. May someone help me if there is a way to Deploy Mezzanine 4.3 and any version of Django without such challenges. It seems building was better than deployment Now. I will be glad to be help in simple steps possible for this to work. Thank you very much in advance -
I am trying to edit the Django database but this error keeps happening:The view social.views.edit didn't return an HttpResponse object
This is my code for my view: def edit(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) else: if form.is_valid(): user = form.save() form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'social/edit.html', args) And here is the code for the form: class EditProfileForm(UserChangeForm): edit ='social/edit.html' class Meta: model = UserProfile fields = ('description', 'image') Here is the model: class UserProfile(models.Model): description = models.CharField(max_length=300, default=' ', blank=True) image = models.ImageField(upload_to='profile_image', blank=True) if you need any more information to help I would be more than gladly to give it to you -
How to debug "make sure every static file has a unique path" warnings?
Running a small django (3.0.5) project dockerized via cookiecutter (1.7.2). And getting a crazy long list of the following warnings on production (not on local). Just copied one but the list is huge: django_1 | Found another file with the destination path 'sass/project.scss'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. django_1 | 0 static files copied to '/app/staticfiles', 2607 unmodified, 2101 post-processed. I tried commenting out one of the two STATICFILES_FINDERS in settings/base.py. But no change. STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", # "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] Then I tried commenting out STATICFILES_DIRS in settings/base.py: # STATICFILES_DIRS = [str(APPS_DIR / "static")] Could someone recommend a way to debug this? I am running out of ideas. -
Checking Form upload progress WITHOUT ajax
So, I am using Vue + Django to make a web app, and I have a simple file upload form like this: <form id="uploadForm" action="" method="POST" enctype="multipart/form-data"> <input v-on:change="handleInputChange" type="file" name="file_data" id="file" accept="video/mp4, video/avi, video/mov, video/wmv, video/flv" > <button type="button" class="btn btn-primary" v-on:click="getUploadInfo" :disabled="!filename">Upload</button> </form> And I need a custom action (determined in javascript) so I have a method which submits it programmatically: getUploadInfo() { videoService.getUploadInfo().then((data)=>{ var upload_link = data.upload_link; var form = document.getElementById('uploadForm'); form.action = upload_link; form.submit(); }); } Now, when I submit the form this way, it works, and I can see that little progress bar in the bottom left corner that shows the upload % as it's going. I'd like to display that number in a custom progress bar so people don't navigate away. However, every single post I can find involves submitting with xhr/ajax/other packages. I would rather not change my approach right now though... surely, if my browser is already displaying the percent completion, there has to be a way to retrieve that number. Am I wrong? Does anyone know? -
Fail to load the model with joblib in the Heroku server
Hy i have build a website with the django framework. I use the sklean library to train my model for my site. I have export the final model with joblib and i pass it in my site. When i need a prediction i load the model with load function from jolib. Fist i tested my site in local host and it run properly. The next step it was to deploy my site to a free host and a good choice is heroku. I have crate all necessary files and the dependencies. In requirements.txt i have the following : Django==2.2.4 django-crispy-forms==1.9.0 django-widget-tweaks==1.4.8 entrypoints==0.3 flake8==3.7.8 gunicorn==20.0.4 joblib==0.14.1 mccabe==0.6.1 numpy==1.18.3 pandas==1.0.3 psycopg2==2.8.3 pycodestyle==2.5.0 pyflakes==2.1.1 python-dateutil==2.8.1 pytz==2019.2 scikit-learn==0.22.2.post1 scipy==1.4.1 six==1.14.0 sqlparse==0.3.0 And for runtime.txt: python-3.7.3 The problem i have is when i need to load my model (GradientBoostingClassifier) in the server i get a value error Buffer dtype mismatch, expected 'SIZE_t' but got 'int' I find a similar post hear about the version of python. In my second attempt to resolve this i create the model in the server and i have again the same results Hear my code of extraction of model import pandas as pd import numpy as np import scipy.io from … -
Django: How to query based on a ForiegnKey and display related data for each ForeignKey?
I am brand new to Django and to programming and I'm trying to make a page that will display the Workout with all the associated Exercises listed under each work out. For example: Chest Chest Press Incline Press Flat Flyes Shoulders Shoudler Press Arnold Press Back/Legs Wide Grip Pull Up Neutral Grip Pull Up Bent Over Row Here is my code: models.py class Workout(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='workouts') title = models.CharField(max_length=100) weight = models.DecimalField(decimal_places=0, max_digits=10000) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title views.py def home(request): context = { 'workouts': Workout.objects.all() } return render(request, 'workouts/home.html', context) def workout(request): context = { 'workouts': Workout.objects.all(), 'exercises': Exercise.objects.all() } return render(request, 'workouts/workout.html', context) workout.html {% extends 'workouts/base.html' %} {% block content %} {% for workout in workouts %} <h1>{{ workout.title }}</h1> {% for exercise in exercises %} <h3>{{ exercise.title }}</h3> <p>{{ exercise.weight }}</p> {% endfor %} {% endfor %} {% endblock content %} In my view.py I have it set to Exercise.objects.all() which just displays all of the exercises under each Workout title, I can figure out how to get only the exercises that are associated with the Workout. Like I said I am … -
Django for loop save instance
I have a form that has two input fields which are returning the id values that will have to be parsed and added into the database. This is the code if form_stage_1.is_valid() and form_stage_2.is_valid(): # GET the new TP to pass to the next instance form_stage_1.instance.created_by = self.request.user new_tp = form_stage_1.save() # Parse and add suppliers to the TP for supplier_id in request.POST["supplier"]: form_stage_2.instance.counterpart = Counterpart.objects.get(pk=supplier_id) form_stage_2.instance.side = 1 form_stage_2.instance.save() form_stage_2.instance.transaction_proposal.add(new_tp) # Parse and add clients to the TP for client_id in request.POST["client"]: form_stage_2.instance.counterpart = Counterpart.objects.get(pk=client_id) form_stage_2.instance.side = 2 form_stage_2.instance.save() form_stage_2.instance.transaction_proposal.add(new_tp) messages.success(request, "TP created successfully".format()) return redirect("add-tp") Unfortunately is only adding one client.. why the form_stage_2.instance.save() is only working once? What would be the most appropriate way to -
Fakepath when uploading file with React on mac
I'm new with React and I try to upload info into my Django API from my React frontend. I followed the Semantic UI React code details on their website about how to manage the onChange and the onSubmit: https://codesandbox.io/s/9y4uv?module=/example.js My probleme is that when I add an Input with a type file the value of image is "C:\\fakepath\\IMG_0320.jpg" In this exact example, how do I need to manage the image so it give me the real image path ? After that my goal is to use Axios to post the value to my Django API. I found some explanations about the fact it's a security features and I understand it. I was not able to implement any detailed solutions because I'm new to React. The context of what I want to do is that I really want user to upload data into the API. Here is the exact same code available on the sandbox but with an additional Input for the image. Thanks a lot for your help. It's very appreciated ! import React, { Component } from 'react' import { Form } from 'semantic-ui-react' class FormExampleCaptureValues extends Component { state = { name: '', email: '', image: '', submittedName: … -
How does the Client in a docker image know the ip address of a server which is in another docker image?
I am using React Client, Django for the backend and Postgres for the db. I am preparing docker images of the client, server and the db. My docker-compose.yml looks like this: version: '3' services: client: build: ./client stdin_open: true ports: - "3000:3000" depends_on: - server server: build: ./server ports: - "8000:8000" depends_on: - db db: image: "postgres:12-alpine" restart: always ports: - "5432:5432" environment: POSTGRES_PASSWORD: bLah6laH614h Because the docker images can be deployed anywhere separately, I am unsure how to access the server from the client code and that of the db's ip in the server. I am new to react,django and dockers. Please help! -
Python request handler not concatenating strings sometimes
I have a request handler that gets a person's signature from a POST request, saves it to Google cloud storage, and then sends a link to the signature in an HTML email. def handler(request): pic = request.POST.get('signature') firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') data = pic[22:] png_image = base64.b64decode(data) link = firstname+'/'+lastname+'/'+"sig.png" #create storage URI temp_location = '/tmp/myfile.png' with open(temp_location,'wb') as f: f.write(png_image) client = storage.Client.from_service_account_json(os.path.abspath('evmailkeys.json')) bucket = client.get_bucket('mybucket') blob = bucket.blob(link) blob.upload_from_filename(temp_location) signature = "https://storage.googleapis.com/mybucket/" + link subject = 'signature' sender = 'email@email.com' message = f"""<div>Signature: <img src={signature} /></div>""" recipients = ["recipient1@email.com"] send_mail(subject, "hello", sender, recipients, html_message=message) This works about half of the time, but the other half of the time, the link to signature only contains firstname, so it doesn't work. Meaning, instead of signature being https://storage.googleapis.com/mybucket/john/galt/sig.png it only sends as https://storage.googleapis.com/mybucket/john. The signature image saves to the right place in cloud storage and exists where it should, but something happens to the link string. Again, this happens about half the time, but the other half of the time it works as intended. Why would that be? -
How to check if billing address of customer is correct in stripe?
I am trying a build a website for a client and I am using stripe for the first time. I build the platform and now I am checking payments using my card. I tried to enter wrong billing address but the payment still went through where as it should have been declined as the billing address is not correct. I am trying to figure out how to setup a functionality in stripe that check whether the billing address is correct. -
Django messages not showing when used with Django CMS
I'm trying to use django messages alongside django-cms. I currently have a login plugin on the homepage that tries to log them in, if failed, it will make an error message and send it back to the homepage. I have both the cms page template and the plugin html checking for messages, but neither of them seem to pick up the message. If I then go to a static page, the messages will show up. view.py def login_view(request): user=EmailBackend.authenticate(username=request.POST.get('email'),password=request.POST.get('password')) if user: login(request,user, backend='django.contrib.auth.backends.ModelBackend') return HttpResponseRedirect('/') else: messages.error(request,'username or password not correct') return HttpResponseRedirect('/') There was a stackoverflow answer to a similar question that said that HttpResponseRedirect was the issue and that using something like render would solve the issue. However, I'm not sure how to use render on a cms page, since I cannot locate the html file location of the homepage. For reference, here is the rendering of the static page in views.py return render(request, 'polls/signup.html', {'form': MyLoginForm}) template (cms page template & plugin template & static page template) {% if messages %} <img src="{% static 'warning.jpg' %}"> {% for message in messages %} <div class="error"> {{ message }} </div> {% endfor %} {% endif %} I have this … -
New Developer trying to run task on Django without page reload. Possibly Alpine.js
Long time reader. First time poster. I've been using a Django site in a Windows only house for about 2 years. We're running scripts on Cisco network equipment with Paramiko. These tasks are run on multiple devices at times, and are time consuming (anywhere from 20 seconds to 3 minutes). I want to submit the script for processing and provide user live updates while the script runs. My research says that Javascript can do this with Ajax by not requiring a page reload. I'd want to attempt with Alpine.js due to its perceived simplicity. My background is in simpler static HTML/CSS type sites. Has anyone tried the Django/Alpine combo at this time? I know Channels/Redis/Celery are popular, but these async requests are onesy twosy affairs, and I feel that a full task queue manager is complete overkill, while not being compatible with Windows for me at this time. I'm not looking for specific code to fix my problem, more direction on how "best" to handle this issue of the user sitting and waiting on a script.