Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create model method using fields from two different models?
I am trying to create a model method that takes data from a field in one model and performs simple arithmetic using data from a field in another model. I am not trying to create a QuerySet in views.py, rather I am trying to create a model method in models.py that I can easily access via a context variable in my html (e.g. obj.model.modelmethod). Below is a very simplified version of my models (before adding the desired model method): class Person(models.Model): ''' This table serves as the ultimate parent. ''' id = models.IntegerField(auto_created=False, primary_key=True) name = models.CharField(max_length=128, null=True, blank=True) def __str__(self): return self.name class SalaryYearOne(models.Model): id = models.OneToOneField( Person, on_delete=models.DO_NOTHING, db_constraint=False, primary_key=True ) salary1 = models.IntegerField(null=True, blank=True) class SalaryYearTwo(models.Model): id = models.OneToOneField( Person, on_delete=models.DO_NOTHING, db_constraint=False, primary_key=True ) salary2 = models.IntegerField(null=True, blank=True) The model method I want to create will be under the SalaryYearOne class. The goal is calculate the salary percent change year-over-year (rounded to two decimal places). For example: class SalaryYearOne(models.Model): ... def salary_percent_change(self): return round((self.salary1 - self.salary2) / self.salary2, 2) The aforementioned is more for illustrative purposes. I understand that there are several issues with it as written. For example, I understand that the SalaryYearOne table does not β¦ -
Django, URL and Views not found
I'm using Django 2.1 and testing views.py and urls.py What I don't understand is why whenever I enter the URL http://127.0.0.1:8000/blog/post_list I get a 404 error message My top urls.py: from django.urls import path from django.contrib import admin from django.conf.urls import include, url from organizer import urls as organizer_urls from blog import urls as blog_urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(organizer_urls)), path('tag/', include(organizer_urls)), path('startup/', include(organizer_urls)), path('blog/', include(blog_urls)) ] my application's urls.py from django.urls import path from blog.views import post_list, post_detail urlpatterns = [ path('', post_list, name='blog_post_list'), path( '<int:year>/<int:month>/<slug:slug>', post_detail, name='blog_post_detail'), ] my application's views.py: from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): return render( request, 'blog/post_list.html', {'post_list':Post.object.all()} ) def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) the error message is: Using the URLconf defined in suorganizer_project.urls, Django tried these URL patterns, in this order: admin/ tag/tag_list [name='organizer_tag_list'] tag// startup/startup_list [name='organizer_startup_list'] startup// [name='organizer_startup_detail'] tag/ startup/ blog/ The empty path didn't match any of these. -
Django 1.11:Apps aren't loaded yet
I'm learning how to do web programming with Django framework and I got this error message when I try to return a template. When I try to load https://www..../index2/ everything is ok. This is my urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^index2/$', views.index2, name='index2'), ] This is my views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, 'main/index.html',) def index2(request): return HttpResponse("Hello, world.") -
django warning urls.W005 URL namespace isn't unique
I am having trouble understanding the following warning. I have a namespace called "v1" and I am using these namespaces to determine versioning in my API (using django rest framework). So, I have paths like these: /v1/accounts/me /v1/listings Here is the URLs configuration (project/urls.py): urlpatterns = [ path('admin/', admin.site.urls), path('v1/accounts/', include('accounts.urls', namespace='v1')), path('v1/listings/', include('listings.urls', namespace='v1')) ] accounts/urls.py app_name = 'accounts' urlpatterns = [ url(r'^token/$', views.obtain_auth_token, name='obtain_token'), url(r'^me/$', my_account, name='my_account'), ] listings/urls.py app_name = 'listings' urlpatterns = [ path('', recent_listings, name='recent_listings') ] Everything works as expected. All urls are dispatched. Versioning works. However, I keep getting the following error: ?: (urls.W005) URL namespace 'v1' isn't unique. You may not be able to reverse all URLs in this namespace I know it is a warning and I might be able to suppress it; however, I want to understand why this is happening. Based on my URLconf and this warning, it seems like there cannot be multiple namespaced paths as "siblings." They need to be children of one namespaced path (e.g "v1"). If my understanding is correct, how am I supposed to create this URL configuration. -
Using postcodes.io API on Django
I'm trying to achieve this: Use postcodes.io to get the latitude and longitude for each postcode and render them next to each store location in the template I have a series of postcodes into a json file: [ { "name": "St_Albans", "postcode": "AL1 2RJ" }, { "name": "Hatfield", "postcode": "AL9 5JP" }, { "name": "Worthing", "postcode": "BN14 9GB" }, { "name": "Rustington", "postcode": "BN16 3RT" }, { "name": "Eastbourne", "postcode": "BN23 6QD" }, ... And so on... I need to check on postcodes.io[0] the latitudes and longitudes of these postcodes, and render these coordinates next to the json result. My question isn't about on how to render them, it's about on how to POST my json postcodes on their website, and get the respective latitudes and longitudes of each one. I'm doing this on pure python, any ideas? 0.- https://postcodes.io/docs -
API url routing - Django/Postman
I am messing around with a backend Django API tutorial (Django 2.1) and I am having trouble pulling 'profile' information via Postman. My assumption is that I am not correctly stating my url in my urls.py. Here is my project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('conduit.apps.authentication.urls'), name='authentication'), path('api/v1/', include('conduit.apps.profiles.urls'), name='profiles') ] Here is my profiles.urls.py: from .views import ProfileRetrieveAPIView urlpatterns = [ path('profiles/<username:username>/', ProfileRetrieveAPIView.as_view()) ] I think my issue has to do with how I am implementing / to the end of my path. My only other relevant experience with this kind of mechanism was on prior projects where I was using something like this for unique blog post url routing (which I have done successfully): ".../<slug:slug>/" Now, here is my relevant class-based view for the above url: class ProfileRetrieveAPIView(RetrieveAPIView): permission_classes = (AllowAny,) renderer_classes = (ProfileJSONRenderer,) serializer_class = ProfileSerializer def retrieve(self, request, username, *args, **kwargs): try: profile = Profile.objects.select_related('user').get( user__username=username ) except Profile.DoesNotExist: raise ProfileDoesNotExist serializer = self.serializer_class(profile) return Response(serializer.data, status=status.HTTP_200_OK) You can see in my retrieve function, I am working with a username attribute. This is what I think I am trying to match up with my url path. I am guessing that I am probably not β¦ -
Empty Set using fitler startswith
Here's my model: class Student(models.Model): name = models.CharField(max_length=100) student_id = models.IntegerField() grade = models.IntegerField() I imported the data from Excel.I want to use Student.object.filter(name___istartswith = _ ) because every Student.name instance as "\xa0" before it. I've tried: .filter(name___contains= _) works (but is not what I need) Replacing "\xa0" with s.name.replace("\xa0",'') did...nothing. The "\xa0" returned! .filter(name___istartswith = u_ ) Every time I run Student.objects.filter(name__istarts with = _) an empty set is returned. I'm sure it's something dumb, but what am I doing wrong? (Running python 3.5) -
Django relationships in models
I have a problem with creating relationship for models. I tried to use ForeignKey to complete structure like this: Tech -> Firm -> Model -> type of fix Tech can have different objects, for example computer, phone, or tablet. At this moment, I got problem. Computer can include firms of phones. How I can fix it? uml-scheme of my structure for this moment: https://i.stack.imgur.com/KvRfw.png -
How to implement a global class in django
I am currently working on a networked multiplayer game using django and django channels for websockets. I currently have my project set up where players send data to the server which then processes that data in a "GameManager" class that processes all game logic and interactions between all players. This works perfectly fine in my dev environment, but when I tried setting up my project for production, my global "GameManager" class does not seem to retain it's data across multiple requests. I'm guessing that since I'm using gunicorn in my production environment, my django project is running amongst multiple processes that each have their own instance of my classes. My question is how can I implement some sort of global class in django to handle all the game logic that will be shared across all requests? I can't use sessions because I need this data to be shared by ALL connected clients, and I'm skeptical of using a solution such as redis because I would need to be reading/writing to it multiple times a second, so keeping it within python would help me keep things running smoothly. Any help would be greatly appreciated. -
how to use a forloop such that the if the "IF" statement in the loop is satisfied the loop ends in Django Templates
I have 2 Django models Review and Item that I am working with. I want to see if the user has already reviewed the item. If yes he sees the review score. if no he sees the button to review the item I have the below Review model class Review (models.Model): review_from = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_from') review_for = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_for') item = models.ForeignKey(OrderItem, related_name='items') Defining the variables in the view context (pseudocode) admin = User.objects.get(username="admin") admins_reviews = Review.objects.filter(review_from__username = "admin") Below is my template {% for item in buyers_items %} {% for review in buyers_review%} {% if review.item.id == item.id %} <button class="text-success">Your rating<br/><b>{{review.ratings}}/10</b></button> {% else %} <a href="{% url ... %}"> <button>Leave Review</button> </a> % endif %} {% endfor %} {% endfor %} If I do this I get a below error How can I overcome this problem. -
How to serve static if exist, otherwise pass to wsgi application?
I am converting a static website to Django with Apache mod_wsgi. How can I have Django serve .html files if they don't already exist in a static files location. For example, user requests www.mysite.com/test.html. If test.html exists in my static directory then serve it using Apache. If the file does not exist then pass the request to Django. I know of uWSGI and it has a parameter --check-static which will do what I'm asking (https://uwsgi-docs.readthedocs.io/en/latest/StaticFiles.html). However, it's not practical for me to use uWSGI for this application. Does anyone know if this is possible using mod_wsgi and how? -
Load JSON file in alphabetical order - Django
With this method: def postcodes(request): with open('core/stores.json') as f: data = json.load(f) return JsonResponse(data, safe=False) I load a local json file into this url: urlpatterns = [ path('stores/', views.postcodes, name='postcodes'), ] It renders flawlessly, now, my json file looks like this: [ { "name": "St_Albans", "postcode": "AL1 2RJ" }, { "name": "Hatfield", "postcode": "AL9 5JP" }, { "name": "Worthing", "postcode": "BN14 9GB" }, And so on... As You can see, this is in alphabetical order, if You take into account the postcodes. What I need, is to read this file, and render it in alphabetical order, but not as it is (by postcode), but by name. I don't think I can use the builtin Django loops or tags for this, since they work with models or stored data mostly. But I'm not completely sure. What could be a quicker approach to this, instead of saving everything into a database? I took a look into serializers but that's for django-rest-framework I'm using plain requests here. Any ideas? I'm not using any template right now, it is just rendered on browser as it is. -
The view core.views.postcodes didn't return an HttpResponse object. It returned None instead
I want to render a local json file I'm loading from a view in Django. I have this function on my views.py file: def postcodes(request): data = open('core/stores.json').read() jsonData = json.loads(data) On my urls.py: urlpatterns = [ path('stores/', views.postcodes, name='postcodes'), ] It throws me this error: Internal Server Error: /stores/ Traceback (most recent call last): File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 139, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view core.views.postcodes didn't return an HttpResponse object. It returned None instead. I think this comes from the fact that I'm using request as a parameter on my postcodes function. Any ideas on how can I load this json file on my view? I'm using Django 1.11 -
Passing context variable in generic.UpdateView
I have a template begining with: {% extends load_template %} the load_template takes values from this condition in my view if user == 'guest': load_template = 'damage/menus/menu.html' else: load_template = 'damage/menus/sidebarmenu.html' I use a generic.UpdateView for update (which returns an error , because load_template variable hasn't got a value) How can I pass value to this variable in this UpdateView? -
Django Group Permission Created view duplicates query
Using simple CreateView: class GroupCreateView(CreateView): model = Group fields = '__all__' template_name = 'group/add.html' success_url = reverse_lazy('group_list') It Creates duplicate query. All getting from permission. How to reduce query -
Django dropdown menu links
i currently have a dropdown menu in my code and i would like the bit that the user hovers over to be clickable as well, but currently the href is being used by javascript. This is for the archive drop-down menu and the calendar menu. Any help would be much appreciated and i am very new so pls dont hurt me HTML: {%load static%} <html> <head> <title>Athletics Program</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> </head> <body> <ul> <li><a href="{% url 'index' %}">Home</a></li> <li class="dropdown"> <a href="javascript:void(0)" class="dropbtn">Archive</a> <div class="dropdown-content"> <a href="{% url 'ArchiveHome' %}">Records</a> <li class="dropdown" a href="{% url 'ArchiveHome' %}"> <a href="javascript:void(0)" class="dropbtn">Calendar</a> <div class="dropdown-content"> <a href="">January</a> <a href="">Feburary</a> <a href="">March</a> <a href="">April</a> <a href="">May</a> <a href="">June</a> <a href="">July</a> <a href="">August</a> <a href="">September</a> <a href="">October</a> <a href="">November</a> <a href="">December</a> </div> </li> <div class="Login"> <li><a href="">Login</a></li> </div> </ul> <div class="twitter"> <a class="twitter-timeline" data-width="400" data-height="626" data- theme="dark" href="https://twitter.com/KWS_Sport?ref_src=twsrc%5Etfw">Tweets by KWS_Sport</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </div> <img src="{% static 'Logo.jpg' %}"" alt="Kingswood Logo" width="200" height="200" border= 1 class="imageOverBackground"> </body> CSS: body{ margin: 0px; background-image: url("background.png"); } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333333; width: 966px; } li { float: left; } li a, .dropbtn { display: inline-block; β¦ -
with which tutorial to create a crowdfunding site like Kickstater step by step in django
I would like to launch a crowdfunding site for a small community like kikstarter on django, how can I do it? I have an intermediate level in web programming and python -
FileNotFoundError at /stores/ - Loading local json file into a Django view
I have this function: def postcodes(request): data = open('stores.json').read() jsonData = json.dumps(data) This is my directory structure: βββ core β βββ admin.py β βββ apps.py β βββ forms.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ stores.json β βββ templates β β βββ core β β βββ github.html β β βββ home.html β β βββ oxford.html β β βββ stores.html β βββ tests.py β βββ urls.py β βββ views.py The function is on my views.py file, and the file stores.json is on the very same directory. This is the traceback: Internal Server Error: /stores/ Traceback (most recent call last): File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kristian/tails/restful-apis-example/core/views.py", line 83, in postcodes data = open('stores.json').read() #opens the json file and saves the raw contents FileNotFoundError: [Errno 2] No such file or directory: 'stores.json' [25/Nov/2018 20:07:31] "GET /stores/ HTTP/1.1" 500 75613 I was thinking about declaring something like the BASE_DIR for static or templates, but I'm not sure about that approach. I've never loaded a local json file into Django, so, β¦ -
Django - How to dynamically restrict category of blog post?
I'm working on a blog project. I want to set primary and secondary categories for the posts. For example, primary category: Music, Movie, Computer and secondary categories for each primary category like: Music - Dance, Rock, Country / Movie - Script, Teaser, Review / Computer - Hardware, Software / And when I create a new post I want to restrict secondary category choices according to the primary category I chose. (to be precise, in the post creation form, first, I want both primary and secondary categories to be shown in dropdown menus, and second, after I choose a primary category I want only the secondary category choices which belong to the primary category I chose to be shown in the dropdown menu for secondary category.) Currently my models.py: class PrimaryCategory(models.Model): title = models.CharField('Primary Category', max_length=50) class SecondaryCategory(models.Model): title = models.CharField('Secondary Category', max_length=50) primary = models.ForeignKey(PrimaryCategory,on_delete=models.CASCADE) class Post(models.Model): title = models.CharField(max_length=256) content = models.TextField() create_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) primary_category = models.ForeignKey(PrimaryCategory, on_delete=models.CASCADE, null=True) secondary_category = models.ForeignKey(SecondaryCategory, on_delete=models.CASCADE, null=True) and I searched and I can maybe use ForeignKey.limit_choices_to in my ModelForms, but I'm stuck here. Could anybody kindly help writing my forms.py? currently I only have forms.py like: β¦ -
python says apple is not equal to apple
I have an odd situation in my django code, where python refuses to accept that two strings are equal: def depticon(depta): print(f'depta is {depta}') print(f'Testing |{depta}| against |Ear, Nose, Throat|') if depta=="Ear, Nose, Throat": icon = "ear.png" print("Matched ENT") else: print("No match") icon = "health-sign.png" print(f'Icon is {icon}') return icon This is how it is called. Here, clinics is a queryset: specialties = [] specialtytext = [] specialtyicon = [] for clinic in clinics: if clinic.doctorid.dept not in specialties: dept = clinic.doctorid.department specialties.append(dept) specialtytext.append(depttext(dept)) specialtyicon.append(depticon(dept)) See the output: depta is Ear, Nose, Throat Testing |Ear, Nose, Throat| against |Ear, Nose, Throat| No match Icon is health-sign.png I put the | character around the string to check whether there are any special characters in the string. -
rawsql equivalent django queryset
I would like to write django queryset which is equivalent of below query with one hit in db. Right now I am using manager.raw() to execute. with annotate, I can generate the inner query. But I can't use that in the filter condition (when i checked queryset query, it looks like ex1). select * from table1 where (company_id, year) in ( select company_id, max(year) year from table1 where company_id=3 and total_employees is not null group by company_id); Ex1: 'SELECT table1.company_id, table1.total_employees FROM table1 WHERE table1.id = (SELECT U0.company_id AS Col1, MAX(U0.year) AS year FROM table1 U0 WHERE NOT (U0.total_employees IS NULL) GROUP BY U0.company_id ORDER BY NULL)' I appreciate your response. -
Using django with sqlite on aws lambda
I am trying to deploy my django app on aws lambda using zappa. However, when I try to login to the app I get attempt to write a readonly database. My understanding is that this is because sqlite is an embedded database and you can't use embedded databases on lambda because they require write-access which is not possible on lambda and just generally not a good idea to try and persist data on lambda. Is this correct? Is my only option to thus switch to using postgres or mysql or another server database? -
django throws 'function' object has no attribute 'objects', while picking data from models
I'm actually playing with manual signin forms and while I was trying to query data from database it threw me this error..... views.py ----section def signin(request): username = 'not logged in' notify = "" if request.method == "POST": form = signinForm(request.POST) if form.is_valid(): username = form.cleaned_data['user_name'] password = form.cleaned_data['password'] signup_data = signup.objects.all() # focus here for data in signup_data: name = data.user_name passw = data.password if name == username and passw == password: post = form.save(commit=False) post.save() request.session['user_name'] = username return redirect('/home') notify = "Incorrect User name or Password" return redirect("/home/signin") else: form = signupForm() signins=blog.objects.all() number=len(signins) return render_to_response('blogger/signin.html', {'form':form, 'signins': signins, 'number':number, 'notify': notify}, RequestContext(request)) -
What is the reason that celery should not run as root?
I see recommendations in the shell that I shouldn't run celery as root, that it is "absolutely not recommended!". Can someone explain this? -
Can't get XMLHttpRequest response with async:true
In Rich Text Editor I want to upload local images into server media folder. For this, I made a XMLHttpRequest. The request with a downloadable file is sent to the server, then a function on the server saves the file and returns its url. The returned url should be displayed on the Text Editor dialog box. At first I tried this code and everything worked fine with async:false parameter. In the dialog box appeared relative url of file and I could load it on the view page. The picture below shows successful image uplod. file_picker_callback: function(cb, value, meta) { if (meta.filetype == 'file') { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'MIME_type'); input.onchange = function () { var file = this.files[0]; var reader = new FileReader(); // FormData var fd = new FormData(); var files = file; fd.append("file",files); var location = ""; // AJAX jQuery.ajax({ url: "/fileupload/file/", type: "POST", data: fd, dataType: 'json', contentType: false, processData: false, async: false, success: function(response){ location = response.fileurl; } }); reader.onload = function(){ //call the callback and populate the Title field with the file name cb(location, { download : files.name }); }; reader.readAsDataURL(files); }; input.click(); } }, But then, in the console I get β¦