Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save the changes into user log of two different field separately
I am using Django where I'm trying to show to users any changes in the table made by the user itselfs. Something like a user log. So any data changes inside the system will be displayed in User Log. The current issue is so far I can manage to capture the changes for only one field in the table. But it is needed to get any changes in several fields. def updatePart(request, pk): action = 'update' part = Part.objects.get(id=pk) previous_standard = part.standardpack previous_pack = part.stylepack form = PartForm(instance=part) if request.method == 'POST': form = PartForm(request.POST, instance=part) if form.is_valid(): pack= form.save() create_log(request, pack, object_repr=pack.partname, change_message=f"stylepack {previous_pack} to {pack.stylepack}") create_log(request, pack, object_repr=pack.partname, change_message=f"standardpack {previous_standard} to {pack.standardpack}") return redirect('part-list') context = {'action': action, 'form': form} return render(request, 'store/update_part.html', context) Here is the part table, there are nine fields here that I'd like to save the changes in userlog. Base on the current situation, if only "stylepack" field data changes, the user log show this at the same time Changed “Outer Opening Handle Assy Door RH RL (C/BROWN)” — Standardpack 17 To 17 Changed “Outer Opening Handle Assy Door RH RL (C/BROWN)” — Stylepack Rack2 To Rack How can I solve this issue that … -
How can I present the option to create a new related model instance alongside existing options presented in a Django form from a ManyToMany field?
I am building an auction website a la eBay, and want to, when adding a new listing, be able to associate 0 or more categories with that listing. Specifically I would like a Categories CheckboxSelectMultiple (or similar?) that: Lists all existing categories as options Presents an option to create a new category which, when selected, presents a CharField, the value of which will be saved as the title of a new category, and that category and the new listing associated with each other. I have the following m2m relationship set up in models.py: class Category(models.Model): name = models.CharField(max_length=64) class Listing(models.Model): categories = models.ManyToManyField(Category, blank=True) ... and, on GET request, am passing the following ModelForm from forms.py to my new_listing.html template: class ListingForm(ModelForm): class Meta: model = Listing widgets = {'categories': forms.CheckboxSelectMultiple} fields = ['title', 'categories','starting_price', 'image_url', 'description'] I am having trouble figuring out how to do this, any help is much appreciated! -
Creating multiple url_paths for a Django actions-based view
I am using DRF and I have this viewset action view: @action(methods=['get'], detail=False, url_path=r'top-products/(?P<tag>\w*)/(?P<query>\w*)') def top_products(self, request, tag='', query=''): print(f'tag \t {tag}, query \t {query}') filtered = Product.objects.all() \ .annotate(items_count=Count('products_users')) \ .order_by('-items_count') if tag: filtered.filter(tags__name=tag) if query: filtered.filter(name__contains=[query.lower()]) topProducts = filtered paginator = StandardResultsSetPagination() result_page = paginator.paginate_queryset(topProducts, request) data = ProductSerializer(result_page, many=True).data return paginator.get_paginated_response(data) It is filtering the top products based on a query and a tag if they exist. Now as I want to make the function generic that works for three cases: - tag and query values exist - one of them exists - none exist After a bit of search I found that I needed to create one URL pattern for each case, but how can we do multiple url paths for an action view in Django? -
django did replace the existing name with new name because of the same name not other field. help appricated
I have an inquiry form and when I try to give data as below. ram, 20, surket, usa ram, 22, diren, usa unable to get stored in database 1 might get replaced. help appreciated tried numerous research but failed. I want to store both values in the database. would you let me know what to use? -
Can I access an elements index within a dictionary value?
I am passing a dictionary with one Key, Value pair where the value is a list of images. Is there any way to only loop through the first 4 elements within the values list? Here is my views.py file: def portfolio_couples(request): img_list = os.listdir("/Users/andershanson/Documents/Django/kh_photo/static/my_app/images/portfolio") context = {"images": img_list} return render(request, 'my_app/couples.html', context) Here is my HTML template: {% if images %} {% for image in images %} <img src="/static/my_app/images/portfolio/{{ image }}" class="container-fluid px-0 m-0" alt="portfolio-pic"> {% endfor %} {% endif %} This currently works looping through images, but is there any way to index the the first 4 elements in the dictionary value?? Thanks! -
how to insert a python variable inside a hyperlink in html using Django?
In this html block: {% block body %} <h1>All Pages</h1> <ul> {% for x in entries %} {% comment %} {% wik = 'mask/' + x + '.md' %} {% endcomment %} <li><a href = 'mask/'{{x}} </a>{{ x }}</li> {% endfor %} </ul> {% endblock %} I am trying to insert a string in x that will go to end of the hypertext. mask/cat, where "cat" is x [just as an example]. When I do this, the entry does not seem to be added to the hyperlink when I click it. The other way I thought is to create a python variable wik with the correct page hyperlink, but then I get an issue in Django Invalid block tag on line 12: 'wik', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Any help appreciated thanks -
update object if exists and create if it not exists django
i'm trying to create new object if not exists and update some fields if it exists , i've seen several answers but still its unclear , and i couldnt implement it well this is my models.py class Information(models.Model): name = models.CharField(max_length=50,unique=True) def __str__(self): return self.name class Item(models.Model): item = models.ForeignKey(Information,on_delete=models.CASCADE) quantity = models.IntegerField() quantity_storage = models.IntegerField(blank=True) buying_price = models.DecimalField(max_digits=30,decimal_places=3) def __str__(self): return self.item.name def save(self,*args,**kwargs): if self.item: Item.objects.filter(item__name=self.item).update( quantity=F('quantity') + self.quantity else: super(Item,self).save(*args,**kwargs) i have to update quantity field if the object already exists for example i've entered item :cableXYZ , quantity : 10 then i enter cableXYZ again with quantity : 20 it should update the quantity field to 30this works fine , but when i try to enter a new object which doesnt exists , it wont save the object ! is there something i've missed to add to save save() method ?! or isnt there a better approach to achieve it please ?! i very appreciate your helps -
How can I insert the try except block in this django-import-export view?
I can't get it right on how to appropriately add a try except block in this django-import-export view. My aim is to catch and display the particular errors that might be experienced during import. I believe a try except block can help but I don't know how to implement it in this view. class upload(LoginRequiredMixin,View): context = {} def post(self, request): form = UploadForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportResource() result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,result.invalid_rows) self.context['result'] = result return redirect('/') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Successfully.') else: self.context['form'] = UploadForm() return render(request, 'home.html', self.context) -
docker-compose run app python manage.py migrate results in psycopg2: database "app" does not exist
I have a Django app with Docker,I added postgres image and made all settings to create postgres db, but when I run "docker-compose up" which contains command: sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" it fails when it comes to migrate docker-compose.yml: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTRGES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword Dockerfile: FROM python:3.7-alpine MAINTAINER kubousky ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } The first part of command: **python manage.py wait_for_db** && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 is OK because of the message "Database available!!!". docker-compose run app python manage.py migrate … -
"NameError: name '_mysql' is not defined" error happening on Django only when running as ./manage.py
I'm working on a django project on MacOS 11.3 Intel. Problem is when I run "./manage.py runserver" I get error "NameError: name '_mysql' is not defined", however when running "python manage.py runserver" project starts whitout a problem. In trying to use vscode debugger I realized it jumpstarts the project with "./manage.py runserver" so I get the error and can't debug. I use Poetry as my package manager and have already added to my .zshrc file, the following commands: "export PATH=${PATH}:/usr/local/mysql/bin/" & "export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/" -
Django and PosgresSQL adds a timezone offset on every save
My django and postgresql adds the timezone offset to a datetime field on every save. it is working propperly on sqlite. >>> from picture.models import * >>> p=Picture.objects.get(id=561) >>> p.date_taken datetime.datetime(2020, 8, 12, 19, 23, tzinfo=<UTC>) >>> p.save() >>> p=Picture.objects.get(id=561) >>> p.date_taken datetime.datetime(2020, 8, 12, 21, 23, tzinfo=<UTC>) I tried all sorts of configurations combinations in django settings: USE_TZ = True TIME_ZONE = 'UTC' postgresql.conf timezone = 'Etc/UTC' psql ALTER ROLE albumusertest SET timezone TO 'UTC'; some snippets: from postgres date_taken | timestamp with time zone | | not null | django date_taken = models.DateTimeField() postgres version psql (PostgreSQL) 11.12 (Debian 11.12-0+deb10u1) django version 3.2 I am really in a loss. Can anyone help me? -
How can I use Django template syntax in CSS selectors?
I'm pretty new to Django, and I've been wondering about this for a while. Is there any way to put template syntax into a CSS selector, like this: {% for i in list %} <div id='div{{ forloop.counter }}'>test{{ forloop.counter }}</div> <style> #div{{ forloop.counter }} { color: blue; } </style> {% endfor %} And have it produce this code: <div id='div1'>test1</div> <style> #div1 { color: blue; } </style> <div id='div2'>test2</div> <style> #div2 { color: blue; } </style> <div id='div3'>test3</div> <style> #div3 { color: blue; } </style> I tried this, but it just flat out refuses to work. Is there a way to even achieve this, and if so, how? -
i have a field in the database "tags", i can put like the following: php, laravel, html, css. I need to split the tags variable into an array
i have this model : class Projects(models.Model): tags = models.CharField(null=True, max_length=255) title = models.CharField(max_length=255) this is the view: def homepage(request): projects = Projects.objects.filter(status='1').order_by('-listorder') return render(request, 'homepage.html', {'projects': projects}) this is where i want to display it in <div class="box-cat-title">{{ project.title}}</div> <div class="box-cat-content">{{ project.tags }}</div> i need something like that: {% for project in projects %} <div class="box-cat-title">{{ project.title}}</div> {% for tag in tags %} <div class="box-cat-content">{{ tags.tag }}</div> {% endfor %} {% for project in projects %} -
Django - Import CSV to model, handling relationships to other models
Let's suppose we have Author and Book models: class Author(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) def __str__(self): return self.last_name class Book(models.Model): title = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title And we try to do multiple inserts using CSV files: (author.csv) FirstNameA, LastNameA FirstNameB, LastNameB (book.csv) FirstTitle, LastNameA AnotherTitle, LastNameA OneMoreTitle, LastNameB I try to build a class-based view which imports a CSV in a model. The view: is given the name of the model as an argument fetches the model and its fields and uses get_or_create method in a loop for each row of the CSV While this approach works class ImportCSV(View): ... def post(self, request, model_name): model = apps.get_model('app', model_name) fields = list(modelform_factory(model=model, fields='__all__').base_fields.keys()) file = request.FILES['csv_file'] decoded_file = file.read().decode('utf-8').splitlines() reader = csv.reader(decoded_file) for row in reader: dict = {} for i, field in enumerate(fields): dict[field] = row[i] _, created = model.objects.get_or_create(**dict) While it works for Author model, it does not work for Book model, due to ForeignKey field. It expects an id (number), not the value that __str__ returns for this record. It is totally logical. The question is, how can I handle such an import? What I would like to tell Django to … -
Django template inheritance does not work correctly
basically, I have a base Html and want to extend on it using every page specific elements but it does not place the elements in the place I want them to be in this is the base template : <!doctype html> <html lang="en"> <head> {% load static %} <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/styles/default.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <mdaseta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="flex"> <div class=" fixed h-screen bg-yellow-400 " id="side_nav" style="width:25% !important"> <a class="navbar-brand max-h-20 text-white p-10" href="/"> FUN CODING </a> <div class="flex flex-col h-full "> <hr class="mx-3"> </hr> {% if btn == "home"%} <button id="Home" class="transition duration-500 text-base font-medium p-3 bg-white text-black w-full side_btn">Home</button> {% else %} <button id="Home" class="transition duration-500 text-white text-base font-medium p-3 hover:bg-white hover:text-black bg-yellow-400 w-full side_btn">Home</button> {%endif%} {%if btn == "blog"%} <button id="Blog" class="transition duration-500 text-base font-medium p-3 bg-white text-black w-full side_btn">Explore Blog</button> {% else %} <button id="Blog" class="transition duration-500 text-white text-base font-medium p-3 hover:bg-white hover:text-black bg-yellow-400 w-full side_btn">Explore Blog</button> {%endif%} {% if btn == "store"%} <button id="Store" class="transition duration-500 text-base font-medium p-3 bg-white text-black w-full side_btn">Store</button> {% else %} <button id="Store" class="transition duration-500 text-white text-base font-medium p-3 hover:bg-white hover:text-black bg-yellow-400 w-full side_btn">Store</button> {%endif%} <button id="Contact" … -
Uncaught DOMException: Blocked a frame with origin "http://localhost:8000" from accessing a cross-origin frame
I am currently building a website with Django and Javascript. I am working on the ajax calls that would the data needed for populate my homepage. However, I keep getting this cross-origin error. I have tried setting the document domain, enabling CROS headers and passing CSRF tockens. All attempts have been unsuccessful. Please take a look at my javascript code above. if (window.scrollY > news_elementTarget.offsetTop) { if (!news_fetched) { $.ajax({ url: '/ajax/home', type: 'get', data: { button_test: $(this).text(), section: 'news', CSRF: csrftoken, }, success: function (response) { console.log('success') create_section_1(response.id, response.sections) news_fetched = true } }) } } I'm trying to make an ajax call to the backend when the window scrolls to a certain div. The get request is never even sent to the backend. I really confused because I thought my domains are the same which wouldn't cause a Cross-origin error. -
Django Rating for both side
I am writing an application for service based. When a user purchase a service, then the seller can leave a rate to the order for buyer and also the buyer can leave a rate to the order for seller. Like think about fiverr , upwork, freelanecr guru, when you sell a service or buy a service, you can leave review as buyer or as a seller which you are!! My logic is same, i am not getting should i add to models or should i handle with same models. Here you go for my current models class Ratings(models.Model): order = models.OneToOneField( Order, on_delete=models.CASCADE, related_name="ratings" ) seller_comment = models.TextField(_("Rating Body")) seller_value = models.IntegerField() buyer_comment = models.TextField(_("Rating Body")) buyer_value = models.IntegerField() seller = models.ForeignKey( User, on_delete=models.CASCADE, related_name="+", ) buyer = models.ForeignKey( User, on_delete=models.CASCADE, related_name="+", ) You know above models solving both buyer and seller case but i found this is not best practice. in other side, also i am thinking this way. class BuyerRatings(models.Model): order = models.OneToOneField( Order, on_delete=models.CASCADE, related_name="ratings" ) comment = models.TextField(_("Rating Body")) value = models.IntegerField() author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="rating_as_buyer", ) class SellerRatings(models.Model): order = models.OneToOneField( Order, on_delete=models.CASCADE, related_name="ratings" ) comment = models.TextField(_("Rating Body")) value = models.IntegerField() author … -
django Error Help please - IntegrityError: NOT NULL constraint failed: new__PFC_userdata.user_id
Here's the UserData model class UserData(models.Model): fruits = models.CharField(max_length=100) nfruits = models.CharField(max_length=100) vege = models.CharField(max_length=100) nvege = models.CharField(max_length=100) o_factor = models.IntegerField(default=None, blank=True, null=True) g_factor = models.CharField(max_length=2, default=None, blank=True, null=True) c_factor = models.CharField(max_length=2) Here's the View I'm working with def grains(request): if request.method == 'POST': form = GrainsForm(request.POST) if form.is_valid(): form.save() g_factor = form.cleaned_data.get('g_factor') messages.success(request, f'g_factor: {g_factor}') return redirect('PFC-clothes') else: form = GrainsForm() return render(request, 'PFC/grains.html', {'form': form}) The form: class GrainsForm(forms.ModelForm): g_factor = forms.CharField(label="d for Daily, w for Weekly, m for Monthly, or n for None", max_length=1) class Meta: model = UserData fields = ['g_factor'] The program is running okay but I get this error when I attempt to migrate (I have 6 unapplied migrations). Any clues where I'm going wrong? Thanks -
Django API challenge using Django and Django Rest Framework
guys! So, I have the following challenge and I have a question about it. Should I use the name of the actions for the urls? Ex: create_tyre/:card_id or create_tyre and pass the car_id in the request or just use car/:car_id/create_tyre? How should I write the algorithm in the form of UnitTest? What to do Create a Rest API that controls a car maintenance status, and the trips it performs. Note that, each litre of gas can run 8 KM and every 3 KM the tyres degrades by 1%. Objects: Tyre -- Should have its degradation status in % Car -- Should have 4 tyres -- Should have its total gas capacity in liter -- Should have its current gas count in % Actions: Trip -- Input: car, distance (in KM) -- Output: Complete car status on trip end Refuel -- Input: car, gas quantity (in Litre) -- Output: Final car gas count in % Maintenance -- Input: car, part to replace -- Output: Complete car status CreateCar -- Input: None -- Output: Complete car status GetCarStatus -- Input: car -- Output: Complete car status CreateTyre -- Input: car -- Output: The created tyre Restrictions: The car should NOT have more … -
ValueError: Related model cannot be resolved
I'm trying to migrate my defined models in Django. When I run migrations on my app with manage.py makemigrations SkyrimApp everything runs correctly, but I get an error when trying to apply said migrations on the project with manage.py migrate. ValueError: Related model 'SkyrimApp.participante' cannot be resolved It appears SkyrimApp.participante is undefined when a certain migration is going to be made. Is there something wrong about the order of my models in models.py?? models.py: from django.db.models import CASCADE class Personaje(models.Model): idP = models.UUIDField(primary_key=True) #tiene restricción de unicidad nombreP = models.CharField(max_length=200) razaP = models.CharField(max_length=200) puntosSaludP = models.IntegerField() class Meta: ordering = ["nombreP"] def __str__(self): return self.nombreP class Hechizo(models.Model): nombreH = models.CharField(primary_key=True, max_length=200) #tiene restricción de unicidad puntosDH = models.IntegerField() class Meta: ordering = ["nombreH"] def __str__(self): return self.nombreH class Batalla(models.Model): idBat = models.UUIDField(primary_key=True) #tiene restricción de unicidad lugar = models.CharField(max_length=200) sobreviviente = models.CharField(max_length=200) fecha = models.DateTimeField() class Meta: ordering = ["fecha"] def __str__(self): return f'{self.lugar} - {str(self.fecha)}' def duration(self): return self.evento_set.count() class TipoDD(models.Model): nombreD = models.CharField(primary_key=True, max_length=200) #tiene restricción de unicidad class Meta: ordering = ["nombreD"] def __str__(self): return self.nombreD class Participante(models.Model): idPar = models.UUIDField(primary_key=True) #tiene restricción de unicidad deb = models.ForeignKey(TipoDD, CASCADE, related_name="%(class)s_deb") #daño al que es débil inf = … -
Django admin filter by foreign model's property retrieved by raw sql
How do I filter using a property. I know this is a duplicate, but existing answers that I think would work is not doing it for me. I have these models for my models.py: class Profile(models.Model): name = models.CharField(max_length=30, blank=True, null=True) country = models.CharField(max_length=30, blank=True, null=True) class Investment(models.Model): ... deal_type = models.CharField(max_length=30, choices=deal_type_choices) @property def investor_country(self): with connection.cursor() as cursor: # Data retrieval operation - no commit required cursor.execute('SELECT crowdfunding_profile.country FROM crowdfunding_profile WHERE crowdfunding_profile.associated_entity_id = %s ORDER BY crowdfunding_profile.associated_entity_id DESC LIMIT 1', (int(self.profile.id),)) row = cursor.fetchone() if not row is None: return row[0] return self.profile.country And this is my InvestmentAdmin on my admin.py: class InvestmentAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ('deal_type', 'investor_country') list_filter = ('deal_type',) It's working fine but I can't find a way to add the investor country into the list_filter. Something like this: list_filter = ('deal_type', 'investor_country') I tried doing something like this or this, because it's the most similar problem to what I have: list_filter = ('deal_type', 'profile__investor_country') but I'm receiving an error: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. -
Django - Recommendations for Django Tagging library packages
So I'm just about to begin implementing a "tags" feature in to my app where my users can create posts representing certain "tags" similar to the StackOverflow tags feature. I've just come across Tagulous but I wanted to first know if anyone may recommend any other tagging libraries? Ideally, I'm wanting to use a tags library where I can manage singular and nested tree type tags from my Django Admin. Any suggestions would be welcomed! -
Total price of items for each Order line and global with Django
I'm trying for a long time but no way to find a solution ... So I ask here hoping someone could help me ;) Here is my MODELS (models.py into /order) : class Client(models.Model): [...] class Commande(models.Model): objects = models.Manager() date = models.DateTimeField(auto_now=True) client = models.ForeignKey(Client, related_name='clients', on_delete=models.CASCADE) remise = models.DecimalField(max_digits=5, decimal_places=2, default=0) statut = models.CharField(max_length=200, db_index=True, null=False, blank=False, default='En cours') class Cartdb(models.Model): objects = models.Manager() produit = models.ForeignKey(Produit, related_name='produit', on_delete=models.CASCADE) qte = models.IntegerField(default=1) prix = models.DecimalField(max_digits=10, decimal_places=2, default=15.00) commande = models.ForeignKey(Commande, related_name='commande', on_delete=models.CASCADE) def add_cartdb(self, produit, qte, prix, commande): cartdb = self.create(produit=produit, qte=qte, prix=prix, commande=commande) return cartdb Here is my Views (views.py into same directory) : def order_list(request, date_before=None, date_after=None, statut_request=None, client_request=None): orders_list = Commande.objects.filter(statut='En cours').order_by('-date') clients = Client.objects.all() client_cmd = None if date_before: orders_list = orders_list.filter(date >= date_before) if date_after: orders_list = orders_list.filter(date >= date_after) if statut_request: orders_list = orders_list.filter(statut=statut_request) if client_request: client_cmd = get_object_or_404(Client, id=client_request) orders_list = orders_list.filter(client=client_cmd) paginator = Paginator(orders_list, 10) page = request.GET.get('page') try: orders = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. orders = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. orders = paginator.page(paginator.num_pages) context = {'client_cmd': client_cmd, … -
Combine existing models into one unmanaged model Django
I've currently got existing tables in my database that were created with models as per the usual way (using makemigrations and migrate). Now, I am looking to combine certain data from these existing tables, without having to create a new table in my database. Then, I would like to serialise that data to make it accessible via the views APIs. My understanding is that I create an unmanaged model to handle this. I understand as part of the docs that you need to specify managed = False but that's just a start. So far, I've literally only found one link (that isn't very helpful): https://riptutorial.com/django/example/4020/a-basic-unmanaged-table- Let's say hypothetically, I've got user information that is inputted in many different tables in my existing database and I'd like to create certain data points within my new and unmanaged model to combine it into one serialiser. As of now, this is what I've come up with. Note that in my user model, I don't know what to specify for my db_tables parameter since, like I mentioned, data will be coming from many different tables, not just one. UserModel from django.db import models class UserModel(models.model): user = models.CharField(db_column="LABEL", max_length=255) class Meta: managed = False … -
how can I fetch the specific ids data( multiple ids are stored in list) using Django
I want to fetch data of multiple ids which is provided from the User Interface and these ids are stored in a list. So how can I retrieve the data of these ids using Django ORM? When I try the following approach It returned nothing def selectassess(request): if request.method=='POST': assess=request.POST.getlist("assess") quesno=request.POST.getlist("quesno") subid=request.POST.getlist("subid") print(quesno,subid) print(assess) max_id = Sub_Topics.objects.all().aggregate(max_id=Max("id"))['max_id'] print(max_id) pk = random.sample(range(1, max_id),3) subss=Sub_Topics.objects.raw("Select * from Sub_Topics where id=%s",(str(pk),)) context4={ 'subss':subss, } print(pk) return render(request,"assessment.html",context) By applying the below-mentioned approach I can get only one id-data which is specified by typing the index value. But I want to get the data of all ids which are stored in the list so how can I get my required output by using Django ORM def selectassess(request): if request.method=='POST': assess=request.POST.getlist("assess") quesno=request.POST.getlist("quesno") subid=request.POST.getlist("subid") print(quesno,subid) print("youuuuu") print(assess) max_id = Sub_Topics.objects.all().aggregate(max_id=Max("id"))['max_id'] print(max_id) pk = random.sample(range(1, max_id),3) sub = Sub_Topics.objects.filter(pk=pk[0]).values('id','subtopic') context4={ 'sub':sub, } print(pk) return render(request,"assessment.html",context4)