Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrations failing with fresh database
wondering if anyone else is experiencing frustrating behavior with Django migrations. I have looked at several related posts on SO but have not found anything addressing this specifically. This keeps happening to me, and it MUST be a common scenario, so what am I missing? My scenario: List item I've built a Django application, iterating using sqlite on my local machine I now want to deploy to a production Postgresql db (AWS or elsewhere) I set up my new database, add it to my settings, and run python manage.py makemigrations I get a SQL error telling me that one of my model tables doesn't exist. Duh! That's why I'm running makemigrations. I end up having to hand-make tables, do weird things like python manage.py migrate <app_name> --fake which creates further issues with packages like simple_history I'm sure there must be an obvious answer -- what should I do to set up database schema on a brand new, clean database? -
Django ORM query, left join with where
I need to translate one query. Models class Publication_dependecy(models.Model): def __str__(self): return(str(self.id)) class Publication(models.Model): def __str__(self): return(self.name) name = models.TextField() class Publication_relationship(models.Model): def __str__(self): return(self.publication_from + '#' + self,publication + '#' + self.publication_dependecy_id) from_publication = models.ForeignKey(Publication, related_name='from_publication', on_delete=models.CASCADE) to_publication = models.ForeignKey(Publication, related_name='to_publication', on_delete=models.CASCADE) publication_dependecy = models.ForeignKey(Publication_dependecy, on_delete=models.CASCADE) SQL query: select Publication.id from Publication left join Publication_relationship on Publication.id = Publication_relationship where publication_dependecy is NULL or Publication_dependecy = 1 I need to retrive all publications that are not in Publication_relationship or his publication_dependecy is 1. In other words publication_dependency is 1 or NULL -
How to change Django paths/project/app
After going through How to change the name of a Django app? I am still having issues with my django setup The last time my django project 'ran' my setup was like this /resume ~/repos/resume /resume /apps /static /templates __init__.py settings.py urls.py wsgi.py ... manage.py requirements.txt ... The project name was resume and was in /repos/resume I changed the project name to portfolio and the directory to /repos/portfolio so that it becomes /portfolio ~/repos/portfolio /resume /apps /static /templates __init__.py settings.py urls.py wsgi.py ... manage.py requirements.txt ... I renamed them using pycharm's rename feature. I believe the references and such are updated correctly. Now when I am running python manage.py migrate (portfolio) nono@nono:~/repos/portfolio$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/nono/.virtualenvs/portfolio/src/django/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/nono/.virtualenvs/portfolio/src/django/django/core/management/__init__.py", line 300, in execute settings.INSTALLED_APPS File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/nono/.virtualenvs/portfolio/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Sending uploaded file to another pc over network
i am new to Django and just discover how to select and upload images using "https://github.com/axelpale/minimal-django-file-upload-example". now i want to again select a image from a uploaded files and send that select image to another computer over network. i want all this to be done in python and Django. search a lot but did not find any thing useful -
Django ImageKits "ImageSpecField" with values_list()
Im using Django ImageKit to generate thumbnails. I would like to get a "preview" Image from the existing ImageField. ImageKit provides a ImageSpecField model field but I have trouble using it in combination with values_list(). Since the ImageSpecField isn't a real database field ("ImageSpecFields, on the other hand, are virtual—they add no fields to your database and don't require a database. "), it can't be called through values_list(). Anybody an idea how to get the value of the ImageSpecField into the values_list? How does the ImageSpecFields exactly work? Is an Image generated each time the model gets called? I'm curios for efficiency reasons. What I tried? In the current state I would add a URLField into the model and write a function to save the output of self.thumbnail.url into the URLField but this doesn't seem very practical... -
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?