Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My images are not being visualized Django
Hi i´m doing an ecommerce project with Django and i have the following issue; when i upload a product from my admin panel the product image is not shown just the place holder as if there was an image in there. proyecto/proyecto/settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') tienda/urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) tienda.html: {% extends 'tienda/index.html'%} {%load static%} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img src="{{product.image.url}}" alt="" class="thumbnail" > <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Agregar al carrito</button> <a class="btn btn-outline-success" href="">Ver</a> <h4 style="display: inline-block; float: right;"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {%endfor%} </div> {% endblock %} The first time i did this worked and suddenly i refreshed one time the page and never again where the images shown in my page. -
how to display plotly json object in html template
I have a django application that displays a few charts generated using plotly. This is my views.py file def assam(request): const_list = pd.read_csv('./const.csv').Const.unique() part_list = pd.read_csv('./part_list.csv').abbr.unique() part_bargraph = main_graph(part_list, len(const_list)) context = {'main_graph': part_bargraph} return render(request, 'home.html', context) The main_graph is a function that takes a list and an int value as parameters and generates a plotly graph. This graph is then returned as a json object using the plotly.io.to_json method. I want to display this graph in an HTML template. This is what I am doing right now <div class="main_graph"> {% if main_graph %} <script> { { main_graph: "safe" } } </script> {% else %} <p>No graph was provided.</p> {% endif %} </div> But this does not seem to work. What am I doing wrong? Thanks in advance -
calling a template and return it as a string in django from view
In my django project I want to call my template with from views.py with a list view and return it like a string in my view function. This is because I want to print the string as an pdf. Is it possible to call the template with context_object_name so it can generate the html page and then return it an an string to my pdf generator, weasyprint? views.py: def eprint(request): g=request.GET checked=g.getlist('marked[]') print(checked) res=[Concert.objects.get(pk=l) for l in checked] con='<table class="table table-hover table w-auto text-xsmall cellspacing="1" cellpadding="1" table-striped table-sm">' paragraphs=['first paragraph', 'second paragraph', 'third paragraph'] # html_string=render_to_string('test', {'paragraphs': paragraphs}) hres=render(request,'events.html',{'cc':res}) html=HTML(string=hres) # html=HTML(string=html_string) html.write_pdf(target='pdf/test.pdf'); fs = FileSystemStorage('pdf') with fs.open('test.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="test.pdf"' return response return response class Events(ListView): context_objecjt_name='cc' model=Concert template_name='kammem/events.html' events.html: {% for l in object_list %} <tr> <td> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> </td> <td><a href="eupdate/{{l.pk}}"><i class="bi bi-pencil-square"></i></a></td> <td><a href="edelete/{{l.pk}}"><i class="bi bi-trash"></i></a></td> <td>{{l.pk}}</td> <td>{{l.cname}}</td> <td><a href="detail/{{l.venue.pk}}">{{l.venue}}</a></td> <td>{{l.date}}</td> <td><a href="detail/{{l.organizer.pk}}">{{l.organizer}}</a></td> <!-- <td><a href="detail/{{l.vadress.pk}}">{{l.vname}}</a></td> --> <!-- <td>{{l.organizer}}</td> --> <td>{{l.antmus}}</td> <td>{{l.män1}}/{{l.kvinnor1}}</td> <td>{{l.publik}}</td> <td>{{l.män2}}/{{l.kvinnor2}}</td> </tr> {% endfor %} </tbody> -
how can I extends from another class
I'm new in Python/Django and I'm working on a little project to improve my self, I would like to know how can I extends or how can I call a function from another class I already tried but I got some errors this is my code : first class # Create your views here. class ContactCenter(object): def myFunction(self, logged_user_id = None): print("hello") second class from apps.contact.views import ContactCenter class ListModelMixin(object): def list(self, request, *args, **kwargs): ContactCenter.myFunction() -
No Data is Getting Sent to Django Rest Framework API
I am trying to send the Post objects to my API for posts where followers of a user each have a Source_id and Source_id=Post.sourceID. Basically, I am trying to return all the Post objects for the followers of a user in order to then render a feed. But, I am running into a problem because my API is not returning any data, even though I made sure the data is in the database. In my views.py, this is what I am doing: class FeedAPI(ObjectMultipleModelAPIView): #lookup_url_kwarg = 'id' def get_querylist(self, *args, **kwargs): id = self.kwargs['id'] if id != None: profile = Profile.objects.filter(id=id) if len(profile) > 0: data = ProfileSerializer(profile[0]).data return Response(data, status=status.HTTP_200_OK) querylist = [ {'queryset': Profile.objects.all(), 'serializer_class': ProfileSerializer}, {'queryset': Post.objects.all(), 'serializer_class': PostSerializer}, {'queryset': Source.objects.all(), 'serializer_class': SourceSerializer}, ] props = Source.objects.filter(profile_id=id) followers = [f.pk for f in Profile.objects.filter(followers__in=props)] return followers feedPosts= [] postID = Post.objects.filter() i=0 length = len(followers) #while i < length: #feedPosts = list(Post.objects.filter(Source_id=Post.sourceID)) #return feedPosts(i) #i+=1 for x in followers: feedPosts = Post.objects.filter(Source_id=followers) return feedPosts(x) return Response(feedPosts, status=status.HTTP_200_OK) The url is path('feed/<int:id>', views.FeedAPI.as_view()), models class Profile(models.Model): user = AutoOneToOneField(User, default=True, on_delete=models.CASCADE) sourceID = models.ForeignKey('Source', on_delete=models.CASCADE, related_name='+', blank=True, null=True) followers = models.ManyToManyField( 'Source', related_name='+', default='', blank=True, null=True) following = … -
Run django and postgresql on two computers
We are developping a website with two developpers. The first one is a superuser but not the second one. We don't have a server but only a mutualized server. The issue is that when we need to do python manage.py migrate (or makemigrations), we have to log in the website of the server provider and to open the security consol (which is only open for ten minutes), which takes 2/3 minutes each time. When i was working alone, it was faster to have a local database on my computer and to do a quick manage.py migrate in conda. Is it possible to use my personnal conda window to do a manage.py makemigrations on a distant mutualized database ? If not what would be the best solution to share the database ? Thanks a lot -
how to use pagination
def subcategoryProduct(request, subcategory_slug=None): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] subcategory = None subcategories = SubCategory.objects.all() categories = Category.objects.all() product = Product.objects.filter(available=True).order_by('?') page = request.GET.get('page',1) paginator = Paginator(product,2) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if subcategory_slug: subcategory = get_object_or_404(SubCategory, slug=subcategory_slug) products = paginator.object_list.filter(subcategory=subcategory) -
Django No module named win32com?
I got this issue. I have to deploy my Django project from a Mac computer(OSX). But I get this error: No module named win32com Is there a way or alternative library? This is where I need it: views.py excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True ex = excel.Workbooks.Open(save_path) ex_sheet = ex.Worksheets('Finansal Tablolar_formul') ex_sheet.Columns.AutoFit() ex_sheet_2 = ex.Worksheets('Finansal Tablolar_formul') ex_sheet_2.Columns.AutoFit() ex.Save() ex.Close(True) excel.Application.Quit() -
Django extends tag loading wrong templates
I'm building a new site in Django using TailWind CSS and have been trying to utilize to the use of extends tags and block content. This is the base.html file: {% load static %} <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>{% block title %}{% endblock %}</title> <meta name="description" content="{% block description %}{% endblock %}"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="canonical" href=""/> <link rel="stylesheet" type='text/css' href="{% static 'css/style.css'%}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;1,400;1,800&display=swap" rel="stylesheet"> </head> <body> <!-- START NAV --> <div class="w-full text-gray-700 bg-white dark-mode:text-gray-200 dark-mode:bg-gray-800"> <div x-data="{ open: false }" class="flex flex-col max-w-screen-xl px-4 mx-auto md:items-center md:justify-between md:flex-row md:px-6 lg:px-8"> <div class="p-4 flex flex-row items-center justify-between"> <a href="{% url 'main' %}" class="text-lg font-semibold tracking-widest text-gray-900 uppercase rounded-lg dark-mode:text-white focus:outline-none focus:shadow-outline">Dummy Logo</a> <button class="md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open"> <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6"> <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 … -
convert string value to integer in Django template
In home.html <div class="container"> <div class="row"> <div class="col-md-6"> <h3>Select products:</h3> <form id="selectProduct" role="search" method="get" action="{% url 'home' %}"> <select name="parameters" data-placeholder="Choose products" class="chosen-select" multiple tabindex="4"> {% for p in productnames %} {% if k == p %} <option value="{{ p.productnames }}" selected> {{ p.productnames }} </option> {% else%} <option value="{{ p.id }}"> {{ p.productnames }} </option> {% endif %} {% endfor %} </select><br/> <label for="submit"></label><button id="submit" type="submit" class="btn btn-default">Submit</button> </form> </div> </div> <div class="row"></div><br /> <h3> Distribution of sales in the products:</h3> </div> </div> {% for p in productList %} {% for pin in productnames %} <p>{{pin.id}} {{p}}</p> {% if p == pin.id %} <p>exists</p> {% else %} <p>not exist</p> {% endif %} {% endfor %} {% endfor %} <p>{{ productList }}</p> in this html file 'p' always returns a string value for ex: it returns like '10' instead of 10. all i want is to convent this '10' to 10 or convert returned other p_in value to 10 to '10'. in views.py def productList(request): if request.method == 'GET': p = request.GET.get('parameters') print(p) #k = request.GET('parameters[]') productnames = Products.objects.all() context = { 'productList': p, 'productnames': productnames, } return render(request, 'home.html', context) I tried to convert the values of the p … -
Why does the script tag, not work in djagno?
I am using the navbar of this example project of Bootstarp 4.6. in my django project. Here is the code. $(function() { 'use strict' $('[data-toggle="offcanvas"]').on('click', function() { $('.offcanvas-collapse').toggleClass('open') }) }) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--Bootstrap--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!--Navbar--> <link rel="stylesheet" href="{% static 'css/quicky/navbar.css' %}"> <title>The</title> </head> <body> <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark"> <a class="navbar-brand mr-auto mr-lg-0" href="#">Offcanvas navbar</a> <button class="navbar-toggler p-0 border-0" type="button" data-toggle="offcanvas"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Dashboard <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Notifications</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Profile</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Switch account</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Settings</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="nav-scroller bg-white shadow-sm"> <nav class="nav nav-underline"> <a class="nav-link active" href="#">Dashboard</a> <a class="nav-link" href="#"> Friends <span class="badge badge-pill bg-light align-text-bottom">27</span> </a> <a class="nav-link" href="#">Explore</a> <a class="nav-link" href="#">Suggestions</a> <a class="nav-link" href="#">Link</a> <a class="nav-link" … -
i am making a test application in django and i want to submit the form when the time is over
this is my Html file and here I am trying to submit the form after 1 minute with all the values user has entered but the form is not posting any values <script> function countdown( elementName, minutes, seconds ) { var element, endTime, hours, mins, msLeft, time; function twoDigits( n ) { return (n <= 9 ? "0" + n : n); } function updateTimer() { msLeft = endTime - (+new Date); function submitform(){ document.getElementById("myForm").submit(); window.location.href = "http://127.0.0.1:8000/acceptAnswer"; } if ( msLeft < 100 ) { submitform() } else { time = new Date( msLeft ); hours = time.getUTCHours(); mins = time.getUTCMinutes(); element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() ); setTimeout( updateTimer, time.getUTCMilliseconds() + 500 ); } } element = document.getElementById( elementName ); endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500; updateTimer(); } countdown( "ten-countdown", 1, 0 );</script> <div class="container" > <div style="margin-left: 45%;" id="ten-countdown"></div> <form id="myForm" action="{% url 'acceptAnswer' %}" method="POST"> {% csrf_token %} {% for key, value in questions.items %} {{key}}){{value.question}} <br> <input type="radio" id="1" name="{{key}}" value="1">:{{value.option1}}<br> <input type="radio" id="2" name="{{key}}" value="2">:{{value.option2}}<br> <input type="radio" id="3" name="{{key}}" value="3">:{{value.option3}}<br> <input type="radio" id="4" name="{{key}}" value="4">:{{value.option4}}<br> {% … -
Django ManyToMany Field admin display highest value
I want to know how I can display the "highest value" from my ManyToMany Field in the admin. This is my models.py file: class Personal(models.Model): lastname = models.CharField(max_length = 100) firstname = models.CharField(max_length = 100) degree = models.ManyToManyField('Degree') def __str__(self): return self.lastname class Degree(models.Model): name_degree = models.CharField(verbose_name = 'Degree', max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name_degree In my backed, I have created different types of Degree's, all with a "ranking". In my case, the highest degree you can have is "Doctoral Degree", with a rank of "6". So if a User is creating himself in "Personal" he will have the option to select all the Degree's he has achieved. But for my Personal list, I just to want to see the highest one, e.g. if the User selects "Bachelor's Degree" and "Master's Degree", the Personal list should only contain "Master's Degree", because 5 > 4. Someone with an idea on how my admin.py file should look like? class PersonalAdmin(admin.ModelAdmin): list_display = ('lastname', 'firstname', ) # 'degree' -
NoReverseMatch at / 'learning_logs' is not a registered namespace
I think i tired everything in trying to solve this problem. I'm getting a NoReverseMatch i understand its from my "urls" but that's basically it, I was using url() instead of path().at the end of it all i just made a mess of my code. view.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic as TopicModel from .forms import TopicForms # Create your views here. def index(request): """"the home page for learning app""" return render(request,'learning_logs/index.html') def topics(request): topics = TopicModel.objects.order_by('date_added') context = {'topics' : topics} return render(request, 'learning_logs/topics.html',context) def topic(request, topic_id): """show a single topic ans all its entries""" topic = TopicModel.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic':topic, 'entries': entries} return render(request,'learning_logs/topic.html',context) def new_topic(request): """add a new topic""" if request.method != 'POST': #no data submitted ; create a black form form = TopicForms else: #POST data submited ; process data if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_log:topics')) context = {'form': form } return render(request,'learning_log/new_topic.html', context) urls.py #defins URL patterns for learning log from django.conf.urls import url from . import views from django.urls import path app_name = 'learning_log' urlpatterns = [ #home page path('', views.index, name ='index'), #url(r'^$', views.index, name='index.html'), #show topics path('topics/',views.topics, name ='topics'), … -
Get the previous values of a multi-step form to render the future form in Django
I am making a project in Django but Im not using Django built-in forms. Rather, I have my way with html and bootstrap to render forms. On a page, I want to create a quiz. I am doing this via a multi-step form where I input the number of questions on the first form. Then based upon this field, when I hit next, I want to have the same number of the fields for questions and corresponding answers to appear so that I can set them. Is there a way to dynamically do this? Your help is much appreciated Thank you n here is my code snippet {% block content %} <div class="row"> <h2 style="color: darkblue;" class="text-center">Add a Quiz</h2> </div> <form action="" id="add_test_form" method="POST"> <!--This form will contain the quiz information--> {% csrf_token %} <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Name of test</label> <input type="text" class="form-control" name="test_name" required> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Description</label> <textarea type="text" class="form-control" name="test_desc" rows="8" required></textarea> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Number of questions</label> <input type="number" class="form-control" name="test_num_questions" min="1" oninput="validity.valid||(value='')" required> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Time( Duration) in minutes</label> … -
'WSGIRequest' object has no attribute 'template' (Attribute Error while rendering a class based view in django)
What my view does, is takes an even from id, and returns an html page containing a table of all the details. It is a simple enough view: class Edetails(View, SuperuserRequiredMixin): template = 'events/details.html' def get(request, self, pk): event = Event.objects.get(id=pk) count = event.participants.count() participants = event.participants.all() ctx = { 'count': count, 'participants': participants, 'pk': pk } return render(request, self.template, ctx) However, when i click on the link to send a get request to the view: <a href="{% url 'events:Edetails' event.id %}">View Participants</a> I get this error message: AttributeError at /Edetails2 'WSGIRequest' object has no attribute 'template' I don't understand what this means. How can i fix this? -
Hello hope all of you are well i want to select motherboard on the basis of socket and chipset supported by CPU but it can fetch all motherboard
**basically, i want to develop a website like pc part picker in Django I want to select a motherboard on the basis of socket and chipset supported by CPU problem is it can fetch all motherboard I want to select only those motherboard having the same socket and chipset stored in session problem in build_mobo **here are models**** class vendor(models.Model): vendor_name=models.CharField(max_length=250) def __str__(self): return self.vendor_name class socket(models.Model): socket_type = models.CharField(max_length=250) def __str__(self): return self.socket_type class chipset(models.Model): cpu_chipset=models.CharField(max_length=250) def __str__(self): return self.cpu_chipset class CPU(models.Model): image = models.ImageField(upload_to="uploads/product/") vendor = models.ForeignKey(vendor , on_delete=models.CASCADE) cpu_name=models.CharField(max_length=250) cpu_price = models.CharField(max_length=250 , default="") generation = models.CharField(max_length=250) socket= models.ForeignKey(socket ,on_delete=models.CASCADE) chipset =models.ManyToManyField(chipset) def __str__(self): return self.cpu_name class Motherboard(models.Model): mobo_name= models.CharField(max_length=250) chipset = models.ForeignKey(chipset , on_delete=models.CASCADE) socket = models.ForeignKey(socket ,on_delete=models.CASCADE) vendor = models.ForeignKey(vendor , on_delete=models.CASCADE) DIMM_sockets = models.CharField(max_length=250 ,default="single", choices=(("dual","dual"), ("single","single"),("4","4"))) Supported_ram= models.CharField(max_length=250 ,default="ddr3", choices=(("ddr3","ddr3"), ("ddr4","ddr4"))) Onboard_Graphics= models.CharField(max_length=250,blank=True,null=True) Expensions_socket_version= models.CharField(max_length=250 ,default="version 1", choices=(("version 1","version 1"), ("version 2","version 2"), ("version 3","version 3"))) Audio =models.CharField(max_length=250,blank=True,null=True) LAN =models.CharField(max_length=250 ,blank=True,null=True) Storage_Interface =models.TextField(max_length=250 ,blank=True,null=True) USB =models.TextField(max_length=250 ,blank=True,null=True) def __str__(self): return self.mobo_name my view is : def build_cpu(request): data = CPU.objects.all() d = {'data1': data} return render(request, 'build/cpu.html', d) def build_home(request): if request.method == 'POST': cpu_id = request.POST['cid'] cpu_nam = request.POST['nammm'] dat = CPU.objects.get(cpu_name=cpu_nam) … -
Issues with Django Translations when deploying Webapp to Azure (localhost works)
Azure: Linux Webapp Deployment towards Azure via Azure Devops Pipeline on localhost everything works but on the Azure site it seems it does not get translated -
django request authentication every app after deployment in google cloud
after I have hosted my django app on google cloud, I keep asking for login every time I click on an app link. Does anyone know why? -
Trying to open select2 on page load gives the error “The select2('open') method was called on an element that is not using Select2.”
Trying to open the select2 on page load using document.ready doesn't work because "autocomplete_light.js initialize function" is tied to same event and at document.ready, the componente isn't initialized yet. So, doing as below doesn't work: $(document).ready(function () { $('#select2_field').select2('open') //OR $('#select2_field').open() }); The problem is that django autocomplete_light initializes the field on document.ready too. I need to open and focus the field on page load, same event. When I try to do so, it gives the error: The select2('open') method was called on an element that is not using Select2. If I access the method on another event, after document.ready, it works. So, the question is, how can I open the select2 on page load, after it has been initialized by autocomplete light? Autocomplete light doesn't have any callback that I could use. -
PyCharm with django template cannot recognize javascript without <script> tag
In order to centralize on "document ready" javascript bits, in my Django base template I have a main.html something like this : ... <script type="text/javascript"> <!-- $(document).ready(function () { {% block jqueryDocReady %}{% endblock jqueryDocReady %} ... some global init ... }); //--> </script> In views I use a new template that inheriates from the base template and add some javascript bits : {% extends ".../main.html" %} ... {% block jqueryDocReady %} {{ block.super }} some_init_vars = {{ context_var }}; ... and some little view specific javascript code ... {% endblock %} Here comes my problem with PyCharm : the javascript syntax coloration does not work in view specific code : some_init_vars = {{ context_var }}; ... and some little view specific javascript code ... The reason is because I cannot add here <script></script> tags as there are already present in base template. I do not want to create many little .js file for every little view-specific code. How can I make Pycharm color javascript code bits without any script tags or how can I reorganize my code to be nicer for Pycharm while being still concise ? -
Unresolved reference 'graphene_django'
I just started working with GraphQL, Django and Graphene. I was attempting to import GraphQLView and DjangoObjectType from graphene_django but it always says unresolved reference I did already installed the needed modules with pip install graphene-django==2.8.2, and the Virtual environment is up and running. #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books', 'graphene_django', ] I couldn't get graphene_django to import properly. What are the possible fixes to this? -
Django: Customize Admin page or create admin app
I want to create a login page and an admin page for users (with different permissions) for a web project. In it, models from different apps can be edited. However, the linked models should be edited in different structures, e.g. model in "Settings" for an app. Should I modify and adapt the Django Admin interface more for this or create an 'Admin' app in which I regulate this through forms? -
Django : Git ignored files are deleted automatically after every git push to the server
I have a local repo that has a live remote to our Django server, where I have a git post-recieve hook to deploy pushed files. The problem is, the files under gitignore are deleted automatically as soon as a new commit is pushed to the server. The files are namely local_settings.py, db.sqlite3 and the /media directory. For obvious reasons, I want those files to be utilized off the server itself. After a commit, I manually added those files/folders back to the website directory, and everything works fine, until I push another set of updates to the server. Whenever this happens, the updates come out fine but local_settings.py, db.sqlite3 and the /media directory is auto-deleted somehow and nowhere to be seen. This is making my deployment a nightmare and I've been struggling with it for the past 3 days. Any help/insight into this will be highly appreciated, thank you! -
How to override foreign key null values in django serializer?
I'm serializing a query set to json format using natural_keys. Reference: docs I'm able to serialize data successfully. In case, there are any foreign keys, then I'm also able to add it's object instead of foreign key. For example: class Parent(models.Model): name = models.CharField() def get_natural_keys(self): return( {'name': self.name, 'pk': self.pk} ) class Child(models.Model): name = models.CharField() parent = models.ForeignKey(Parent, null=True) And while querying data: child = serializers.serialize('json', Child.objects.all(), user_natural_foreign_keys=True, use_natural_primary_keys=True) This will return json: { "model": 'proj.child' "pk": 1, "fields": { "name": "child name", "parent": {"id": 1, "name": "parent name"} } } Till this point every thing is fine. My issue is that when parent foreign key is null in child, it returns None in parent: fields: { "name": "child name", "parent": None } How I am expecting is: fields: { "name": "child name", "parent": {"id": None. "name": None} } How can I override the None value to another dictionary?