Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LookupError: No installed app with label 'app_name' when running tests
I am trying to set up a test database in a Django project that's a couple of years old. I'm using Postgres and the default database (non-test) works fine. I run it against a database instance in a Docker container. When try I run my tests, however, this is what happens: Got an error creating the test database: database "mytestdatabase" already exists Type 'yes' if you would like to try deleting the test database 'mytestdatabase', or 'no' to cancel: I type yes. I then get a traceback and at the bottom it says LookupError: No installed app with label 'providers'. These are my database settings: DATABASES = { 'default': { 'NAME': os.getenv('POSTGRES_NAME'), 'USER': os.getenv('POSTGRES_USER'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'TEST': { 'NAME': 'mytestdatabase', }, } } These are my installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'providers.apps.ProvidersConfig', 'storages', 'accounts', 'sso', 'rest_framework', 'widget_tweaks', 'anymail', 'mailchimp_marketing', 'mailchimp_marketing.api_client', 'analytics', ] This is the entire traceback: Creating test database for alias 'default'... Got an error creating the test database: database "mytestdatabase" already exists Type 'yes' if you would like to try deleting the test database 'mytestdatabase', or 'no' to cancel: yes Destroying old test database … -
Store list variable with Avg function in a Django aggregate
How to store and pass multiple Avg function in an aggregate the code below gives error of type views.py riasec_avg =[Avg('realistic'),Avg('investigative'),Avg('artistic'),Avg('social'),Avg('enterprising'),Avg('conventional')] context['riasec_male'] = Riasec_result.objects.filter(user__profile__gender='M').aggregate(riasec_avg) context['riasec_female'] = Riasec_result.objects.filter(user__profile__gender='F').aggregate(riasec_avg) -
Django self join with ForeignKey (ORM)
I have an Event Model: class Event(models.Model): message = models.CharField(max_length=128) timestamp = models.DateTimeField() cancels_event = models.ForeignKey('self', on_delete=models.CASCADE) I'm analysing lots of event messages, but firstly I need to check if the event has been canceled. Let's say I receive an Event_1, then I receive an Event_2 with Event_2.cancels_event=Event_1, so Event_2 cancels Event_1. I want to find out, given a subset of Events, which Events from this subset have been canceled. In SQL I'd use a join with self: SELECT * FROM Event e1 JOIN Event e2 ON e1.id = e2.cancels_event But I don't know how to do it within Django ORM. -
django 3.2 how to save multiple related model in a single model like inlineformset_factory using django-rest-framework?
I would like to store multiple checklist that belongs to a single declaration using django rest framework but i dunno how to implement it thanks for the help. Here are my models. class Question(models.Model): id = models.BigAutoField(primary_key=True) question = models.CharField(max_length=50) class Declaration(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, related_name='declarations', on_delete=models.CASCADE) class Checklist(models.Model): id = models.BigAutoField(primary_key=True) declaration = models.ForeignKey(Declaration, related_name='checklist_declarations', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='checklist_questions', on_delete='models.CASCADE) is_yes = models.BooleanField() -
Sending image from front end(JavaScript) to backend(Django)
I have a image at the front end and I want to send it to the backend. I have simple JavaScript at the front end and Django-python at the backend. I have tried dozens of different methods and spent weeks but I am not able to figure this out. Can you guys suggest how can I achieve this on front end(sending part) and backend(receiving part). A piece of code with an advice would be really appreciated. I am using function based views on the backend. Can someone help me out with the backend code (if the front end code is right) to handle incoming from the front end. Because I have first converted the image file to base 64 stream in order to send it to the backend through fetch api. Front end code: const { snippet, transform } = anno.getImageSnippetById(annotation.id) //this function returns a DOM canvas element in snippet variable const base64Canvas = snippet.toDataURL("image/jpeg").split(';base64,')[1]; //converting into a base64 stream fetch(url1,{ method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body: {'snippet':base64Canvas} }) Backend code: def snippetCreate(request): serializer = Annotated_SnippetsSerializer(data=request['snippet']) image = base64_to_image(base64_string=serializer.data) img = Annotated_Snippets(asnippet=image) img.save() return Response({'success':'success'}) ``` base64_to_image: ```def base64_to_image(base64_string): format, imgstr = base64_string.split(';base64,') ext = format.split('/')[-1] return ContentFile(base64.b64decode(imgstr), name=uuid.uuid4().hex + … -
How can I set the `max` attribute of a number inout form widget within the view in Django?
so I have a form that allows the user to input a withdraw amount. I want the form to be rendered with the max attribute according to an aggregated value within a queryset in my view. But how can I actually update the form's attribute in the view before returning it to the client? # views.py def render_dashboard_overview(request): # Get the withdrawal form withdraw_form = WithdrawForm() # How to now set the `max` attr. of the number input to 500 for example? ... # forms.py class WithdrawForm(forms.Form): """ A form to withdraw available funds from Farena to the users bank account """ withdraw_amount = forms.FloatField(required=True, widget=forms.TextInput(attrs={ 'step': 0.01, 'min': 0 })) -
How convert PDF file of CSV file using python web development project
I used may ways in my knowledge to do I know to convert a pdf file to csv but I wanted to know how to do it in a website project i.e by using django framework how we can do it ... -
How to have multiple return statement in python django?
In my Views.py, I try to download the csv file first to client side then only wish to redirect to another page. Below was my code def main(request): ... ... url = '//file1.km.in.com/sd/recipe/' +"/"+ model + "_" + code + ".csv" filename=model + "_" + code + ".csv" download_csv(url,filename) data = {"TableForm": TableForm, "devicelist": devicelist_1} time.sleep(10) return redirect('/ProductList/BetaTest', data) def download_csv(url,filename): csv = process_file(url) response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename return response def process_file(file_handle): df = pd.read_csv(file_handle, index_col=False) return df.to_csv(index=False) However, download function didn't work but it directly redirect to BetaTest page. I try to edit to below code, and now the download function is work but it cannot redirect to another page: def main(request): ... ... data = {"TableForm": TableForm, "devicelist": devicelist_1} csv = process_file(url) response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename return response time.sleep(10) return redirect('/ProductList/BetaTest', data) Is there any ideas to overcome this issue? -
object carousel in django
{% for object in obj %} {{ object.title }} {{ object.sub_title }} Previous Next {% endfor %} -
Django Matching query don't exist in AddProduct.objects.get(Name=productname[i])
I have a model AddProduct and StockIn. When a new stock are purchased from dealer than all purchased product are get added in StockIn model. And Existing products are updated in AddProduct model. My AddProduct models are as follows class AddProduct(models.Model): Name = models.CharField(max_length=120,verbose_name="name") Description = models.CharField(max_length=120, verbose_name="description") Unit = models.ForeignKey(Unit,on_delete=models.CASCADE,max_length=150,verbose_name='unit') purchaseRate = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="purchase rate") AvgRate = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="avg rate") OpnStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="Opening stock") ClosingStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="closing stock") StoreLocation = models.CharField(max_length=120,verbose_name="store location") MinStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="minimum stock") ReOrder = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="reorder") MaxStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="maxstock") Group = models.ForeignKey(ProductGroup,on_delete=models.CASCADE,max_length=150,verbose_name='productgroup') CGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="CGST") SGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="SGST") IGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="IGST") Validity = models.IntegerField(verbose_name="validity") Updated = models.DateTimeField(auto_now=True) while my StockIn model are as follows class StockIN(models.Model): GrnNo = models.IntegerField(verbose_name="GrnNo") Date = models.DateTimeField(default=timezone.now) Supplier = models.ForeignKey(AddSupplier,on_delete=models.CASCADE,max_length=150,verbose_name='supplier') InvoiceNo = models.IntegerField(verbose_name="invoice No") InvoiceDate = models.DateTimeField(default=timezone.now, verbose_name="Invoice Date") ProductName = models.CharField(max_length=120,verbose_name="productName") Quantity = models.IntegerField(verbose_name="quantity") Unit = models.ForeignKey(Unit,on_delete=models.CASCADE,max_length=150,verbose_name='unit') Rate = models.CharField(max_length=120,verbose_name="rate") Value = models.CharField(max_length=120,verbose_name="value") DisPer = models.CharField(max_length=120,verbose_name="disper") DisValue = models.CharField(max_length=120,verbose_name="disvalue") Taxable = models.CharField(max_length=120,verbose_name="taxable") CGSTPER = models.CharField(max_length=120,verbose_name="cgstper") CGST = models.CharField(max_length=120,verbose_name="cgst") SGSTPER = models.CharField(max_length=120,verbose_name="sgstper") SGST = models.CharField(max_length=120,verbose_name="sgst") IGSTPER = models.CharField(max_length=120,verbose_name="igstper") IGST = models.CharField(max_length=120,verbose_name="igst") NetAmt = models.CharField(max_length=120,verbose_name="netamt") I recieving a list of product details from template. So after submiting the request i am getting the result … -
Django, editable help texts of form field
I want to edit help texts of each form field on the frontend, is there any method to accomplish this? -
Product sorting based on prize in ecommerce
I am trying to perform a prize sorting(low to high and vice versa)on product varients on my e-commerce website. since I am new to this, I am a bit confused. Here is my model: class Product(models.Model): Name = models.CharField(max_length=250) Description = RichTextField(null=True) Features = RichTextField(null=True,default=None) Varient_Type = models.ForeignKey(VarientType,on_delete=models.CASCADE) Product_Category = models.ForeignKey(Catogory,on_delete=models.CASCADE) Product_Brand = models.ForeignKey(Brand,on_delete=models.CASCADE,blank=True,null=True) related_product=models.ManyToManyField('Product',blank=True,null=True) status = models.CharField(default='Active',max_length=20, choices=( ('Active','Active'), ('Inactive','Inactive') )) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "Products" ordering = ['-created_at'] def __str__(self) -> str: return self.Name class Product_Varients(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) Sku_Code=models.CharField(max_length=100) Varient_Values = models.ForeignKey(VarientValues,on_delete=models.CASCADE) Selling_Prize = models.DecimalField(max_digits=12,decimal_places=2) Display_Prize = models.DecimalField(max_digits=12,decimal_places=2) Product_stock = models.PositiveIntegerField(blank=True,null=True) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(default='Active',max_length=20, choices=( ('Active','Active'), ('Inactive','Inactive') )) class Meta: db_table = "Product_Varients" ordering = ['-created_at'] class ProductImage(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) Thumbnail_image = models.ImageField(upload_to='Products',null=True) I am passing all products to the template and iterating the product varients of each product and displaying only the first varient. here is my template code: <div class="col-md-9 product-model-sec"> {% for product in products %} {% for pro in product.product_varients_set.all %} {% if forloop.first %} <div class="product-grid love-grid"> <div class="more-product"><span> </span></div> <div class="product-img b-link-stripe b-animate-go thickbox"> <div class="shrt"> <a href="javascript:void(0)" data-id="{{pro.id}}" class="button add-Cart add-to-wish-btn" title="Add to Wishlist"></span>Wishlist</a> </div> {% for img in product.productimage_set.all%} {% if forloop.first %} <a href="{% url … -
django views pass a list in aggregate function
So I have a list and I want to pass it on to .aggregate() so it looks like .aggregate(riasec_avg) but instead I get type error views.py riasec_avg =[Avg('realistic'),Avg('investigative'),Avg('artistic'),Avg('social'),Avg('enterprising'),Avg('conventional')] context['riasec_male'] = Riasec_result.objects.filter(user__profile__gender='M').aggregate(riasec_avg) context['riasec_female'] = Riasec_result.objects.filter(user__profile__gender='F').aggregate(riasec_avg) I also have tried () instead of [] -
How to enforce user permissions using user Groups in Django Class Based Views
In my Django app, I have created Groups and assigned (selectively) Permissions the Groups. And later assigned the Groups to the Users. These steps were carried out in the app's admin. Now I am trying to restrict certain views to the users (using CBV) like as under: class UomListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): template_name = "..." context_object_name = 'unit_meas' model = U_o_M permission_required = 'myapp.view_u_o_m' def get_queryset(self): return U_o_M.objects.order_by('uom') As expected I am able to restrict access to the view to users who are assigned the permission "myApp.view_u_o_m". My understanding of the system is that if a user is attached to a Group which has permission "view_u_o_m" should be automatically assigned the privilege of accessing the view. To quote (from Admin > Change User page): The groups this user belongs to. A user will get all permissions granted to each of their groups. However, when I remove the line permission_required = 'myApp.view_u_o_m', anticipating that the user Permission will hold good but it doesn't and I get an error saying View is missing the permission_required attribute. Define... or override .get_permission_required(). Obviously I am wrong about how defining "Groups" affect the Permissions scenario. May I ask somebody to help clarify the issue here and … -
How can I return multiple values from hidden input when I click the button with jquery?
When I click the button, I want to get the value of the hidden input, but when I write it like this, it only takes the first value. <div> <input type="hidden" name="producecode" class="pdcode" value="{{per.produceCode}}" /> <input type="hidden" name="useremail" class="uponequantity" value=" {{user.username}}" /> <button class="btn btn-sm btn- primary" onclick="upoq()"><i class="fa fa-plus"></i></button> $(".up").click(function(){ $(".prdtd").find("input:first- child").attr("value"); $(".pcode").val()} -
Stop CSS loader spinning if form validation error, django, javascript
How do I stop the loader spinner showing if the forum submit fails and the user has to complete a missing form field. The spinner keeps spinning forever while the user enters the missing information. My submit button in the form: ... <div class="control"> <button type="submit" class="button" onclick="showDiv()">Submit </button> </div> </form> My spinning loader below the form: <span class="loader" id="loadingdisplay" style="display:none;"></span> My javascript on click event to display spinning loader: <script type="text/javascript"> function showDiv() { document.getElementById('loadingdisplay').style.display = "block"; } </script> -
Affect total sum with start date and end date
My views: class CentreRevenue(ListAPIView): permission_classes = [IsAuthenticated, ] pagination_class = CustomPagination serializer_class = serializers.CentreRevenueSerializer def get_queryset(self): self.pagination_class.page_size = page_size id = self.request.query_params.get("id") start_date = self.request.query_params.get("start_date") end_date = self.request.query_params.get("end_date") data = center_models.Centers.objects.filter(center_type__in=['collection_center', 'direct_client'], id__isnull=False) if id: data = data.filter(id=id) # if start_date and end_date: # data = data.filter(created_at__date__range=[start_date, end_date]) return data #Serializer class CentreRevenueSerializer(serializers.BaseSerializer): class Meta: model = package_models.CollectionCenterLedger def to_representation(self, instance): tbc = booking_models.Booking.objects.filter(center=instance, center__isnull=False).values_list('id').count() amount = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, center=instance, ledger_type='debit' if instance.type == 'prepaid' else 'credit' ).values_list('amount', flat=True) ) remove_test_billing_client_billing = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, ledger_type='credit' if instance.type == 'prepaid' else 'debit', center=instance, ).values_list('amount', flat=True) ) add_test_billing = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, ledger_type='debit' if instance.type == 'prepaid' else 'credit',center=instance ).values_list('rcl_share', flat=True) ) remove_test_billing = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, ledger_type='credit' if instance.type == 'prepaid' else 'debit', center=instance ).values_list('rcl_share', flat=True) ) rcl_amount = add_test_billing - remove_test_billing amount = amount - remove_test_billing_client_billing return{ 'ccdc_name':instance.name, 'sales_person':instance.sales_manager.user.username if instance.sales_manager else None, 'centre_type':instance.center_type, 'total_booking_count':tbc, # 'total_revenue':sum([i for i in total_rev if i is not None]), 'total_revenue':amount, 'rcl_share':rcl_amount } Here i am calculating total_booking_count, total_revenue and rcl_share. I want to filter these data with start_date and end_date and accordingly these calculation will affect. Suppose if i selected date range 5 days then it will only show calculation of … -
HOW TO UPDATE DJANGO FORM WITH FILES AND TEXT INPUTS?
I have an update form in django and the code below is working particulary the instance: def edit_project(request, project_id): detail = projectDB.objects.get(pk=project_id) form = projectForm(request.POST or None, instance = detail) if form.is_valid(): form.save() return redirect ('/manage') return render(request, 'edit_project.html', {'detail': detail, 'form':form }) But when I inserted request.FILES as well to save the updated file from the form like this, def edit_project(request, project_id): detail = projectDB.objects.get(pk=project_id) form = projectForm(request.POST or None, request.FILES instance = detail) if form.is_valid(): form.save() return redirect ('/manage') return render(request, 'edit_project.html', {'detail': detail, 'form':form }) the instance seems not working anymore. Im new to django and I want to update a form that contains files and text inputs from users and I dont know how to save both at the same time. Hope you help me, thank you -
Github Actions CI/CD without docker on an -Django-Gunicorn-Nginx
I have a digital ocean server setup with Django-Gunicorn-Nginx. Everything is working as I want but sadly everytime I make a code change I have to manually login to my server pull my changes from github and restart gunicorn. Is it possible to setup a CI/CD workflow by just using Github-Actions? P.S - Docker is not an option right now. -
Why my django send_mail is not working with Occasion models?
I am working on project, in this project a user can make a group(occasion) where he saves the message, members(Many-to-many), occasional_date(date of the occasion) and when the occasional date appears the webapp should send the message by email to all members of the occasional group. But It is not sending emails. here is my occasions/models.py from django.db import models from django.dispatch import receiver from members.models import Member from django.contrib.auth import get_user_model import uuid import datetime from django.core.mail import send_mail class Occasion(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="occasions") description = models.TextField(max_length=500, null=True, blank=True) members = models.ManyToManyField(Member) occasional_date = models.DateField(help_text="Enter the date on what you want to send the notifications to members.", default="2022-03-01") message = models.TextField(max_length=500, default="hello") is_email_sent = models.BooleanField(default=False) def __str__(self): return self.name def send_email(self): if self.is_email_sent == False and self.occasional_date == datetime.date.today(): for member in self.members: receiver = [] receiver.append(member.email_address) send_mail("Smart Alert", self.message, "officialsmartalert@gmail.com", receiver, fail_silently=False,) self.is_email_sent = True self.save() return True And in a template I call this method to work. {% for occasion in user.occasions.all %} {% if ocassion.send_email %} <li>{{ ocassion.name }}</li> {% endif %} {% endfor %} Please tell me how it will work because I am tired of … -
How to escape out of django tags?
I am currently working on a small project where I am using HTMX with Django. {% render_field form.email class="form-control my-3" placeholder="Email" hx-post="{% url 'accounts:verify-email' %}" hx-trigger="keyup" hx-target="#email-verif" hx-swap="outerHTML" %} {{ form.email.errors|striptags }} However, the code breaks because it thinks the %} portion of the url snippet is close bracket of the whole line. Is there any solution for this? -
Unable to declare javascript variable with a django variable
I am using django and when I assign a django variable to a javascript variable I get the following error. Uncaught SyntaxError: Unexpected token '&' What Im doing is I passed a variable which is a list of strings to the template html through the view function Im calling here is the view function: def index(request): class_obj = AllClasses() return render(request, 'index.html', { 'classNames': class_obj.classList }) Then I declared a global JavaScript variable inside index.html like this: <script> var names = {{classNames}}; </script> This results in the following error that Uncaught SyntaxError: Unexpected token '&' Any idea on how to solve this ? -
How to make an api completely independent from the main Django Project?
I have a django project that is hosted internally, and this project feeds the database. I need an API that serves the data of that database to a public domain (that api does not do any DML only selects), but this API needs be hosted in a diferent machine and even if the project that is hosted internally explodes that api needs to keep working. I am using DRF for the api I did an api project that has its own apps, views, serializers and models(those models connect to the db existing table like this) and only have the fields that I need represented. Is this the right way to do this or am I missing something? The thing that I am worried is if one of the columns of a model changes name i will have to change the model in the api, but that is a very rare modification. -
Multiple add to cart buttons on the same page in django
i am trying to add multiple add to cart buttons of products on the same page. i had the code of one add to cart button for one produc in one page but now i am trying to do it for multiple products (a grid) def product(request, category_slug, product_slug): cart = Cart(request) product = get_object_or_404(Product, category__slug=category_slug, slug=product_slug) imagesstring = '{"thumbnail": "%s", "image": "%s", "id": "mainimage"},' % (product.get_thumbnail(), product.image.url) for image in product.images.all(): imagesstring += ('{"thumbnail": "%s", "image": "%s", "id": "%s"},' % (image.get_thumbnail(), image.image.url, image.id)) print(imagesstring) if request.method == 'POST': form = AddToCartForm(request.POST) if form.is_valid(): quantity = 1 #form.cleaned_data['quantity'] cart.add(product_id=product.id, quantity=quantity, update_quantity=False) messages.success(request, 'The product was added to the cart') return redirect('product', category_slug=category_slug, product_slug=product_slug) else: form = AddToCartForm() similar_products = list(product.category.products.exclude(id=product.id)) if len(similar_products) >= 4: similar_products = random.sample(similar_products, 4) context = { 'form': form, 'product': product, 'similar_products': similar_products, 'imagesstring': "[" + imagesstring.rstrip(',') + "]" } return render(request, 'product/product.html', context) here is the view function for one product page. -
Routing does not work in Django: page not found (GET)
I've tried multiple methods of writing views but I don't think it is a problem here. App is installed in settings.py It displays error every time. project structure: structure url.py in apps folder from django.urls import path from . import views urlpatterns = [ path('home_view/', views.home_view) ] apps.py in app folder from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' urls.py in store folder from django.contrib import admin from django.urls import path, include from app import views urlpatterns = [ path('app/home_view/', include('app.url')), path('admin/', admin.site.urls), ] error message: error