Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to write join query in django?
I have googled several hours but couldn't understand how to write sql join(raw or ORM) related queries. Below is my model with two tables sandBox1 and licenseType where they will have common item "email" on which join will be performed class sandBox1(models.Model): email = models.EmailField(unique=True) name = models.CharField(max_length=200) website = models.TextField(validators=[URLValidator()]) comment = models.TextField(default='-') gender = models.CharField(max_length=6) def __str__(self): return self.email class licenseType(models.Model): #1=other, 2=two-wheeler 4=four-wheeler licenseId = models.IntegerField() sandboxId = models.ForeignKey(sandBox1) template file : index.html <html><form id="form1" method="post" action="{% url "sandbox" %}"> {% csrf_token %} Name: <input type="text" name="name" > <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website" > <span class="error"></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <hr>Check the license type you have:-<br> <input type="checkbox" name="license[]" value=2 > 2 wheeler<br> <input type="checkbox" name="license[]" value=4 > 4 wheeler<br> <input type="checkbox" name="license[]" value=1 > Other <br> <br> <input type="submit" name="submit" value="Submit"> </form> <div> {% for obj in sandBoxObj %} <p> {{ obj.name }}<br> {{ obj.email }}<br> {{ obj.website }}<br> {{ obj.gender }}<br> {{ obj.comment }}<br> {% endfor %} </div> </html> here is a view file that needs correction. I want to show the result of this sql query: select … -
Django/Python TypeError unorderable types: float() < HighscoreEasy()
I copied my working Django-App to a new Project and now I have an issue I can not resolve. I will check if the new playtime is lower than the old one. if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first(): Environment: Request Method: POST Request URL: https://www.maik-kusmat.de/kopfrechnen/results/ Django Version: 1.11.5 Python Version: 3.5.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'home', 'contact', 'kopfrechnen', 'braces'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware'] Traceback: File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/pi/Dev/mkenergy/src/kopfrechnen/views.py" in kopfrechnen_results 168. if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first(): Exception Type: TypeError at /kopfrechnen/results/ Exception Value: unorderable types: float() < HighscoreEasy() Here is the snippet from my Code with the issue: def kopfrechnen_results(request): end_time = time.time() if 'start_time' in request.session: start_time = request.session['start_time'] else: template = loader.get_template('kopfrechnen/kopfrechnen.html') context = {'error': 'Starte ein neues Spiel immer von hier.'} return HttpResponse(template.render(context, request)) if 'tasks' in request.session: tasks = request.session['tasks'] else: template = loader.get_template('kopfrechnen/kopfrechnen.html') context = {'error': 'Starte ein neues Spiel immer von hier.'} return HttpResponse(template.render(context, request)) if 'difficulty' in request.session: difficulty = request.session['difficulty'] … -
Django Project- CSS
I have a base.html file in my Django project in a the templates directory that is in the main project folder. I want my base.html to locate my file, so where should I be putting it in the project? I'm new to Django. -
Include jinja2 from django template
How can I include Jinja2 template from Django template? I'm using Django 1.11.5 and django-jinja 2.4.0. -
Aldryn News & Blog Instance Namespace
I have a question regarding Django CMS, in particular the "Aldryn News and Blog" apphook. I refer to this article on creating multiple "News and Blog" apphook. http://aldryn-newsblog.readthedocs.io/en/latest/how-to/apphook_configurations.html Everything works fine in development and I see a field "Instance Namespace". But in production, the "Instance Namespace" field is gone. Kindly refer to picture below. Any idea why? Thanks very much. Picture of Instance Namespace Screen -
How to sum three columns using django ORM
I'd like to execute such query using djagno models: SELECT id, ( first+second+third ) FROM testTable Without grouping. Was trying to find the solution using google but unsuccessfully. Thanks in advance, -
Wrapping the code
I have a friend who wants to pull NHL data from an API in such a way he could treat it directly in Excel. In fact, he has got a tremendous experience with Excel and wants to make predictions with it. I would like to create a little web application so that he could make his request easily, directly from an interface. https://www.quora.com/Is-there-any-JSON-API-available-for-getting-NHL-information-rosters-lineups-statistics-etc Questions: If I pull NHL data inside a .xlsx file, will he be able to process information in Excel from that file? If so, if I update the file twice a day and do its calculations in the same file, but on a different page, will the update delete its calculations? Assume I finished this web application, and the API used is no longer supported. I will need to change of API and refactor the entire code so that it will work with the new one. Is there a sort of wrapper I could use to avoid that kind of problem? A type of problem I could encounter is to have to reformat the 'pulling file' so that it could work with my application. -
How Should Django´Views be In this example?
https://www.w3schools.com/bootstrap/trybs_theme_company_full.htm In this example,the homepage view should return the entire page? And the buttons in the navbar just scrolls the page to a certain area of the page. How should I do it with Django? -
Django: disable initial system checks in production?
I've scoured the documentation and am looking for a Django setting that disables system checks (not just silences them) in production. I have a project with 20,000+ models which are autogenerated to create RESTful endpoints. These system checks take quite some time: https://docs.djangoproject.com/en/1.11/ref/checks/#models Having the systems check in development is necessary, even though it causes manage.py 20-30 minutes to fire up. However, any time I publish a new version to production, the first HTTP request to a production node takes 20-30 minutes to respond as well! I'd obviously like to avoid this, because after the initial request, the site is lightning fast. I've looked around for a setting like DISABLED_SYSTEM_CHECKS but have only come across SILENCED_SYSTEM_CHECKS (see here), but that just seems to silence the output rather than not running the checks that take the time. Does such an animal exist? I'm running mod_wsgi in production. I've seen requires_system_checks for individual commands, but am looking for a project-wide solution. Thanks very much. -
How do I prevent Anonymous Users from accessing certain parts of my website?
I want to prevent a user from seeing certain links on my navigation bar if the user is not logged in. I am using the if statement in my template to do this. When I am logged in it shows the correct set of links but when I signed out it does not. It should show the ul with the sign in links. WHat am I doing wrong? This is my code : <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> {% block head %} {% endblock %} </head> <body> <style> ul, li { margin: 0px 14px; } </style> <nav class = "navbar fixed-top navbar-light bg-light justify-content-between flex-nowrap flex-row"> <div class = " container"> <a class = "navbar-brand float-left" href = "{% url 'Identities:nest'%}">nest</a> {% if user.is_authenticated %} <ul class = "nav navbar-nav flex-row float-left "> <li class = "nav-item "><a class = "nav-link" href = "{% url 'Identities:logout'%}">Sign Out</a></li> <li class = "nav-item"><a class = "nav-link" href = "{% url 'Identities:view_profile' %}">view Identity </a></li> <li class = "nav-item"><a class = "nav-link" href = "{% url 'Identities:edit_profile' %}">edit Identity </a></li> </ul> {% else %} <ul class = "nav navbar-nav flex-row float-left "> <li class = "nav-item "><a class="nav-link" href = "{% … -
Nested routes with APIViews in Django Rest Framework
I'm writing my school project, building Django Rest API. And i have next entities: Profiles, Albums, Images, Comments, Likes. What i want is to make resources accessible in this way: api/v1/profiles/1/albums --> to get all the albums from profile with id 1 On examples i found, there is ViewSet used, instead APIView which i wanted to use ( I'm really newbie and i don't even know can i use ViewSet for CRUID operations ). I tried to implement next: https://blog.apptension.com/2017/09/13/simple-nested-api-using-django-rest-framework/ Routing API Views in Django Rest Framework? http://chibisov.github.io/drf-extensions/docs/#routers and many others, but i can't get it worked... If there is some detailed tutorial, please reference it, i really need to be fast. Thanks everybody! -
Allow different views for different types of users in django rest class based views
How do I write the following views using class based view? @api_view(['GET', 'POST']) def hotel_list(request): # List all hotel or add new . if request.method == 'GET': if request.user.is_authenticated: # Allow GET request for all authenticated users hotels = models.Hotel.objects.all() serializer = serializers.HotelSerializer(hotels, many=True) return Response(serializer.data) return Response({"message": "not authorized"}, status=status.HTTP_401_UNAUTHORIZED) elif request.method == 'POST': if request.user.is_superuser: # Allow POST method for super users only serializer = serializers.HotelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"message": "not authorized"}, status=status.HTTP_401_UNAUTHORIZED) I want to allow different permissions for different groups of user. -
How to filter out queryset based on model method?
I have this query et: plist = UserProfile.objects.filter(q).order_by('-created_at') The model is: class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=30, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) def online(self): if self.last_seen(): now = datetime.datetime.now() if now > self.last_seen() + datetime.timedelta( seconds=settings.USER_ONLINE_TIMEOUT): return False else: return True What I want to achieve is to filter out further plist to contain only online users. I tried different tricks, like: for p in plist: if p.online: print 'profile onlnine \n', p.id online_plist.append(p) plist = online_plist But it does not work. So appreciate your hints. -
Django JOIN on nested model Foreign key with look up field
I'm using 2 models in Django Rest Framework. class Questions(models.Model): question = models.TextField() answer = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) categories = models.ForeignKey(Categories, related_name="cat_questions", on_delete=models.CASCADE) class QuestionnaireResult(models.Model): patient_info = models.ForeignKey(PatientInfo, related_name="+", on_delete=models.CASCADE) questions = models.ForeignKey(Questions, related_name="result_questions", on_delete=models.CASCADE) answer_given = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) having serializers for both: class QuestionnaireResultSerailizer(serializers.ModelSerializer): class Meta: model = QuestionnaireResult fields = '__all__' class QuestionsSerializer(serializers.ModelSerializer): result_questions = QuestionnaireResultSerailizer(many=True) class Meta: model = Questions fields ='__all__' Using URL - http://localhost:9000/api/questions/1, It gives result based on question_id = 1 and result_questions contains only those nested records which have questions id == 1. That is correct. { "id": 1, "result_questions": [ { "id": 1, "answer_given": "no", "timestamp": "2017-10-01T12:28:19.770454Z", "patient_info": 1, "questions": 1 }, { "id": 4, "answer_given": "no", "timestamp": "2017-10-01T13:13:19.658930Z", "patient_info": 2, "questions": 1 } ], "question": "digestive ques 1", "answer": "yes", "timestamp": "2017-09-30T17:04:59.143857Z", "categories": 1 } But above nested json (result_questions) returns all patient_info which has questions id == 1 but I want to add one more filter(patient_info) on it. I want only those patient_info which I want to retrieve by passing as look up field. What I want is that. Assume, I use this url http://localhost:9000/api/questions/1?patient_info=1 It returns response having question_id == 1 and patient_info ==1. Therefore, response … -
Django's choices field don't match
I have 2 models that have the same field using a choices tuple, yet when I compare them, they aren't equal. TEAM_CHOICES = ( ('ANA', 'Anaheim'), ('ARI', 'Arizona'), ) class GameData(models.Model): player_name = models.CharField(max_length=50) team = models.CharField(max_length=3, choices=TEAM_CHOICES) goals_scored = models.SmallIntegerField() class GameResult(models.Model): date = models.DateField('game date') away_team = models.CharField(max_length=3, choices=TEAM_CHOICES) home_team = models.CharField(max_length=3, choices=TEAM_CHOICES) Yet, when I go into my console and do: >> GameData.objects.first().team u'ARI' >> GameResult.objects.first().away_team u'Arizona' I found out via debugging that I forgot to use the acronyms for team names when importing the data into my database. But shouldn't the max_length attribute on the field have prevented something like this from happening in the first place? -
Last N posts per category SQL to ORM
I'm starting my first Django blog app [after completing the Django official tutorial and Django Girls tutorial]. I'm having some trouble wrapping my head around Django ORM. I have this SQL query that works, but I feel that it is quite inefficient and I rather learn the correct way before going forward. Post.objects.raw(('SELECT * FROM (SELECT id, category, body, slug, author, title, published, row_number() OVER (PARTITION BY catagory) as rownum FROM post) tmp WHERE rownum < 5')) Basically I want to display last 5 rows for each post category. The code above is already working, The problem is that when I loop trough each post in my templates it runs additional queries per each post when Post's get_absolute_url method is being called. I fixed this using Django's {% url %} tag but still 7 additional queries are run and I want to limit this to 2-3 max. I Have a model like this : class Post(models.Model): title = models.CharField(max_length=250) category = models.CharField(max_length=30, choices=CATEGORY_CHOICES) tags = TaggableManager() slug = models.SlugField(max_length=250, unique_for_date = 'published') author = models.CharField(max_length=50) body = HTMLField('body') published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-published',) db_table = 'post' def … -
Django Object with lot of data
I'm a script-noobie and have a question about Django. I have an access point that feeds me data about the MAC addresses seen/connected and timestamps. I've setup a web hook and I can process the data in Django so that's all fine. Now I'm wondering how I could save all this data. As I get the info almost every minute, I would like to save this. For example: Mac Address Connected (true/false) Timestamp The Mac Address would be a one-time thing and under the Mac Address, there would be a lot of row with the 'child' data. How can I implement this? Thanks! -
unable to render a file upload template
I have a python django based server that a client can access through a javascript plugin. The plugin allows the server to collect user's login information of another platform and connect to that platform on his behalf. To access our server, the plugin initiate the following instruction: chrome.tabs.create({ url: targetURL + '?random_code=' + username + '&token=' + token }) where target url contain our IP and two functions in defined in views.py (function 'A' and 'B') targetURL =IP+'/A//B/'. When receiving the request, the server collects the login information through A and returns a response containing the username. Function B then redirects the user to another view (C) rendering some processing results. I would like to insert a file upload page where users will upload a txt file that the server will then process before function B is executed. I have tried to link view A to a template containing the file upload html code however at every execution the file upload page doesn't display and users directly get the result of C. I also tried to remove B (from the plugin as well) and directly return C from A if request.FILES is defined or return the file upload html page … -
NOT NULL constraint failed: app_business.user_id
I am rendering a form and when I am submitting that form getting this error IntegrityError at /business/ NOT NULL constraint failed: app_business.user_id models.py class business(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=400) rate_it = models.BooleanField(default=False) availibility = models.BooleanField(default=True) def __str__(self): return self.name forms.py class businessform(forms.ModelForm): class Meta: model = business fields = ['name', 'rate_it', 'availibility'] views.py def formview(request): if request.method == 'POST': form = businessform(request.POST) if form.is_valid(): form.save() return HttpResponse('saved') else: form = businessform return render(request, 'business.html', {'form':form}) I don't know why this error is coming. -
Django model missing inherited fields from base class
I have made some models in my Django app to describe different types of polls that exist in my application. from django.db import models from api.models.helpers import JSONSerializableModel from api.models.speaker import Speaker from api.models.auth import Attendee from api.models.event import Event class BasePoll(JSONSerializableModel, models.Model): text = models.CharField('текст опроса', max_length=300, blank=False) class Meta: abstract = True class MultipleChoicePoll(JSONSerializableModel, models.Model): @property def results(self): results = multiplechoicepollresponse_set.all().annotate(Count('multiplechoicepollresponse')) return average_rating class RatingPoll(BasePoll): @property def average(self): average_rating = ratingpollresponse_set.all().aggregate(Avg('rating')) print(average_rating) return average_rating class OpenQuestionPoll(BasePoll): pass I've made the migration and all seemed fine, but now when I try to use the interactive shell: In [6]: poll = MultipleChoicePoll.objects.all()[0] In [7]: poll.text = 'Some poll text' In [8]: poll.save() In [9]: poll = MultipleChoicePoll.objects.all()[0] In [10]: poll.text --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-10-28f6dbcd48ba> in <module>() ----> 1 poll.text AttributeError: 'MultipleChoicePoll' object has no attribute 'text' poll seems to be missing all the fields I have created for it. Is it because I have inheritted those fields? -
Return file using HttpResponse
Good afternoon. I need to download data from database in excel format. Below, my code and its working correct when i'm trying to download file through firefox, but using chrome this view returning archive with some openpyxl files. Openpyxl - this library i'm using to filling excel table from database in excel_download() function. Will you please help me to solve it? def excel_download_view(request, **kwargs): if 'sorting_argument' in kwargs: queryset = Lot.objects.filter( Q(bank__slug__iexact=kwargs['sorting_argument']) | Q(auction_date__iexact=kwargs['sorting_argument']) | Q(which_time_auction__iexact=kwargs['sorting_argument']) | Q(fgvfo_number__iexact=kwargs['sorting_argument']) | Q(prozorro_number__iexact=kwargs['sorting_argument']) | Q(decision_number__iexact=kwargs['sorting_argument']) ) else: queryset = Lot.objects.all() excel_download(queryset) data = None with open('media/excel/lots.xlsx', 'rb') as f: data = f.read() return HttpResponse(data, content_type='application/vnd.ms-excel') -
is there a way to return a response first but still does something else after the response? django
I want to return a response in django view first then does something after the response. Let's say I have something like this as example..... class Res(View): def post(self, request): data = request.POST new_obj = Model.objects.create(name=data.['name']) # what is below does not have to be done RIGHT AWAY, can be done after a response is made another_obj = Another() another_obj.name = new_obj.name another_obj.field = new_obj.field another_obj.save() # some other looping and a few other new models to save return JsonResponse({'status': True}) So I am wondering if there is a chance to return the response first? What's above is an example of what I mean. I am not sure if this can be done in django, if possible, can someone let me know who this can be done Thanks in advance. -
Get details of users those who rate the business
I have three columns named as business name , rate it, .com availability in a table. I want details of those users who hit the rate it button. models.py file class VNN: def set_params(self, W_x_h, W_h_h, W_h_y, b_h, b_y, h_prev, ch_2_ix, ix_2_ch): self.W_x_h = W_x_h self.W_h_h = W_h_h self.W_h_y = W_h_y self.b_h = b_h self.b_y = b_y self.h = h_prev self.ch_2_ix = ch_2_ix self.ix_2_ch = ix_2_ch self.vocab_size = len(ch_2_ix) self.words=[] def sample(self, seed_ix, n, _temperature=1): """ sample a sequence of integers from the model h is memory state, seed_ix is seed letter for first time step """ h = self.h x = np.zeros((self.vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in range(n): h = np.tanh(np.dot(self.W_x_h, x) + np.dot(self.W_h_h, h) + self.b_h) y = np.dot(self.W_h_y, h) + self.b_y p = np.exp(y / _temperature) / np.sum(np.exp(y / _temperature)) ix = np.random.choice(range(self.vocab_size), p=p.ravel()) x = np.zeros((self.vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes def unique_words(self, seedword, seed_ix, n, _temperature=1): out_words = [] ch_batch_size = 100 while len(out_words) < n: sample_ix = self.sample(seed_ix, ch_batch_size, _temperature) txt = ''.join(self.ix_2_ch[ix] for ix in sample_ix) raw_words = txt.split('\n') for word in raw_words: if not (word in self.words) and not (word in out_words): out_words.append(seedword+word) return out_words … -
Why does Django give me an invalid filter error when I try to apply two filters?
I want to make two changes to the text that is displayed in my Django template. First, I want to strip the text of any HTML. The following code works for me: {{ article.abstract|striptags }} Second, I want to replace all instances of \n with <br /> I tried: {{ article.abstract|striptags|replace('\n', '<br />') }} That gave me an invalid filter error. I even tried: {{ article.abstract|striptags|replace('\n', '') }} That did not work either. Are there any suggestions? Thank you. -
NoReverseMatch at /accounts/detail
I got an error,NoReverseMatch at /accounts/detail Reverse for 'upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'accounts/upload/(?P\d+)/$'] . I wrote in detail.html like <body> <a href="{% url 'accounts:upload' %}"><img src="{% static 'accounts/Send.jpg' %}" alt="SEND"></a> </body> My ideal system is when I click images, it sends to upload method(maybe I should say photo.html). I wrote in views.py like def detail(request): return render(request, 'registration/accounts/detail.html') def upload(request, p_id): form = UserImageForm(request.POST or None) d = { 'p_id': p_id, 'form':form, } return render(request, 'registration/accounts/photo.html', d) in urls.py urlpatterns = [ url(r'^detail$', views.detail,name='detail'), url(r'^photo/$', views.photo, name='photo'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), ] When I access http://localhost:8000/accounts/detail, these error happens.How can I fix this?What should I write it?