Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Override django-ckeditor bullet style class
I have a django application that I'm using with tailwind, and I'd like to be able to apply the tailwind classes to my bullet lists by default. I have tried adding a custom style in the config.js file as well as the styles.js file, but for some reason it doesn't seem to update with any changes I make there? I've tried running collect static but it says files are unmodified 0 static files copied to '/code/myproject/static', 1280 unmodified. config.js CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.format_p={element:"p", name: "Normal", styles:{ 'color': 'red'}}; }; styles.js CKEDITOR.stylesSet.add( 'default', [ ] ); I don't have the bullet styles there yet, but even the paragraph change is not picking up. I realise I can do this with javascript to add class to all ul and li elements, but I'd rather not do that if there's a cleaner solution. -
Understanding Django exclude queryset on ForeignKey relationship
Really struggling to explain this one. I have the following models class Star(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=255, unique=True) class Image(models.Model): star = models.ForeignKey(Star, on_delete=models.CASCADE, related_name='images') status = models.BooleanField(verbose_name="Show online", default=True) With the following data Star table star name slug 1 Star 1 star-1 2 Star 2 star-2 Image table star status 1 False 1 True 2 True 2 False I then have the following query to grab a single star object with all the associated images with a status of True. star = Star.objects.filter(slug=slug).exclude(images__status=False).get() However this retunrs DoesNotExist exception, despite images with a status of true existing. Can anybody explain this? Any help would be much appreciated. -
construct url dynamically (name view as argument) with name space url tag in Django template
In a Django template, I want to construct dynamically urls I try to concatenate (see below) but got an error : Could not parse the remainder: '+key+'_index'' from ''ecrf:'+key+'_index'' {% for key, values in forms.items %} <!-- for exemple a key would be 'inclusion' --> <a href="{% url 'ecrf:'+key+'_create' %}">{{ key|capfirst }}</a> {% endfor %} urls app_name='ecrf' urlpatterns = [ path('inclusion/create/', views.InclusionCreate.as_view(), name='inclusion_create'), expected result: <a href="/localhost/ecrf/inclusion">Inclusion</a> -
Django - generate Zip file and serve (in memory)
I'm trying to serve a zip file that contains Django objects images. The problem is that even if it returns the Zip file, it is corrupted. NOTE: I can't use absolute paths to files since I use remote storage. model method that should generate in memory zip def generate_images_zip(self) -> bytes: content = BytesIO() zipObj = ZipFile(content, 'w') for image_fieldname in self.images_fieldnames(): image = getattr(self, image_fieldname) if image: zipObj.writestr(image.name, image.read()) return content.getvalue() ViewSet action @action(methods=['get'], detail=True, url_path='download-images') def download_images(self, request, pk=None) -> HttpResponse: product = self.get_object() zipfile = product.generate_images_zip() response = HttpResponse(zipfile, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=images.zip' return response When I try to open the downloaded Zip file, it says it's corrupted. Do you know how to make it work? -
How can I make one out of two fields required in my model/serializer?
I'm trying to allow my user to input either their email or their phone to continue. I've read a bunch of answers on here but none of them seem to work. For now I have the constraint in my model by it just returns " NOT NULL constraint failed: core_client.phone " This is the model and the serializer: class Client(models.Model): email = models.EmailField(max_length=200, unique=True, blank=True) phone = models.IntegerField(unique=True, blank=True) def clean(self): super(Client, self).clean() if self.email is None and self.phone is None: raise ValidationError('Validation error text') return super(Client, self).clean() def __str__(self): return self.email class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' Is there a better way to do it? I only want to the user to be created if both fields are filled but the user should still be able to continue on the website if they only wrote either one of the fields (there just wouldn't be an account for that user since they only completed one field). -
Django. Moving a redis query outside of a view. Making the query results available to all views
My Django app has read-only "dashboard" views of data in a Pandas DataFrame. The DataFrame is built from a redis database query. Code snippet below: # Part 1. Get values from the redis database and load them into a DataFrame. r = redis.StrictRedis(**redisconfig) keys = r.keys(pattern="*") keys.sort() values = r.mget(keys) values = [x for x in vals if x != None] redisDataFrame = pd.DataFrame(map(json.loads, vals)) # Part 2. Manipulate the DataFrame for display myViewData = redisDataFrame #Manipulation of myViewData #Exact steps vary based from one view to the next. fig = myViewData.plot() The code for part 1 (query redis) is inside every single view that displays that data. And the views have an update interval of 1 second. If I have 20 users viewing dashboards, the redis database is getting queried 20 times a second. Because the query sometimes takes several seconds, Django spawns multiple threads, many of which hang and slow down the whole system. I want to put part 1 (querying the redis database) into its own codeblock. Django will query redis (and make the redisDataFrame object) once per second. Each view will copy redisDataFrame into its own object, but it won't query the redis database over and … -
Make history for someting
i need to make tickets for an equipment How to filter that in views.py class Filter_Tickets(LoginRequiredMixin, ListView): model = Ticket template_name = 'workflow/history_of_equipment.html' def queryset(self): if(self.request.user.type == 'ENGINEER'): eng = Engineer.objects.get(id = self.request.user.id) eng_hos = eng.current_hospital dep_list = eng_hos.department_set.all() # ordering by the newest id object_list = [ticket for q1 in dep_list for eq in q1.equipment_set.all() for ticket in eq.ticket_set.all().order_by('-id')] return object_list elif(self.request.user.type == 'DOCTOR'): doc = Doctor.objects.get(id = self.request.user.id) doc_hos = doc.current_hospital dep_list = doc_hos.department_set.all() object_list = [ticket for q1 in dep_list for eq in q1.equipment_set.all() for ticket in eq.ticket_set.all().order_by('-id')] return object_list else: man = Manager.objects.get(id = self.request.user.id) dep_list = man.hospital.department_set.all() object_list = [ticket for q1 in dep_list for eq in q1.equipment_set.all() for ticket in eq.ticket_set.all().order_by('-id')] return object_list def get_context_data(self, **kwargs): context = super(Filter_Tickets, self).get_context_data(**kwargs) if(self.request.user.type == 'ENGINEER'): eng = Engineer.objects.get(id = self.request.user.id) context['eng'] = eng return context -
How to embad (show map in website) GIS shape file data in to my website?
Here, I'm trying to show GIS map in to my website. I'm using GIS dataset from https://opendatanepal.com/dataset/nepal-municipalities-wise-geographic-data-shp-geojson-topojson-kml this site. and I have following files in this dataset: local_unit.dbf local_unit.xml local_unit.shx local_unit.prj local_unit.sbn local_unit.sbx local_unit.shp Now I have problem is to use this file in to my Django/Python website. I'm trying to use like jquery library with ArcGIS from this: https://developers.arcgis.com/javascript/3/jssamples/framework_jquery.html. I don't know this is good way or not t use. Please suggest me how can I use GIS map in website. -
Django CSRF exception after removing clickjacking middleware
I need to fully load my website inside an iframe, so I deleted clickjacking middleware but after that, I got 403 code status and CSRF exception, how I can fix this to allow load my website inside iframe? -
Django - Class based view - Meta tags from model don't get passed to template
I am having an issue with my meta tags not being passed to my category.html template. Here are my models.py class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) image = models.ImageField(null=True, blank=True, upload_to='images/') meta_title = models.CharField(max_length=255) meta_keywords = models.CharField(max_length=255) meta_description = models.CharField(max_length=255) def __str__(self): return self.name Here are my views.py class CategoryView(ListView): model = Post template_name = 'category.html' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.filter(category=self.category) # def get_context_data(self, **kwargs): # context = super(CategoryView, self).get_context_data(**kwargs) # context['category'] = self.category # return context def get_context_data(self, *args, **kwargs): category_menu = Category.objects.values_list('slug', flat=True) context = super(CategoryView, self).get_context_data(*args, **kwargs) context['category_menu'] = category_menu return context The commented-out code works, however, I need the second one so that I can also display categories (name from Category model) on nav template. Here is my nav template <div class="container-fluid categories-main"> <ul class="categories list-inline mx-auto text-center"> {% for item in category_menu %}<a href="{% url 'categories' item %}">{{ item|capfirst }} {% endfor %}</a> </ul> </div> Here is my url.py urlpatterns = [ path('', HomeView.as_view(), name="home"), path('article/<slug:slug>', ArticleDetailView.as_view(), name="article-detail"), path('category/<slug:slug>', CategoryView.as_view(), name="categories"), and finally here is my category.html {% extends 'base.html' %} {% block title %} {{ category.meta_title }} {% endblock %} {% block meta_extend %} <meta name="description" content="{{ category.meta_description }}"> … -
Create an already populated dashboard with a displayed graph in Atoti using Django
I'm not sure how to word this differently but I'm integrating Atoti with a Django project using their project template, I've searched a lot in their documentation but I can't seem to get an answer about this. What I need to do is after a button click on a Django view, redirect the user to a custom Atoti Dashboard that's already populated with a specific information already displayed (for example, a line graph with a title). I don't need to save it unless the user wants because we're planning on using Atoti mainly as means of visualization. At this point in time, I can only redirect the user to the standard Atoti dashboard with my information and then create what I need to display but that's not user friendly at all and presumes the user has knowledge with Atoti. Anyone know if this is possible and if isn't, anyone has any suggestions on good Data Visualization libraries that make use of Django? Thanks in advance. -
Display the image in the django-tables2
settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class Product(models.Model): name = models.CharField(max_length=250) image = models.ImageField() tables.py import django_tables2 as tables from .models import Product class ProductTable(tables.Table): class Meta: model = Product fields = ("image" ,"name") views.py In the views.py , I filter the model objects and get QuerySet import django_tables2 as tables from .models import Product from .tables import ProductTable ----- table = ProductTable(new_objects) #new_objects is Product QuerySet return render(request, 'home.html', {'table': table }) Outcome I got a table, but instead of images, only links. How can I display the image?