Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST permissions
Im trying to allow Company owners edit Medicine objects, how can i override permission below? my models class Company(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) class Medicine(models.Model): company = models.ForeignKey( Company, related_name='medicine', on_delete=models.CASCADE, ) default permissions from documentation class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user -
null and blank in django
i have project with account model with many field and i want a person can signup with phone and password and can create user instance but i want when user edit the profile the user should fill that field .i do not know how to use blank and null for that field like (national-code , city and ,,,) ? if for example i add nationl_code field as null=False and blank=False i must add it in my custom UserManager? can any one help me ? can any one help me ? -
Django MPTT hierarchy expand/collapse does not work
I'm trying to exapnd/collapse my comments hierarchy using the following code. Output just shows 0 level nodes as links, upon clicking on them nothing expands. Any suggestions? Bootstrap v.5.0 {% recursetree comments%} <a role="button" data-bs-toggle="collapse" data-bs-parent="#accordion" href="#collapse{{node.level}}" aria-expanded="false" aria-controls="collapsed"> {{ node.text}}</a> {% if not node.is_leaf_node %} <ul class="children"> <div id="collapse{{node.level}}" class="children panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> {{ children }} </div> </div> </ul> {% endif %} {% endrecursetree %} -
How to query Django ORM on models connected with latest record
Hi I have a Django Project with the following models class Organization(models.Model): name = models.CharField("Name", max_length=128, unique=True) description = models.CharField("Description", max_length=256) class Scholar(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) name = models.CharField("Name", max_length=128) title = models.CharField("Title", max_length=256) def get_latest_snapshot(self): return self.snapshotscholar_set.latest('date_crawled') class SnapshotScholar(models.Model): scholar = models.ForeignKey(Scholar, on_delete=models.CASCADE) date_crawled = models.DateTimeField("Date Crawled", auto_now_add=True, db_index=True) title = models.CharField("Title", max_length=256) class SnapshotScholarPublication(models.Model): snapshot_scholar = models.ForeignKey(SnapshotScholar, on_delete=models.CASCADE) title = models.ForeignKey("Title", max_length=256) citation_count = models.IntegerField() Now when I want to get a count of the number of scholars per organization I can do Organization.objects.annotate(num_scholars=Count('scholar')). But how do I get the number of publication per organization when I only want to count publications of the latest snapshot. That is, I want it sorted by SnapshotScholar.date_crawled, and I want all the publications on the latest SnapshotScholar in the database. Going by some of the questions on here I managed to create this SQL - SELECT COUNT(pub.id) as publications, org.id FROM (main_snapshotscholarpublication pub, main_snapshotscholar snap, main_scholar scholar, main_organization org) INNER JOIN ( SELECT MAX(main_snapshotscholar.date_crawled) as latest_date, main_snapshotscholar.scholar_id as 'id' FROM main_snapshotscholar GROUP BY main_snapshotscholar.scholar_id ) as latest_snap ON (latest_snap.id = snap.id) WHERE pub.snapshot_scholar_id = snap.id AND snap.scholar_id = scholar.id AND scholar.organization_id = org.id GROUP BY org.id The results I'm getting … -
Django: Is there a way to use "Extends" for a Div container that I can then add elements inside?
I'm making a website using Django. I created a <div> container class to keep the content of my webpages standardized: <div class="container"> <div class="content"> </div> </div> I need this div class because its styling interacts with the navbar element I created. I am looking for a way to use extends such that I can add elements inside the div container after I extend or include it in my new html page: <div class="container"> <div class="content"> <p> </p> </div> </div> Is there a way to do this with Django without repeating code every time I make a new html doc? -
CRUD in differents views at same template
I use same template with two differents views, each one applyes one filter to data. The problem is caused because this template have CRUD functionality. So, when its used I can't select where redirect will point for. I can do others views and url for each CRUD but i thinks thats not the best pratice of DRY. url.py for todolistapp urlpatterns = [ path('', views.todolist, name='todolist',), path('me', views.todolist_mine, name='todolist_mine'), path('delete/<task_id>', views.delete_task,name='delete_task'), path('edit/<task_id>', views.edit_task,name='edit_task'), path('complete/<task_id>', views.complete_task, name='complete_task'), path('incomplete/<task_id>', views.incomplete_task,name='incomplete_task'), ] part of views.py @login_required def todolist(request): if request.method == 'POST': form = TaskForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.manager = request.user instance.save() messages.success(request,("Tarefa adicionada")) return redirect('todolist') else: me_page = False form = TaskForm all_tasks = Tasks.objects.filter(manager=request.user) all_users = Tasks.objects.all() is_responsible = Tasks.objects.filter(responsible=request.user, done=False) n_is_responsible = is_responsible.count() return render(request,'todolist.html',{ 'form':form, 'all_tasks':all_tasks, 'all_users':all_users, 'is_responsible':is_responsible, 'n_is_responsible':n_is_responsible, 'me_page':me_page}) @login_required def todolist_mine(request): if request.method == 'POST': form = TaskForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.manager = request.user instance.save() messages.success(request,("Tarefa adicionada")) return redirect('todolist_mine') else: me_page = True form = TaskForm all_tasks = Tasks.objects.filter(responsible=request.user) all_users = Tasks.objects.all() is_responsible = Tasks.objects.filter(responsible=request.user, done=False) n_is_responsible = is_responsible.count() return render(request,'todolist.html',{ 'form':form, 'all_tasks':all_tasks, 'all_users':all_users, 'is_responsible':is_responsible, 'n_is_responsible':n_is_responsible, 'me_page':me_page}) HERE IS THE REDIRECT PROBLEM @login_required def edit_task(request,task_id): if request.method == 'POST': … -
Summarizing values for each row in a table dynamically generated from django context variables
So I have the following table in my template: <tbody> {% for user in users %} <tr> <td>{{ user.title }} </td> {% for fruit in fruits %} {{ sum|add:user|get_attr:fruit }} <td>{{ user|get_attr:fruit }} </td> {% endfor %} {% for vegetable in vegetables %} {{ sum|add:user|get_attr:vegetable }} <td>{{ user|get_attr:vegetable }} </td> {% endfor %} <td>{{ sum }}</td> {% endfor %} </tbody> "fruits" and "vegetables" are lists passed as context from the view. The following custom filter allows me to iterate through those lists extract integer values from the model "user". The table columns are generated the same way, so this filter has to be in the table: @register.filter def get_attr(obj, attr): return getattr(obj, attr) The variable "sum" is passed as context from the view with the value 0. I'm trying to make it summarize all the relevant row variables in the template, but it remains 0. As far as I can see there are three ways I could go about this: Solve this in the template (as I'm trying now) Generate the value in the view (although I have no idea how I would go about this) Add some JS to solve it (would prefer to avoid this). How should I … -
Class method to Django ORM Model class
In a Django project I've the following models: class Asset(Model): code = SlugField(max_length=DEFAULT_CODE_LENGTH, unique=True) name = CharField(max_length=DEFAULT_NAME_LENGTH) class Meta: abstract = True class District(Asset): # ... class-specific fields I would like to add some logic in order that when instancing an Asset subclass the code field is automatically filled. I thought that an elegant way to do it could be modifying the Asset class: class Asset(Model): @classmethod def generate_code(cls) -> str: return unique_code_generation_logic(model=cls, length=DEFAULT_CODE_LENGTH) code = SlugField(max_length=DEFAULT_CODE_LENGTH, unique=True, default=generate_code) name = CharField(max_length=DEFAULT_NAME_LENGTH) class Meta: abstract = True def unique_code_generation_logic(model: type, length: int) -> str: # generating a new code and verifying that is unique for the model class return code But Django does not allow to declare it because the class method can't be serialized: user@PC in repo: backend on feature/task-989_models [$x!?2⇣12] via v3.10.2 (.venv) took 3ms λ ./manage.py makemigrations kmap core Migrations for 'core': core/migrations/0001_initial.py - Create model District Traceback (most recent call last): File "/home/user/django_project/backend/./manage.py", line 22, in <module> main() File "/home/user/django_project/backend/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/user/django_project/backend/.venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/user/django_project/backend/.venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/django_project/backend/.venv/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/django_project/backend/.venv/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute output … -
how to use post_save and pre_save with one sender with django signals
can I use post_save and pre_save with one sender with Django signals? am doing this because there are 2 cases in my module, and both need different approaches.. here is my code : models.py class Team(models.Model): name = models.ForeignKey(TeamName,on_delete=models.PROTECT,related_name="team_team_name") home_strip = models.ForeignKey(TeamStrip,on_delete=models.PROTECT,related_name="team_team_home_strip") away_strip = models.ForeignKey(TeamStrip,on_delete=models.PROTECT,related_name="team_team_away_strip") logo = models.ForeignKey(TeamLogo, on_delete=models.PROTECT,related_name="team_team_logo") region = models.ForeignKey("locations.Region",on_delete=models.PROTECT,related_name="region_teams") cap = models.ForeignKey("players.PlayerProfile",on_delete=models.PROTECT,related_name="team_team_cap") players = models.ManyToManyField("players.PlayerProfile",null=True,blank=True) average_skill = models.PositiveIntegerField(default=0) def __str__(self) -> str: return str(self.name.name) + " - " + str(self.region.name_ar) + "," + str(self.region.name_en) signals.py @receiver(pre_save, sender=Team) def create_Team(sender, instance, **kwargs): if instance.players.all().count() == 0: print('normal save') cap_skills = instance.cap.average_skill instance.cap.is_cap = True instance.cap.save() instance.average_skill = cap_skills region_object = instance.region region_object.available_team_names.remove(instance.name) region_object.available_team_logos.remove(instance.logo) if region_object.available_team_names.count() == 0 or region_object.available_team_logos.count() == 0: region_object.can_create_team = False region_object.save() else: region_object.can_create_team = True region_object.save() @receiver(post_save, sender=Team) def udpate_team(sender, instance, **kwargs): if instance.players.all().count() != 0: print('m2m changed post_add') new_players_count = instance.players.all().count() + 1 print("players count:" + str(new_players_count)) new_players_total_skill = 0 print("new_players_total_skill count:" + str(new_players_total_skill)) for player in instance.players.all(): new_players_total_skill += player.average_skill new_players_total_skill += instance.cap.average_skill print("new_players_total_skill_after_loop count:" + str(new_players_total_skill)) new_team_average = round(new_players_total_skill / new_players_count) print("new_team_average count:" + str(new_team_average)) instance.average_skill = new_team_average instance.save() #had to use this line to make sure the instance is being saved as it is post_save .. but it causes the … -
DataError. Invalid input syntax for type inet
This is killing me.. I'm getting this DataError when trying to insert in to postgres db. DataError at /admin/docmanager/target/ invalid input syntax for type inet: "86.2.2.61:53886" LINE 1: ...}', '90b137f6-b2c5-41b5-a9cc-c7267e61f309'::uuid, '86.2.2.61... My app is deployed on Azure and I've tried two different different postgres instances and both return the same error when the app is deployed on Azure.. But.. when I deploy the app locally using the same postgres databases the queries run fine. Obviously this leads me to believe there is a configuration or a way Azure is passing the IP address as it's an inet issue.. but these are just my ignorant assumptions. here is the pastebin traceback any ideas or a kick in the right direction would be helpful -
Django : Get (models) __str__ foreignkey (text) value instead of its ID in ajax search result
I use JS for products search this way : models.py (summary) class Produit(models.Model): famille = models.ForeignKey(Famille, on_delete=SET_NULL, null=True) sku = models.CharField(max_length=100, unique=True) nom = models.CharField(max_length=250) fournisseur = models.ForeignKey( Supplier, on_delete=models.SET_NULL, default=12, null=True) qty = models.IntegerField() mini = models.IntegerField() [...] And eg. for Famille, I've set str to : class Famille(models.Model): nom = models.CharField(max_length=50) [...] def __str__(self): return self.nom In my template I have a search field that is listened by my JS code product_search.js const searchField = document.querySelector("#searchField"); const tableBody = document.querySelector('.table-body'); const appTable = document.querySelector('.app-table'); const tableOutput = document.querySelector('.table-output'); tableOutput.style.display = 'none' searchField.addEventListener('keyup', (e) => { const searchValue = e.target.value; if (searchValue.trim().length > 2) { tableBody.innerHTML = ''; fetch("search-product2", { body: JSON.stringify({ searchText: searchValue }), method: "POST", }) .then((res) => res.json()) .then((data) => { tableOutput.style.display = 'block' appTable.style.display = "none"; if (data.length === 0) { tableOutput.innerHTML = '<h3>Aucun résultat.</h3>'; } else { console.log("data", data); data.forEach((item) => { tableBody.innerHTML += ` <tr> <th><a href="{% url 'product-update' ${item.id} %}">${item.sku}</a></th> <td>${item.etat_id}</td> <td>${item.nom}</td> <td>${item.famille}</td> <td>${item.mageid}</td> <td>${item.adresse}</td> <td>${item.fournisseur}</td> [...] <td>${item.cau_cli}</td> <td>${item.maxsst2}</td> </tr> `; }); } }); } else { console.log('longueur de terme de recherche insuffisante'); tableOutput.style.display = "none"; appTable.style.display = "block"; } }); The JS code calls this view.py def search_product2(request): if request.method == … -
How to send variables from X-DATA to the server. Alpine JS & HTMX & Django?
I have got the next snippet. There are a few select blocks. What I would like to do is to collect both variables and send to the Django server. But the request.GET is empty. What is wrong? <div class="flex" x-data="{ foo: '', bar: ''}"> <div class="flex justify-between"> <div class="mt-1"> <select x-model="foo" name="foo" id="foo" class="w-64 h-14 text-sm border-gray-300 focus:bg-transparent"> <option value="">Type of FOO</option> <option value="FOO_1">FOO_1</option> <option value="FOO_2">FOO_2</option> <option value="FOO_1">FOO_3</option> </select> </div> <div class="mt-1"> <select name="bar" x-model="bar" id="bar" class="w-64 h-14 text-sm border-gray-300 focus:bg-transparent"> <option value="">BAR Types</option> <option value="BAR_1">BAR_1</option> <option value="BAR_2">BAR_2</option> <option value="BAR_3">BAR_3</option> </select> </div> <input type="text" name="foo" x-model="foo" hidden /> <input type="text" name="bar" x-model="bar" hidden /> <button hx-get="{% url 'server:parse-values' %}" hx-target="#element" hx-swap="innerHTML" hx-include="[name='foo', name='bar']"> <span class="cursor-pointer px-3 py-3 border-2">Parse details</span> </button> </div> </div> But when I click on the button the Django backend does not receive foo and bar parameters. Any thoughts? -
How to fix "InternalError: variable not found in subplan target list"
I have a legacy Django project (django-1.1.29) and some tests in pytest (pytest-4.3.0), all running inside Docker. The database is PostgreSQL 10 and is a docker-compose service on which the application depends on. The python version is 2.7.18. Lately the tests started to fail with a strange error: InternalError: variable not found in subplan target list. The error occurs only when I count the number of objects of a certain model, e.g. Problem.objects.count(). The instruction is turned into the following query (0.000) SELECT COUNT(*) AS "__count" FROM "problems_problem"; args=() by Django. The whole log is here: self = <integration_tests.project_name.subjects.test_views.test_theme_problem_view_set.TestThemeProblemViewSet object at 0x7f01faccbe50> jclient = <project_name.common.test_utils.json_client.JSONClient object at 0x7f01fadb8ed0> def test_all_is_ok(self, jclient, subject_model, content_manager): url, data = self._main_prepare(jclient, subject_model, content_manager) response = jclient.post_json(url, data[0]) assert response.status_code == 201 > assert Problem.objects.count() == 1 integration_tests/project_name/subjects/test_views/test_theme_problem_view_set.py:86: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/local/lib/python2.7/dist-packages/django/db/models/manager.py:85: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) /usr/local/lib/python2.7/dist-packages/django/db/models/query.py:364: in count return self.query.get_count(using=self.db) /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:499: in get_count number = obj.get_aggregation(using, ['__count'])['__count'] /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:480: in get_aggregation result = compiler.execute_sql(SINGLE) _ _ … -
Django models many to many relationship problem
I'm writing my very first django app, kind of cookery book. I have a problem with showing grammage of ingredient in recipe details view (Ingredient and Recipe are in many-to-many relationship through IngredientRecipe model). Here are my models: class Ingredient(models.Model): name = models.CharField(max_length=50, unique=True) glycemic_index = models.IntegerField(choices=GLYCEMIC_INDEX) class Recipe(models.Model): title = models.CharField(max_length=50) cooking_time = models.IntegerField() difficulty_level = models.IntegerField(choices=DIFFICULTY_LEVELS, default=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) cuisine = models.ForeignKey('Cuisine', on_delete=models.CASCADE, null=True) ingredient = models.ManyToManyField(Ingredient, through='IngredientRecipe') class IngredientRecipe(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) **grammage = models.IntegerField(help_text='in grams')** Here is the view: class RecipeDetailsView(View): def get(self, request, id): recipe = Recipe.objects.get(id=id) ingredients = recipe.ingredient.all() return render(request, 'recipe_details.html', {'recipe': recipe, 'ingredients': ingredients}) The thing is that currently my view is showing recipe ingredients without their grammage (grammage field in many to many model). I don't know how to put in in my view's code. Tried few different ways but it doesn't work. Any ideas how to solve it very aprecciated. And sorry for any mistakes, this is my 1st post in here :) -
How to display nested objects in django template?
Here is my objects: (the field uses ArrayField of postgress to store) {{'intake': '2022-01-01', 'deadline': '2022-02-28'},{'intake': '2022-06-01', 'deadline': '2022-11-30'}} Am trying to display intakes of all, but am getting output like i,n,t,a,k,e,:,2,0,2,2,-,............ Please help to resolve this ? This is my code: {% for value in data.intakes %} <div> {{value.intake }} </div> // this gives blank output {% endfor %} {% for value in data.intakes %} <div> {{value.0 }} </div> // this gives output as {{ {% endfor %} -
How can i check if new object is added in models database in django?
Info: How can i check if PlayingEleven get new object in database? Basically I want to check for if PlayingEleven get new object then i want to add this new object in BattingInnings record and if that object is already exists in PlayingEleven than save(commit=False). i don't understand how can i compare the Queries of both models? Problem: My code is working but for one time! if new object added in PlayingEleven then it is not working... views.py def submit_playing_eleven(request, match_id): match = Match.objects.get(pk=match_id) players = PlayingEleven.objects.get(match=match) team1_players = players.team_1_players.all() team1 = BattingInnings.objects.filter(match=match).filter(player__id__in=team1_players) try: if not team1.exists(): for player1 in team1_players: bi1 = BattingInnings() bi1.player = player1 bi1.team = match.team_1 bi1.tournament = match.series bi1.match = match bi1.save() except IntegrityError as e: print(e) return redirect('match-detail', match_id) -
Django image cannot load correctly even though I added static root
settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('food/',include('foodApp.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) HTML Template <a class="navbar-brand" href=""> <img src="{% static 'delivery.png' %}"> </a> Folder Directory food_delivery (Main Project) -- food_delivery -- foodApp -- static (folder that puts images) -- templates -- manage.py For loading images in Django, the HTML template could not correctly recognize the image that I am trying to indicate. I have a confusion where should I put the static folder in my project directory and I am not sure anything I am missing in the settings.py file in order to recognize the images inside the static folder directory. Can anyone can help me find out the solution in order to load images that are put under the static folder directory? -
How should I handle datetimes with Django and PosgeSQL?
I have a Django app which needs to support different time zones. I'm saving events to my database which have timestamps and based on those timestamps I want to send notifications. Because the user can move into different time zone, I want to store timestamps as UTC time and convert them to user current time zone later. If I'm correct, PostgreSQL converts datetimes to UTC automatically? At the moment I get an error RuntimeWarning: DateTimeField event.timestamp received a naive datetime (2022-02-15 15:00:00) while time zone support is active.. I used to use Django's make_aware when saving the timestamp and didn't get this warning then. The questions I'd like to get an answer are: Should I save aware datetimes to the database if I want to support multiple time zones? What should I use in variables TIME_ZONE and USE_TZ in settings.py? UTC and True? I store the time zone info to the database, what is the correct method to activate it when I want to get the local time for the user? django.utils.timezone.activate + get_current_timezone or is there some function like astimezone(string_from_db)? -
Django Row_Number usage with group_by ORM
I have a database(screenshot attached) and I want to retrieve the average of readings as per the aggregation size provided. Suppose my aggregation size is 2. enter image description here So, as per the image, there are four readings for a specific customer_id and device_id. I thus have to group two readings into one average reading row and again, the other two readings into another row. def get_aggregation_filter(self, queryset, name, value): subq = queryset.annotate(row_number=Window( expression=RowNumber() # partition_by=2, # order_by=F('time').asc() )) outsubq = subq.annotate(group_id=((F('row_number') - 1)/ 2) + 1) queryset = outsubq.annotate(avg=Avg('reading')) return queryset I am not able to apply group by on the group_id that I created using annotate. Any help is appreciated. -
unsupported operand type(s) for *: 'decimal.Decimal' and 'float'
Here i am using Django 3.0 and python 3.7 Here is my views.py def update_stock_arriving_item(request, order_item_id): ... ... def _convert(from_currency, to_currency, price): custom_rate_obj = client.custom_rates.filter(currency=to_currency).first() if custom_rate_obj is None or custom_rate_obj.exchange_rate in (0, None): custom_rate_obj = ExchangeRates.objects.latest('created') return custom_rate_obj.convert(from_currency, to_currency, price) ... ... if client.horticulture and val: purchase_price = _convert(obj.currency, 'GBP', float(item_price)) if obj.form_bought_in == 'CT': val = 2.5 elif obj.form_bought_in == 'BR' or obj.form_bought_in == 'RB': val = 3.5 else: val = 0.0 trade_price = math.ceil(_convert(obj.currency, client.currency, float(item_price)) * val) retail_price = trade_price * 1.35 PricingModule.objects.filter( client=client, item=obj).update( purchase_price=purchase_price, trade_price=trade_price, retail_price=retail_price ) How can i solve my issue "unsupported operand type(s) for *: 'decimal.Decimal' and 'float' " -
Best method for Django ORM query
I am new to programming and have been recently messing around with python and django. I am trying to automate reports for my finance department and have come up with a database design but stuck with designing queries to fetch data: Here is a flow of the database: Database flow: I need to fetch report lines for each report and the fetch amounts from TB table for each line. There could be amounts for multiple periods Here is the tricky part. The amount for each period represent sum of different values and are grouped together in a grouping table. Below are my queries: Is this design practical or there could be a better way Do I need to query Report lines, then grouping and then grouping items and ultimately amounts separately or can this be done via a single query? Is relational database suitable for such database or should i look for something else like GraphDB? Really appreciate the support from this community. It has helped me a lot with learning django. -
How to delete the reference object that will not delete the referred object in Django?
Here I've two models. one is Contact and another one is Sent_replies. If client wants to contact with admin his information will be stored in Contact model. So here I want that if admin replies to that client, that specific information will be deleted from Contact model without deleting the record which is in Sent_replies. How can I do that. models.py class Contact(models.Model): message_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) comment = models.TextField(max_length=100) subject = models.TextField(max_length=100) reply = models.TextField(max_length=500); date = models.DateField() def __str__(self): return self.name class Sent_replies(models.Model): message = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True) subject = models.TextField(max_length=100) reply = models.TextField(max_length=500) def __str__(self): return self.message.name -
populate price section by selecting product in django formset
I have a Django formset with 6 input field. Whenever a user select a product for every row it will auto populate 3 fields named dp_price, tp_price and mrp. I have tried some but failed to do it by myself. my formset looks like this and my tried js file is add_purchase.js var send_data = {} for(var i=0; i<10; i++){ $(document).ready(function (prefix) { $('#id_form-' +prefix+ '-product').on('change', function () { console.log("On Product selected") let id = $(this).children('option:selected').val(); console.log(id); $.ajax({ url: 'product-info', data: { 'pk': id }, dataType: 'json', success: function (data) { console.log(data); $("#id_form-"+prefix+"-dp_price").val(data.dp_price); $("#id_form-"+prefix+"-tp_price").val(data.tp_price); $("#id_form-"+prefix+"-mrp").val(data.mrp_price); } }); })(i); }); } forms.py PurchaseChildFormset = modelformset_factory( PurchaseChild, form=PurchaseChildFormCreateForm, extra=1, widgets={ 'product': forms.Select(attrs={'class': 'form-control', }), 'dp_price': forms.NumberInput(attrs={'class': 'form-control', }), 'tp_price': forms.NumberInput(attrs={'class': 'form-control', }), 'mrp': forms.NumberInput(attrs={'class': 'form-control', }), 'qty': forms.NumberInput(attrs={'class': 'form-control'}), 'line_total': forms.NumberInput(attrs={'class': 'form-control'}), }, ) -
How to add extra field other than user in django group
I have one application where users(admin) can create groups and add users. But the admin wants to share some credits with group members. For example, Admin has purchased 100 credits. Out of 100 credits, he can give any number of credits to any user who belongs to that group. -
Can't encode cyrillic characters xhmt2pdf in django
# libraries from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from django.utils.encoding import smart_str # defining the function to convert an HTML file to a PDF file def html_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None In HTML I have some Russian words. When I tried to encode these characters, in my pdf, I have bunch of unclear charactets appeared. I have tried to change coding format to "UTF-8", "UTF-16" but it did not help.