Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at /customers/f0e85ace-438f-4c61-a129-6d5986e6f346/ 'customer' object has no attribute 'get'
i have just started django and i am struggling to find error .Seems like get() method is not being recognized .What should i do?I would really appreciate your help from django.db import models from django.core.validators import RegexValidator import uuid # Create your models here. class customer(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) name=models.CharField(max_length=200,null=True) phone_no=models.CharField(max_length=200, validators= [RegexValidator(r'^\d{1,10}$')],null=True) email=models.EmailField(max_length=200,null=True) def __str__(self): return self.name class tag(models.Model): name=models.CharField(max_length=200,null=True) def __str__(self): return self.name class products(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) categories=[ ('organic','organic'), ('inorganic','inorganic') ] name=models.CharField(max_length=200,null=True) price=models.FloatField(null=True) manufacturedate=models.DateTimeField(auto_now_add=True,null=True) description:models.TextField(null=True) categories=models.CharField(max_length=200,null=True,choices=categories) tag=models.ManyToManyField(tag) def __str__(self): return self.name class order(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) status=[ ('pending','pending'), ('out of stock','out of stock',), ('Delivered',('Delivered')) ] ordered_date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=200,null=True,choices=status) customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL) urls.py url seems ok i could not find any mistake from django.urls import path from . import views urlpatterns=[ path('',views.home), path('products/',views.product), path('customers/<str:pk>/',views.customer), ] views.py Here in the customer it is not it says get is not the attribute .seems like i am missing something from django.shortcuts import render from .models import * # Create your views here. def home(request): customers=customer.objects.all() orders=order.objects.all() total_customers=customers.count() total_orders=orders.count() delivered=orders.filter(status='Delivered').count() pending=orders.filter(status='pending').count() context={'customers':customers,'orders':orders,'total_customers':total_customers, 'total_orders':total_orders,'delivered':delivered, 'pending':pending } return render(request,'accounts/home.html',context) def product(request): product=product return render(request,'accounts/products.html') def Customer(request,pk): Customer=customer.objects.get(id=pk) return render(request,'accounts/customers.html') -
Should I use Django Function based views or Class based views for better functionality?
I am just learning Django, and I am attempting a project to create a notes app. During the process of the project, a friend of mine advised me to use function-based views, but I later discovered that class-based views can be customized too. Given that both can work fine for my little project, is it best practice to use function-based views from scratch or to override class-based views methods? Thank you. -
Django Browser back button issue after logout not able to login again
I am trying to integrate Azure AD with Django and achieve single page application behaviour.When I login with Azure ad at first time it working fine, i logout and click Browser Back button from Logout page it is stay on logout page but After that i'm try to login from logout page I'm not able to login again. Index content doesn’t load, content remains same as logout page. -
how to clear an input fields when i click another tab it should clear the input field data Any suggestions?
any suggestions Iam working on one data filtering part in my task it takes an input values it shows filter options but if i open another tab of same page or switched to another page still it holds given input values my motto is clear the screen when we click another page or tab any suggestions please????? -
How to call bussines logic from seperate class in view in Django?
I am using django framework. And I have some functionality for uploading files. And I have a textarea where the extracted content of the uploaded file will be shown. So for example if you upload a pdf file within a image that contains text. In the textarea the text will be shown. But the logic for extracting the text from the image of course doesn't belong too the method in the view. So I made a seperate class for it, with name: extractingTextFromFile.py that looks like this: import io from tracemalloc import start from PIL import Image import pytesseract from wand.image import Image as wi import re class ExtractingTextFromFile: def extractingtextfromimage(): text_factuur_verdi = [] #image = pdfFile.convert('jpeg') imageBlobs = [] for img in image.sequence: imgPage = wi(image=img) imageBlobs.append(imgPage.make_blob('jpeg')) for imgBlob in imageBlobs: image = Image.open(io.BytesIO(imgBlob)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) and I have the views.py: from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect from .forms import ProfileForm from .models import UploadFile import extractingTextFromFile as textFromFile from wand.image import Image as wi from PIL import Image import pytesseract from django.conf import settings import io import os class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", … -
Insert data from an API on the database - Django project
I would like to save product data from an API in a table in my database that I created Models.py class Product(models.Model): code=models.CharField(max_length=70,primary_key=True) designation=models.TextField() def __str__(self): return self.product.code views.py from .models import Product def products(request): url='http://myAPI/Product/GetProducts' x=requests.get(url) content=x.json() all_product=content['products'] for product in all_product: product.save() return render(request,'cart/product.html',context) How to proceed to insert each product in the table with the for loop ?? Note that each product is characterized by a code and a designation -
Can someone help me to how to add a custom button when I clicked edit in Po or So and Once I clicked that button , one internal Suitelet should open
/** @NApiVersion 2.x @NScriptType ClientScript */ define(["N/record", "N/url",'N/currentRecord'], function (record, url,currentRecord) { function onclick_callforSuitelet(){} function pageInit() { var record = currentRecord.get(); var recordId = record.id; var recordType = record.type; log.debug("recId", recordId); log.debug("recType", recordType); var suitletURL = url.resolveScript({ scriptId:'customscriptss_suiteletbutton', deploymentId:'customdeployss_suiteletbutton', returnExternalUrl: true, params: { recId: recordId, recType: recordType } }); log.debug("suitletURL", suitletURL); } return{ pageInit:pageInit, onclick_callforSuitelet:onclick_callforSuitelet } }); -
The problem of not quickly adding the product to the shopping cart in django
I am building an online store with django, and I encountered a problem. The problem is that I can add the product through the product details page. But I can't do the same thing through the Add to cart button directly on the main page of the site. And my main problem is that when I directly click the Add to cart button on the main page. I am redirected to the shopping cart page, but without any products. All required images This is index.html in shop app: <div class="product"> <div class="product-img"> <img src="{{ product.image.url }}" alt=""> <div class="product-label"> <span class="sale">-30%</span> <span class="new">NEW</span> </div> </div> <div class="product-body"> <h3 class="product-name"> <a href="{{ product.get_absolute_url }}">{{ product.name }} </a> </h3> <h4 class="product-price">${{ product.price }}</h4> <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> </div> <div class="product-btns"> <button class="add-to-wishlist"><i class="fa fa-heart-o"></i><span class="tooltipp">add to wishlist</span></button> <button class="add-to-compare"><i class="fa fa-exchange"></i><span class="tooltipp">add to compare</span></button> <button class="quick-view"><i class="fa fa-eye"></i><span class="tooltipp">quick view</span></button> </div> </div> <div class="add-to-cart"> <form action="{% url 'cart:cart_add' product.id %}" method="post"> {{ cart_add_product_form }} {% csrf_token %} <button type="submit" class="add-to-cart-btn"> <i class="fa fa-shopping-cart"></i> add to cart </button> </form> </div> </div> This is detail.html in cart app: <table class="cart table"> … -
Django similar queryset optimization
I am making a filmography website. However, I am having a hard time optimizing the queryset in the detailview. class Actor(model.Models): id = models.IntegerField() name = models.CharField() class Movie(model.Models): id = models.IntegerField() movie_title = models.CharField() actor = models.ManyToManyField(Actor, related_name='relations') class ActorView(DetailView): model = Actor context_object_name = 'actor' template_name = 'actor.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['movies'] = self.object.relations.all() return context <div> {{ actor.name }} {% for movie in movies %} {{ movie.movie_title }} {% for actor_info in movie.actor.all %} {{ actor.name }} {% endfor %} {% endfor %} </div> I checked the sql tap in the django debug console. {% for actor_info in movie.actor.all %} {{ actor.name }} {% endfor %} Similar queries are being executed repeatedly in the code above. And data connection and query execution time are also very slow. How can I optimize this part in the view or model? -
Getting current username in utils.py django
I am new to django, trying to create a number sequence field while loading the page, the combination of current datetime + current username + count(his posts on this month) + 1 . To achieve this i use initial . forms.py class PostForm(ModelForm): post_no = forms.CharField( label='Post No',initial=getPostNo, widget=forms.TextInput(attrs={ 'class': 'form-control', 'readonly': 'readonly', 'placeholder':'Post No' }) in utils.py the definition of getPostNo def getPostNo: from .models import Posts m = datetime.now().month y = datetime.now().year tme = datetime.now().strftime("%d%m%Y") cnt = Posts.objects.filter(employee_id=1,post_date__month=m,post_date__year=y).count()+1 #here i need to filter using the current user id logged in . i gave 1 for testing return tme+str(cnt)+str(current username) //here i need current username i couldnt pass the logged in userid to getPostNo from forms.py and also i can't get request.user in utils.py. please suggest the right way to do this. thanks for any help. -
How to make autocomplete_fields search in model's string representation in Django 3
As I am using string representation of a model, it is also shown in a autocomplete_fields (Select2). But the problem is that when i try to search in the field, it is searching the model's name field, not string representation. Here is my code example: models.py class Store(models.Model): name = models.CharField(max_length=256) class Department(models.Model): name = models.CharField(max_length=256) store = models.ForeignKey(Store, on_delete=models.CASCADE) class Shelf(models.Model): name = models.CharField(max_length=256) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __string__(self): return f'{self.department.store.name} {self.department.name} {self.name}' class Product(models.Model): name = models.CharField(max_length=256) shelf = models.ForeignKey(Shelf, on_delete=models.CASCADE) admin.py @admin.register(Product) class ProductAdmin(admin.ModelAdmin): autocomplete_fields = ('shelf',) list_display = ('name', 'shelf') Is it posible to search by model string representation in this case? -
Django/Postgresql sequence not set when creatin objects in views
I have write a view that load an excel file as dataframe and use this datafralme to create or update records in a Postgresql database. But I can figure out why Postgresql sequence are not updated? This lead to database error when try add other records via admin forms. My stack: Django 2.2.5/Python 3.7.4/Docker/Docker-compose/Postgresql 2 models used: PData (86 records) and PForm (22 records), with PData_ide_seq and PForm_ide_seq, respectively When I check PForm_ide_seq, current value is 1 instead of 22 What is going wrong? @login_required def update_parameters(request): if request.is_ajax() and request.method == "POST": if ParametersFile.objects.all(): LAST_PARAMETER_FILE = ParametersFile.objects.all().last().upload dcf_queries = pd.read_excel(f'./{ LAST_PARAMETER_FILE }',sheet_name='data_queries_definitions').fillna('') missing_forms_queries = pd.read_excel(f'./{ LAST_PARAMETER_FILE }',sheet_name='form_queries_definitions').fillna('') print(LAST_PARAMETER_FILE) for record in dcf_queries.to_dict(orient='records'): PData.objects.update_or_create( ide=record['ide'], # filter to search for existing objects => should not be pass to default (if not IntegrityError) defaults = { 'query_type':record['query_type'], 'crf_name':record['crf_name'], 'crf_table':record['crf_table'], 'variable_name':record['variable_name'], 'variable_label':record['variable_label'], 'query_condition':record['query_condition'], 'query_message':record['query_message'], 'fields_to_display':record['fields_to_display'], 'activated': True if record['activated'] == 1 else False, } ) for record in missing_forms_queries.to_dict(orient='records'): PForm.objects.update_or_create( ide=record['ide'], # filter to search for existing objects => should not be pass to default (if not IntegrityError) defaults = { 'query_type':record['query_type'], 'source_form':record['source_form'], 'source_condition':record['source_condition'], 'search_form':record['search_form'], 'search_condition':record['search_condition'], 'query_message':record['query_message'], 'activated': True if record['activated'] == 1 else False, } ) return JsonResponse({"response": "Queries definitions table … -
Sum of a the column values of pivot_table - pandas
df = pd.DataFrame(result) df_pivot = pd.pivot_table( df, index=["sizeoforchardholding", "nooforchardists"], columns="fruit_plant_kind", values=["sizeoforchardholding", "nooforchardists"], aggfunc='sum', margins=True, margins_name='Sum', fill_value=0, ).reset_index() I want to find the sum of each column in the end but when I do it with margin it throws an error. Error: Survey Report Had an exception Grouper for 'sizeoforchardholding' not 1-dimensional Internal Server Error: /KindWise-Fruit-Survey-OrchardCount how can I find the sum of each column in the end. -
Using UpdateModelMixin update() to update record
How can I perform a partial update within list()? I am trying to update the balance value in a Wallet record class WalletListCreateAPIView(generics.ListCreateAPIView, mixins.UpdateModelMixin): queryset = Wallet.objects.all() serializer_class = WalletSerializer def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) def list(self, request, *args, **kwargs): current_user = request.user wallets = Wallet.objects.filter(user=current_user) balances = get_wallet_balances([wallet.address for wallet in wallets]) for wallet in wallets: # Update wallet balance based on address balance = balances[wallet.address] return super().list(request, *args, **kwargs) -
Synbolik link on web server doesn't work?
I have static folder serving the files on uwsgi. /user/app/static/ lrwxrwxrwx 1 root root 23 Oct 13 09:40 _out -> /usr/src/app/_mat/_out/ drwxr-xr-x 8 root root 4096 Oct 13 09:49 assets drwxr-xr-x 8 root root 4096 Oct 13 09:40 pages in this case, the imagefiles under assets can be appeared correctly, however the image files under _out can not be accessed.(404 error occurs) static/assets/test.png is ok static/_out/test.png returns 404 error I checked the permissions. Generally speaking, does symbolic link work under web server? -
how i can test views py django
i just learning how to pytest my code in django, and i need your help. So, i have tested my forms.py already,and now i want to test my views.py. I know that i need to test is it post on page,like by response on by ORM, but i cant understand how to do that, probably with my factories or no? This is my views.py class AddPost(CreateView): model = Posts form_class = PostsForm template_name = 'posts/addpost.html' success_url = '/' def form_valid(self, form): instance = form.save(commit=False) if self.request.user.is_authenticated: instance.owner = self.request.user instance.save() return HttpResponseRedirect(self.get_success_url()) class ShowPost(ListView): model = Posts template_name = 'posts/allposts.html' paginate_by = 2 this is test_forms @pytest.mark.django_db(True) class TestPostCreationForm: def test_form(self): proto_post = PostsFactory.build() form_payload = { 'phone_number': proto_post.phone_number, 'title': proto_post.title, 'type': proto_post.type, 'text': proto_post.text, 'price': proto_post.price, 'status': proto_post.status, 'image': proto_post.image, } form = PostsForm(form_payload) assert form.is_valid() instance = form.save() assert instance.phone_number == proto_post.phone_number assert instance.title == proto_post.title assert instance.price == proto_post.price and factories from users.tests.factories import UserFactory def get_mock_img(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGB", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, name=name) class PostsFactory(factory.DjangoModelFactory): owner = SubFactory(UserFactory) phone_number = factory.Faker("phone_number", locale='uk_UA') title = factory.fuzzy.FuzzyText(length=50) text = factory.fuzzy.FuzzyText(length=250) price = factory.fuzzy.FuzzyDecimal(10.5, 50.5) status … -
Python Django use mysql function SHA2('pass',256)
I am creating application in Django and now I want create table with username and password. Right now, we generating password with mysql function SHA2('password',256) and my question... is possible use it the same in Django model? I mean everything what will be save to password row, will be saved as hash sha2 in admin app or I must create functions? this is my models.py class Users(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=128) status = models.IntegerField() valid_from = models.DateTimeField() valid_to = models.DateTimeField() online = models.IntegerField() ip = models.CharField(max_length=20) created = models.DateTimeField() def __str__(self): return f'{self.username}' -
How to connect QuestDB with Django?
Is there any way to connect QuestDB with Django? I have looked into this documentation, but there are no specific engine for that purpose. Is there a way to set the settings in the settings.py file? Thanks. -
Crop multiple images In HTML form using Javascript
I am working on a project in Django , the functionality requires to add 4 images on a single html form for POST submission to the server. Now the images needs to be cropped individually ,for each selection. And should be able to submit it. I am able to do it for single image but cant do it for each image , a solution is JS will be highly helpful. -
Downloading a file from Django template on click doesn't work
I tried multiple ways to download a file on click from a Django template, but the download just won't start. Here's my view where I get the file path: def success(request): model_file_path = request.session.get('model_file_path') if request.method == 'POST': return render(request, "success.html", {'filepath': model_file_path}) else: return render(request, "success.html", {'filepath': model_file_path}) And here is what I tried in the success template with no success: <a href='{{filepath}}' download>download</a> <a href='{{ MEDIA_URL }}{{filepath}}' download={{filepath}}>download</a> <a href='{{filepath}}' download={{filepath}}>download</a> It just won't trigger a download, although the path is correct. -
Updating Database via GET request to Generic views in Django
I've got this Generic view that would list records from my DB for GET request to localhost:8000 However, I also want to UPDATE those records upon GET. For instance, GET localhost:8000 would return a list like so: [ { "user": 1, "address": "sdfgasgasdfg", "balance": "123.00000000" }, { "user": 1, "address": "sdfgasgasdfg25", "balance": "123.00000000" } ] Upon GET, I would like to also make an API to https://www.blockchain.com/api/blockchain_api to get the latest BTC balance and update the balance values for those addresses in my DB. Not quite sure how to do so with generic views view class WalletListCreateAPIView(generics.ListCreateAPIView): queryset = Wallet.objects.all() serializer_class = WalletSerializer model class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=34) balance = models.DecimalField(max_digits=16, decimal_places=8) slug = models.SlugField(max_length=34, blank=True, null=True) def __str__(self): return self.address def save(self, *args, **kwargs): self.slug = slugify(self.address) super().save(*args, **kwargs) -
Generate data when button/link is clicked Django
I'm very new to Django and web apps. I have an HTML page that allows users to search database for player names. An HTML table is returned. Each entry is a player's performance in relation to a game they played. Each game has 10 players associated with it search_db.html <h1>Search Results for: {{searched}}</h1> <table> {% for player in match %} <tr> <td> <a href=search_player_db/{{player.match_id}}>{{player.match_id}}</a> </td> <td>{{ player.name}}</td> <td>{{ player.role}}</td> <td>{{ player.win_or_loss}}</td> </tr> {% endfor %} </table> {{IM TRYING TO GENERATE DATA HERE}} The match id is a link that brings the user to a page with additional details related to the match match_details.html {%block stats%} <body> <h1>Winning team</h1> {%for player in winners %} <li> {{player.name}} {{player.role}} </li> {%endfor%} <h1>Losing team</h1> {%for player in losers %} <li> {{player.name}} {{player.role}} </li> {%endfor%} </body> {%endblock%} Instead of being redirected to a new page when clicking the link, I'd like to load the content from match_details into the page below the table on search_db.html through the button/link in search_db.html views.py def search_playerdb(request): if request.method == "POST": searched = request.POST['searched'] players = PlayerInfo.objects.filter(player_name__contains=searched) context={ 'searched': searched, 'players': players} return render(request, 'searchdb.html', context) else: return render(request, 'searchdb.html', {}) def display_match(request, matchid): match = PlayerInfo.objects.filter(match_id=matchid) winners = … -
Serving static folder not from nginx but from uwsgi
I am using nginx - uwsgi setting. I want to serve the static folder from uwsgi not nginx. So I didn't set any static settings on nginx nginx setting server { listen 80; server_name dockerhost; charset utf-8; location / { proxy_pass http://127.0.0.1:8011/; include /etc/nginx/uwsgi_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_pass_header X-XSRF-TOKEN; } } uwsgi start command uwsgi --http :8011 --processes 4 --threads 1 --module myapp.wsgi --logto /tmp/mylog.log and my django settings is here below. settins.py STATIC_URL = '/static/' STATIC_ROOT = "/usr/src/app/static" STATICFILES_DIRS = ( os.path.join(BASE_DIR,'frontend/dist'), ) urls.py urlpatterns += [ path('sp/', SeparateView.as_view()) ] if settings.DEBUG: urlpatterns += [ re_path(r'^static/(?P<path>.*)$', views.serve), ] When DEBUG=True, it works, static files are served,but DEBUG=False {% static %} in template doesn't work for it, the file under static directories are 404 error. I have done manage.py collectstatic and confirmed that there are files under /usr/src/app/static Where should I check ? -
How to prevent the trigger of django signals based Field value of Model?
I have a model with a boolean field. Based on the value of this boolean field I want to trigger a post_save signal in django. How can I implement it? Thanks in advance -
Django App on Azure App Service. How to upload files and view the uploaded files
I had created a Django app in which user can upload files and view it in dashboard. Its working fine in local system but when I deployed it in Azure App Service the file is uploading but can't view the file in dashboard. Its shows no file but i can see the file has uploaded in the directory mentioned and the url is correctly pointing to the file uploaded.