Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
way to implement Django case insensitive for login without using get_by_natural_key?
Need to make user login case insensitive without overiding the function get_by_natural_key, any way to achieve that with __iexact? Overiding any internal functions cant be done ,also note that we users are added from django admin so I just want to make the use login case insensitive -
"nie mo" after python3 manage.py startserver
I'm trying to start local server by using python django, and pycharm returns "nie mo" after python3 manage.py runserver command. Any idea what's the problem? -
Getting 'ModelBase' object is not iterable
I'm creating the following view to get the list of fruits and I got this type error message. I don't know what I missed here: TypeError: 'ModelBase' object is not iterable views.py class FruitsList(APIView): # To list fruits def get(self, request): fruits = Fruit.objects.all() serializer = FruitSerializer(Fruit, many = True) return Response(serializer.data) serializers.py: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruit fields = [ 'id', 'name', 'customers', ] models.py: class Fruit(models.Model): """represents customer fruits""" name = models.CharField(max_length = 100) customers = models.ManyToManyField(Customer) def __str__(self): return self.name Your help is much appreciated! -
convert dropdown to text box when other option is selected
I have a dropdown which displays choices right now it works as just dropdown but when i select the option Other which is a choice when selected it should become textbox. models.py class MyModel(models.Model): task_name = models.CharField(blank=true, choices=somechoiceClass, default='') <div class="col-md-4"> <div class="form-group label-static" :class="{'has-error': errors.task_name && errors.task_name.length > 0}"> <label class="typo__label control-label">Task Name&nbsp;<span class="req">*</span></label> <multiselect v-model="form.task_name" :options="taskNameChoices" :multiple="false" :close-on-select="true" :clear-on-select="true" :preserve-search="true" placeholder="Select" label="text" track-by="id" :hide-selected="false" :show-labels="false"> </multiselect> <span class="help-block" v-show="errors.task_name" v-text="errors.task_name && errors.task_name[0]" v-cloak></span> </div> </div> <script> taskNameChoices: instanceData.case && instanceData.case.task_names || [], this.taskNameChoices = selectedOption.task_names; </script> -
''QuerySet' object has no attribute 'enter_the_destination_account_number'
Can anyone tell me what's wrong with my code? I am trying to use filter but its showing ''QuerySet' object has no attribute 'enter_the_destination_account_number'. I tried get() but it shows, get() returned more than one MoneyTransfer -- it returned 14!. here's some snap of code. Thanks in advance models.py class Status (models.Model): user_name = models.CharField(max_length=150, default=None) account_number = models.IntegerField() balance = models.IntegerField() phone_number= models.CharField(max_length=20, default=0) class MoneyTransfer(models.Model): enter_your_user_name = models.CharField(max_length = 150, default = None) enter_the_destination_account_number = models.IntegerField() enter_the_destination_phone_number=models.CharField(max_length=20, default=None) enter_the_amount_to_be_transferred_in_INR = models.IntegerField() views.py def TransferMoney(request): if request.method == "POST": form = forms.MoneyTransferForm(request.POST) if form.is_valid(): form.save() curr_user = models.MoneyTransfer.objects.filter(enter_your_user_name=request.user) dest_user_acc_num = curr_user.enter_the_destination_account_number #dest_phone number add korte hobe dest_phone_num= curr_user.enter_the_destination_phone_number temp = curr_user # NOTE: Delete this instance once money transfer is done dest_user = models.Status.objects.get(account_number=dest_user_acc_num) # FIELD 1 dest_phn= models.Status.objects.get(phone_number= dest_phone_num) transfer_amount = curr_user.enter_the_amount_to_be_transferred_in_INR # FIELD 2 curr_user = models.Status.objects.get(user_name=request.user) # FIELD 3 # Now transfer the money! curr_user.balance = curr_user.balance - transfer_amount #dest_phn.balance = dest_phn.balance + transfer_amount dest_user.balance = dest_user.balance + transfer_amount # Save the changes before redirecting curr_user.save() dest_user.save() temp.delete() # NOTE: Now deleting the instance for future money transactions return redirect(index) else: form = forms.MoneyTransferForm() return render(request, "epayapp/Transfer_money.html", {"form": form})