Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
object is not shown in CategoryView
I wrote in top.html <div> <a href="#"> Category </a> <div> {% for category in category_content %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in category.html like <div> {% for content in queryset %} <h2>{{ content.title }}</h2> <a href="{% url 'detail' content.pk %}">SHOW DETAIL</a> {% endfor %} </div> When I put in top.html,no error happens and page is shown but no <h2>{{ content.title }}</h2> is shown here. I wrote in views.py class CategoryView(ListView): model = Category template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(name=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['categories'] = Category.objects.all() return context def category(self,pk): queryset = self.base_queryset() category = self.kwargs.get("category") queryset = queryset.filter(category__name=category) return queryset in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('category/<str:category>/',views.CategoryView.as_view(), name='category'), ] in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) class Index(models.Model): title = models.CharField(max_length=100) text = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) I want to show list of Index data that are by filtered Category in my db in category.html .For example, it is my ideal system ,when I put Python link in top.html,content.title which is related with Python is shown in category.html .But … -
What is JsonResponseMixin? How they work with the class based views
I have read about mixins and understood that A mixin is a special kind of multiple inheritance and provide a lot of optional features for a class. Now i want to know what are JsonResponseMixin and why they are used. class JsonResponseMixin(object): def render_to_json_response(self,context,**response_kwargs): return JsonResponse(context,**response_kwargs) def get_data(self,context): return context This is the code i found in mixin.py .Can someone please expain why this is used .Are they used in serializing data?Please elaborate -
Django: Use admin styles (css files and widgets) in my own app
Is there a simple way to use the admin-style css and widgets in your own app? -
How to get objects based on existence of object of another model?
In my Django app I have the following models: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET('deleted_user')) post_id = models.BigAutoField(primary_key = True) content = models.CharField(max_length = 2000) timestamp = models.DateTimeField(auto_now_add=True) original_poster = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET('deleted_user'), related_name='author') class Following(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='follows') followed_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='followed') I am using standard User model included in Django. Now I would like to retrieve posts of all users that are followed by a given user. What is the simplest way to achieve that? -
Django URLs randomly shows ImproperlyConfigured
I sometimes receive an ImproperlyConfigured "The included URLconf 'app_name.urls' does not appear to have any patterns in it." on my website. When I revisit the URL that caused the error, it works fine. The error shows that "patterns" is a module in these cases. Most of the time it properly loads my URLs. Does anyone spot a problem with my URLs? This is a strange issue that occurs on both the root URL (/) and the details page (####/details). I've never seen an error for my other URLs, but they don't receive much traffic. I haven't been able to reproduce the error, but I receive it several times a day. I'm using Python 3.5.2 with Django 2.0. The codebase was original written with Django 1.6 I believe. I recently migrated to 2.0 and that is when I noticed the issue. I modified django/urls/resolvers.py to log the 'patterns' variable and most of the time I receive this list: [<URLResolver <URLPattern list> (admin:admin) 'admin/'>, <URLPattern '<int:pk>/details' [name='details']>, <URLPattern 'check/' [name='check']>, <URLPattern 'logout/' [name='logout']>, <URLPattern 'search/' [name='search']>, <URLPattern 'features/' [name='features']>, <URLPattern 'terms-of-service/' [name='terms']>, <URLPattern 'privacy-policy/' [name='privacy']>, <URLPattern '' [name='index']>] urls.py from django.urls import path, re_path from django.contrib import admin from app_name import views … -
Jinja2 and Django Set up
Having trouble setting up Jinja2 on Django, attempting to set up on the latest iterations of the software using the how to below. Just wondering weather this setup is still relevant it's been a long time since this post. How to use jinja2 as a templating engine in Django 1.8 -
How do I upload and manipulate excel file with Django?
Ok, I had a look at the UploadFile Class documentation of the Django framework. Didn't find exactly what I am looking for? I am creating a membership management system with Django. I need the staff to have the ability to upload excel files containing list of members (and their details) which I will then manipulate to map to the Model fields. It's easy to do this with pandas framework for example, but I want to do it with Django if I can. Any suggestions. Thanks in advance -
How to use selenium grid with random clients(means no registration of IP)
Is it possible to use selenium server on a website where any user having the servers IP address can join-in? Without going to the server and personally registering the user as mentioned here. I work in an institution where proxy-IP addresses are cycled for security purposes. But I need no run a website on my server which allows clients to go to my website and perform minor automatic browsing and data scraping from a different website. To ensure correct data entry. -
VueJS Authentication with Django REST Key
I can retrieve a key after logging in through my Django REST API, but then I am wondering how I should store that key. I'm not really using Django, but I imagine I have to store the cookie myself then or something. I'm using Axios for VueJS to interact with the API. I am using django rest auth to get the token. -
How to manually make queries into the DB using Django?
Sometimes, I have to make migrations that implie in loss of the db. Then I have to manually go to the /admin page and re-insert every piece of data to start exploring my methods. So, is there any way to manually insert data into the db when I create the models.Model classes? (I'm using the default Django's db: sqlite) -
Categories' list is not shown
Categories' list is not shown.I wrote in views.py class CategoryView(ListView): model = Category template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(category=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['categories'] = Category.objects.all() return context in category.html <div> {% for content in queryset %} <h2>{{ content.title }}</h2> <a href="{% url 'detail' content.pk %}">SHOW DETAIL</a> {% endfor %} </div> <div> <a href="#"> Category </a> <div> {% for category in categories %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) Now FieldError at /app/category/Python/ Cannot resolve keyword 'category' into field. Choices are: created_at, id, name, post happens.I wrote context['categories'],so I really cannot understand why this error happens.What is wrong in my codes?How should I fix this? -
Implementing themes in Django (Custom templates by users)
I want to implement the feature for users to have custom templates. Like they can place themes or templates in a particular folder relative to the home folder. Each theme may have a folder and some config or preview for example(optional). 1) First I need to figure out how to set custom templates dir for an app. 2) Then I can probably do listdir and get all the folders and then give the admin an option to select the dir. 3) A setting list to specify additonal template folders by users. 1 is the problem. The main question I want answer for is how to set custom template dir which can be modified anytime. -
how to save one column value based on id column in django
I would like to save model id along with other format characters into another column, based on the model id being automatically created. For example, For example, I have column name formated_id in shipment model, and want set its value to "easter" + ID which is automatically generated. How could I achieve that? Thanks. class Shipment(models.Model): formated_id = models.CharField("formatedid",max_length= 50) class Meta: ordering = ['-id'] def save(self, *args, **kwargs): super().save(*args, **kwargs) -
Django force only one filefield use TemporaryFileUploadHandler
I have a filefield and in this filefield I want to upload a zip file and work with it from the view, but without saving it in MEDIA_ROOT, I just want to upload it and extract the xml extract info from the xml to send my model and db, the ones from the xml I have solved it, but my question is how can I use only TemporaryFileUploadHandler in this field, from the views and do all the work, the problem is that when it weighs less than 2.5mb it goes up to memory nothing more and the zipfile asks me for a path that's why I want to use the TemporaryFileUploadHandler, how can I do it? small abstract of my view: @login_required def crear_reporte(request): if request.method == 'POST': form = CreateReportForm(request.POST, request.FILES) if form.is_valid(): report = form.save(commit=False) user = request.user report.owner = UserProfile.objects.get(user_id=user.id) current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M") report.title = 'Reporte de ' + current_time + '.' report.save() filez = request.FILES['upload'] filereport = filez.name path = filez.temporary_file_path filereportcom = path + filereport with zipfile.ZipFile(filereportcom, 'r') as z: for f in z.namelist(): xmlss = len(z.namelist()) print (xmlss) print (filez.content_type) print (filez.size) return HttpResponseRedirect('/escritorio') -
SSL errors using Sauce Labs in Travis CI with Selenium webriver tests (Django project)
Trying to get some functional tests running for our Django project but we've hit an error that's proving very difficult to debug. We've attempted to set up sauce connect, but our build is failing. You can see the results of the build, but here's the stack trace. ====================================================================== ERROR: test_page_load (quote_me.tests.FunctionalTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/python/3.6.3/lib/python3.6/urllib/request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 964, in send self.connect() File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1400, in connect server_hostname=server_hostname) File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 407, in wrap_socket _context=self, _session=session) File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 814, in __init__ self.do_handshake() File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 1068, in do_handshake self._sslobj.do_handshake() File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 689, in do_handshake self._sslobj.do_handshake() ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:777) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/build/winecountry/quote-me/quote_me/tests.py", line 77, in setUp self.selenium = webdriver.Remote(desired_capabilities=capabilities, command_executor="https://%s/wd/hub" % hub_url) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 310, in execute response … -
Django 1.11 ignoring on_delete=models.set_null
I have a Django project with a model, something like this: class Track(models.Model): title = models.CharField(max_length=255) name = models.CharField(max_lenght=255) class Disc(models.Model): a_side_disc = models.ForeignKey(Track, null=True, on_delete=models.SET_NULL) b_side_disc = models.ForeignKey(Track, null=True, on_delete=models.SET_NULL) in_jukebox = models.BooleanField() This model is totally made up, and don't make sense, but it shows my current setup in this case. Now with Django 1.11 and Django Restframework, I have a route with a delete for a Track. When I call the Route, I check if the Track is on a Disc with in_jukebox set to False. If that is the case I simply go on with the delete. I expect that both ForeignKeys in Disc are set to Null, but instead Disc is deleted as well like I would expect from CASCADE. I use Postgres as database, and inspected the generated Schema. I understand that SET_NULL is done by django and not the database. But it is not done. Am I understanding somthing wrong? Which direction is on_delete working, and if it's only one, how do I make the same on the other side? -
Django - How to use a template tag in an if statement
I thought this idea would be more popular but I am guessing it's an easy solution that I cannot figure out. What I would like to do is in a Django template page, have an IF statement equal another tag value. For example views.py def seasonstandings(request): divisions = Team.objects.order_by().values_list('division__name',flat=True).distinct() stats = WeeklyStats.objects.values('player__team__team_name').annotate( team=F('player__team__team_name'), points = Sum('finishes'), division = F('player__team__division__name') ).order_by('-points') return render(request, 'website/seasonstandings.html', {'divisions':divisions,'stats':stats}) seasonstandings.html {% for division in divisions %} {{ division }} <br> {% for stat in stats %} {% if stat.division = {{ division }} %} {{ stat.team }}<br> {% endif %} {% endfor %} {% endfor %} So if you note the IF statement is trying to use the result of the Division tag from the first for loop. My main objective here is to have a dynamic list of divisions that a team could be in and then when they are assigned their division they would get listed out under the proper division based on these for loops. The End Result looking like Division A Team 1 Team 2 Team 4 Division B Team 3 Team 5 Division C Team 6 Team 7 Any help is appreciated as always. -
Restricting an embedded powerpoint to logged in users only
I am dynamically creating Powerpoints with user's personal information. I wanted to embed them online and Microsoft has the answer for this: <iframe src='https://view.officeapps.live.com/op/embed.aspx?src=[https://www.your_website/file_name.pptx]' width='100%' height='600px' frameborder='0'> Now I am wondering can I restrict these links to specific users? I only want user JOE to see the powerpoint the program created for him. I am planning on making this in Django -
Ubuntu Python: unable to pip install dlib - Failed building wheel for dlib and machine is almost stuck
I am trying to install dlib (machine learning library) for my django python environment. however, i cant get it installed. there is error and stuck. based on this instruction, this is what I did https://www.pyimagesearch.com/2017/03/27/how-to-install-dlib/ $ sudo apt-get install build-essential cmake $ sudo apt-get install libgtk-3-dev $ sudo apt-get install libboost-all-dev $ source somedotcomenv/bin/activate <-- virtualenv $ pip install numpy $ pip install scipy $ pip install scikit-image $ pip install dlib however, it failed and i think stuck, its almost an hour at the last stage. Im not sure if its still compiling or not. [ 82%] Building CXX object CMakeFiles/dlib_.dir/src/dlib.cpp.o In file included from /usr/include/boost/python/detail/prefix.hpp:13:0, from /usr/include/boost/python/args.hpp:8, from /usr/include/boost/python.hpp:11, from /tmp/pip-build-8xkp8e7q/dlib/tools/python/src/dlib.cpp:4: /usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory compilation terminated. CMakeFiles/dlib_.dir/build.make:62: recipe for target 'CMakeFiles/dlib_.dir/src/dlib.cpp.o' failed make[2]: *** [CMakeFiles/dlib_.dir/src/dlib.cpp.o] Error 1 CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/dlib_.dir/all' failed error: cmake build failed! ---------------------------------------- Failed building wheel for dlib Running setup.py clean for dlib Failed to build dlib Installing collected packages: dlib Running setup.py install for dlib ... full execution and error logs here https://gist.github.com/axilaris/fe58937e8ac39386e6e9816833636461 This is the last top process, its stuck not sure its still compiling but its already been an hour. something is stuck. very … -
What is the point of using Gunicorn when hosting a Django project on Linux VM
I have an Linux instance running on Google Compute Engine. I installed pip and django on it and cloned a Django project that I worked on locally. Like I would on localhost I ran my app like so: python3 manage.py runserver 0.0.0.0:8080, and my server was up and running with no problems. I read online on how WSGI servers are required for python apps to run well on servers however I don't see why I would need something like gunicorn to run my app -
Translation with Django
<form class="nav navbar-nav navbar-right" "{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Language" %}<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a class="btn btn-default lang_selector trn" href="#" role="button" data-value="ca" href="#"><span><img src="{% static 'orders/images/canada.jpg' %}" alt=""></span>{% trans "FRENCH" %}</a></li> <li><a class="btn btn-default lang_selector step1 trn" href="#" role="button" data-value="en" href="#"><span><img src="{% static 'orders/images/usa.png' %}" alt=""></span>{% trans "ENGLISH" %}</a></li> </ul> </li> <li class="section-btn"><a href="#" data-toggle="modal" data-target="#modal-form">{% trans "Login" %}<br>{% trans "Existing Customer?" %}</a></li> </form> The previous code gives me the following dropdown menu. I'd like the language change if I select FRENCH or ENGLISH. With the question Issue trying to change language from Django template, how could I modify my HTML code assuming that the other requirements are satisfied? -
Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response
I continue to keep getting this error even though I have the headers set in my nginx configuration like so: location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; try_files /maintenance.html @uwsgi; } If it's at all pertinent I am seeing this due to a request being made to instagram's api. I am using Spectragram to achieve this, however I do not think that is the issue. If it is I would be happy to give more info. What is additionally odd, is I have this instagram feed plugin working correctly on my localhost:5000, used for development, where I have very little in my nginx configuration, and no headers added... Thanks for any help! -
Javascript mini Navbar insert
I have an interesting but probably simple problem. I am creating a nav bar insert that has 4 JS buttons that toggle hide a division each, I would like each button to hide the other three divisions while showing the one its own division. Currently each button is only attached to it's own division, I am asking for help that would toggle the other three divs. Upon further thought I also would like to have the spades, hearts and clubs divs toggled off while the hearts on when a viewer first enters the page. If you think that there is a better method, I am open to that too, my framework is django jfyi. Cheers! JS: // Card Navigation Bar function dhide() { var x = document.getElementById("diamonds"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function chide() { var x = document.getElementById("clubs"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function hhide() { var x = document.getElementById("hearts"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function shide() { var x = document.getElementById("spades"); if (x.style.display === "none") … -
MySQL with django Grants issue while deploying on pythonanywhere
The MySQL database is connected to the pythonanywhere server. When i insert data in it it gives error 500 after doing R&D I found there is privileges or grant issue. How can i give grants. I used basic Grants query after connection.enter image description here -
Can't save ForeignKey data with Django
I'm trying to make a way to log notes associated with records. When the form is submitted, it's trying to redirect to the same url, but without the record id, which should be required to view the page. I defined it in urls with the record id, so it should be tracker/19/newnote I want it to route to tracker/19/detail, and I'm not sure why it's routing to tracker/newnote, which doesn't exist in my urls file. Maybe I need to create it? anyway, here are my files if anyone wants to take a crack at this with me. models.py class Record(models.Model): serial = models.CharField('Serial Number', max_length=9) product = models.CharField('Product', max_length=6) ticket = models.CharField('Log/RID', max_length=9) eng_date = models.DateField('Date Engaged') customer = models.CharField('Customer', max_length=80) details = models.TextField('Problem Details', max_length=800) owner = models.CharField('Owner', max_length=40) views.py def newnote(request, record_id): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): r = Record.objects.get(pk=record_id) r.note_set.create(note_text=form.note_text, note_date=form.note_date) r.save() return HttpResponseRedirect('/tracker/%s/detail/' % record_id) else: form = NoteForm() return render(request, 'tracker/noteform.html', {'form': form}) forms.py class NoteForm(ModelForm): class Meta: model = Note fields = ['note_text', 'note_date' ] widgets = { 'note_date': DateInput(),} urls.py urlpatterns = [ path('', views.index, name='index'), path('create/', views.create, name='create'), path('<int:record_id>/detail/', views.detail, name='detail'), path('result/', views.result, name='result'), path('query/', views.query, name='query'), path('all/', …