Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Basic non-model Sitemap for Django
Django is really frustrating me now - it seems to lack the most basic of SEO support for a website. This is the last roll of the dice before I move my site across to Wordpress, how on earth do we create a static sitemap for our urls? I understand the post sitemap stuff, all works fine. That's great. But how do we, say, provide the root of our site in the sitemap? I'd rather just generate the sitemap myself, by hand, than the frustrating I have had with Django on this. Now, say I want my home url, which is at root: '/' to appear on my sitemap. How is this achieved? class HomeSitemap(Sitemap): changefreq = 'always' priority = 0.9 location = '/' lastmod = datetime.date.today() Clearly I'm missing items, but why on earth can't we just define static URLs? I can't believe how basic this is and it doesn't seem to be covered? What on earth is going on, and bloody well fix it Django core team. It's ridiculous. I've gone from loving this framework to detesting it fairly sharpish. -
How to define a URL in django that directly points to a static file?
I have a urls.py file that looks like this: from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView from django.contrib.staticfiles.templatetags.staticfiles import static urlpatterns = [ url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want to make a URL (say r'^test/' ) such that when I enter that URL, it directly links to a static file (say 'static/test.html'). -
why is Django giving me a 404 error
I am currently trying to complete the Django 2.0 tutorial Poll application. I am using Django version 2.0.7 and Python 3.7.0. I have set up a virtual environment for this project. I am very new to Django so apologies if my terminology is incorrect. Basically, I cant get part 1 to work. I have tried numerous times to run it and I cant seem to figure out why it wont work. Before I create the Polls app the site runs correctly and I get the rocket ship, however after I create the app, update polls/views.py, create the polls/urls.py file and update the mysite/urls.py, I get the following error: Page not found (404) Request method GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. I thought my code was incorrect, so I copied and pasted the code from the website directly and tried to run it. It still wont work. Below is the code I am trying and the directory layout. Any help would be greatly appreciated. I'm sure I am just missing something simple. Thank you. mysite/urls.py from django.contrib import admin … -
django modules works locally but not over server
I'm using python 3.6 and i have pip installed the requests module.in django i have imported the requests into my view and it is working completely fine locally. but when i deploy my changes to my server and want to run it from my client it says ModuleNotFoundError at / No module named 'requests' for tests reason i run python server locally on my server and even in this case it worked fine on server browser. but still when i want to open page from a local network computer it says no requests module. i uninstalled requests and installed it again, requests module is available when i pip list it. i'm really confused and it does not let me deploy my work on server which is critical for me. -
django admin export to pdf
I want to export admin django to pdf (there is the normally export to csv I already have). What is the correct way to do this? There is some way in Python/Django: convert between CSV file to PDF or create a pdf file from this admin? -
Get referenced object multipla layers django
I'm working with Django, I have trouble fetching objects that are chained referenced. Here we are my Models class Environment(models.Model): name = models.CharField(max_length=200, unique=True) class Element(models.Model): environment = models.ForeignKey(Environment, on_delete=models.CASCADE,related_name='GroupPre') class AlarmActive(models.Model): element = models.ForeignKey(Element, on_delete=models.CASCADE,related_name='AlarmActivePre') My task is straightforward, I have to fetch all environments that have an AlarmActive. How can I achieve it? Thank you! -
OperationalError occurred while adding new fields in Django
I have a web app I've been managing for months, and I attempted to make some updates on my app. I added new fields to the existing class, but django raised an error. These are what I've done. 1. Added a new field to an existing model. class ExistingModel(models.Model): # Existing Fields new_field = models.IntegerField() 2. Attempted to make migration $ python manage.py makemigrations However, it raised django.db.utils.OperationalError: no such column during this process. I added django.contrib.sites to INSTALLED_APPS in settings.py. My django version is 2.0.3. How can I add new fields to the existing model? -
Django: Combine ListView with UpdateView
I created a ListView with a slug that filters all attendees with a certain order_reference. I want to create a second ListView where it is possible to update all these attendees (fields: first_name, last_name, email) at once. Basically, a form with a Save All button to update the database entries. I started to try it with UpdateView, but failed with that as I have several entries in my queryset. Anyone did that before and can lead me the right way to achieve that? views.py: class AssignAttendee(ListView): allow_empty = False template_name = 'attendees/assign_attendee.html' def get_queryset(self): return Attendee.objects.filter( order__order_reference=self.kwargs['order_reference'], order__access_key=self.kwargs['access_key'], ) -
Error while running gunicorn in django
I am getting error while running gunicorn. Started gunicorn daemon. Starting gunicorn daemon... [2018-07-15 07:39:16 +0000] [11359] [INFO] Starting gunicorn 19.9.0 [2018-07-15 07:39:16 +0000] [11359] [INFO] Listening at: http://0.0.0.0:4000 (11359) [2018-07-15 07:39:16 +0000] [11359] [INFO] Using worker: sync [2018-07-15 07:39:16 +0000] [11362] [INFO] Booting worker with pid: 11362 [2018-07-15 07:39:16 +0000] [11362] [ERROR] Exception in worker process Traceback (most recent call last):File "/home/ec2-user/bankserver/env/lib /python3.6/site-packages/gunicorn/arbiter.py", lineworker.init_process() File "/home/ec2-user/bankserver/env/lib/python3.6/site-packages/gunicorn /workers/base.py",self.load_wsgi() File "/home/ec2-user/bankserver/env/lib/python3.6/site-packages/gunicorn/workers/base.py",self.wsgi = self.app.wsgi() File "/home/ec2-user/bankserver/env/lib/python3.6/site-packages/gunicorn/app/base.py", linself.callable = self.load() File "/home/ec2-user/bankserver/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py",return self.load_wsgiapp() File "/home/ec2-user/bankserver/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py",return util.import_app(self.app_uri) File "/home/ec2-user/bankserver/env/lib/python3.6/site-packages/gunicorn/util.py", line 35 __import__(module) ModuleNotFoundError: No module named 'aggregator' [2018-07-15 07:39:16 +0000] [11362] [INFO] Worker exiting (pid: 11362) [2018-07-15 07:39:16 +0000] [11359] [INFO] Shutting down: Master [2018-07-15 07:39:16 +0000] [11359] [INFO] Reason: Worker failed to boot. gunicorn.service: main process exited, code=exited, status=3/NOTIMPLEMENTED Unit gunicorn.service entered failed state. gunicorn.service failed. Installed path: I have installed virtual env in : /home/ec2-user/bserver/env/bin/* I have django application in : /home/ec2-user/sigma_app/django_app_04-07-2018/aggregator(here aggregator is project name) gunicorn.service contains: [Unit] Description=gunicorn daemon After=network.target [Service] User=ec2-user Group=ec2-user WorkingDirectory=/home/ec2-user/sigma_app/django_app_04-07-2018/aggregator ExecStart=/home/ec2-user/bserver/env/bin/python3.6 /home/ec2-user/bserver/env/bin/gunicorn --workers 3 --bind :4000 aggregator.wsgi:application -
Django: Can I join auth backend and shop logic under one app?
I have a working, almost complete e-commerce project. The only think that is still undone is custom users (+ their profiles and authentication). Can I join custom user authentication logic and bookstore catalog logic in one app in my project? Will It be anti-pattern or break some Django conventions, etc? The reason why I'm asking is that my custom auth app which was built as reusable, in practice cause some 403 errors and other problems with my project. What's your thoughts? -
django overrdie admin login page template
I want to change admin login page behavior: if the user is logged in and is staff, directly go to the admin page if the user is not logged in or is logged in but is not staff, go to my website main login page if the admin logs out from the admin page, do not show logout page and directly go to myWebsite. to do that, I created an Admin app in the project, then: 'DIRS': [ os.path.join(PROJECT_PACKAGE, 'templates'), os.path.join(BASE_DIR, 'admin', 'templates') ], and in templates folder, I added a login.html and inside it: {% if not user.is_staff %} <script>window.location = "{% url "login" %}?next=/admin"</script> {% endif %} This works perfectly, but I have two questions: Is this the best way to do that? I have seen some solutions that create a subclass of AdminSite and change login_template, Should I do that or what I did is enough? If it is enough, What is the usage of that practice? In my solution, is default login template rendered as well or only mine is loaded? I am worried that both render at the same time and in some special cases, users see a blink. tnx -
Combining queries into one and then ordering by date
I have 3 tables. User, Post, and Share. Post is a table that contains all posts. Post has a one to many relationship with Share. That being said, the Share table is a table where it indicates which posts a user has shared. Here's the structure of the tables: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) share_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=150) class Share(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) shared_at = models.DateTimeField(auto_now_add=True) What I want specifically is a query that gets what posts the user has shared and the posts the user has created. For example, let's say we have the same data: Post table id user status share_count created_at url 1 1 hello 32 2017-06-01 hello 2 2 What's up 22 2017-07-01 whats-up Share table post user shared_at 2 2 2017-07-02 I want a query that will get a user's shared posts + their posts. So let's say I want to do that for user 1. The result should be post 1 and post 2 since the user posted post 1 and also shared post 2 from user 2. Here's what I have so far: from itertools import chain user = … -
Saving data from form to database using Django in otree game design
I want to post the data from a form to database. I am not sure how to do this. The form is generated from a model, the model has two foreign keys, I want to assign value to them in the page process. But it does not work. Any one have any idea? Thanks!!!!!!!!!! I tried this: class Punishment(Page): def vars_for_template(self): return {'form': TokenForm()} def post(self): # context = super().get_context_data() # context['formset'] = formset # context['form'] = self.get_form() form = TokenForm(self.request.POST) if form.is_valid(): amountp = form.cleaned_data['amountp'] amountn = form.cleaned_data['amountn'] t = Token(amountp=amountp, amountn=amountn, sender=self.player, receiver=self.player.get_others_in_group()[0]) t.save() The model is defined as: class Token(djmodels.Model): sender = djmodels.ForeignKey(to=Player, related_name='tokens_sent') receiver = djmodels.ForeignKey(to=Player, related_name='tokens_received') amountp = models.IntegerField(null=True, widget=forms.HiddenInput(), initial=0) amountn = models.IntegerField(null=True, widget=forms.HiddenInput(), initial=0) The form: class TokenForm(ModelForm): class Meta: model = Token fields = '__all__' I got an error: AttributeError at /p/m0jnvjod/pggfg/Punishment/4/ 'NoneType' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/p/m0jnvjod/pggfg/Punishment/4/ Django Version: 1.11.2 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'get' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/utils/cache.py in patch_cache_control, line 68 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 Python Version: 3.6.4 Python Path: ['/Users/lishuyan/Documents/Practicum/human-behavoir/Treatment1', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib- dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages'] Server time: Sun, 15 Jul 2018 06:20:37 +0000 Traceback Switch to … -
Nginx is not serving my django app media files
I am new at django, and I recently sent my django app to production. On my website, I can only see static files, but media are different story. I have tried for three days to solve this issue but without luck. The following are my settings and nginx set up: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR server { listen 80; server_name myIP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/make/leosblog; } location / { include proxy_params; proxy_pass http://unix:/home/sammy/myproject/myproject.sock; } } I have noticed while inspecting the html, that media files' path start with '/media/media/...', however, all my media files are inside only one media folder. Not sure if this is the cause for this problem. What can I do to solve this issue? Thanks a lot in advance. -
attribute geoManager dont support in django 2?
I search a-lot of time without benefit i use Django 2.0.6 but in the note reles of The Django 2 they sadi . "GeoManager and GeoQuerySet classes are removed" this error objects = models.GeoManager() AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager' my code from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models class Incidences (models.Model): name=models.CharField(max_length=20) locations = models.PointField() objects = models.GeoManager() def __unicode__(self): return self.name class Meta: verbose_name_plural = "World Borders" -
django custom user model with auth_views.login
I have created a custom User model in my app. from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass Then in settings.py i have added this : AUTH_USER_MODEL = 'myapp.User' and this is in urls.py: path('', auth_views.login, name='login'), when i go to localhost:8000 & ebter the login details that i created by loogin in the admin site it shows either username or password is incorrect. why is this so? i can see the user section under myapp in admin . this is where i created my user -
Displaying and submitting form details in same page with some specifications
In my models user is mapped as foreign key to model named "decision" If a User enters that page, I need the following to be seen in page [user dropdown] [start date selection] [end date selection] [submit] after filling all three if he should be able to see his decisions taken between those dates, but still be able to edit those fields. (If it can be done without pressing submit,with Jquery such a solution would be more helpful) class Decision(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) startdate = models.DateField(default=date.today) -
iteration through lookups table in Django Rest Framwork
I have a lookups table that contains course categories and subcategories separate enter image description here The relation between them is that attr3 = id_of_the_category && attr1 = CRS_SB_CTGRY I want to merge them together in one list like: [{"id":140,name":"Computer Science","subcategories":[list of the related ones]} this my model.py -
Can not filter with django-filter
I am using django-filter and django rest framework to filter data. My issue is that I get back all my data and not the filtered ones. This is the view that renders the page with the filters form: class MyProductsFilterView(LoginRequiredMixin, FilterView): model = Product filterset_class = ProductFilter template_name = "products/my_products.html" context_object_name = "my_products" def get_queryset(self): return Product.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super(MyProductsFilterView, self).get_context_data(**kwargs) context["my_products"] = Product.objects.filter(user=self.request.user).select_related().order_by("-timestamp") return context When the apply button is clicked in the filters form the following function is called: function applyFilters(event) { event.preventDefault(); var FiltersForm = $(".filters-form"); $.ajax({ type: 'GET', url: '/filtered-products/', data: FiltersForm.serialize(), success: function(res) { console.log(res) }, error: function (res) { console.log("Error"); } }) } The filters form is serialized and a get request is made to get the filtered data with the following drf class view: class FilteredProductsListAPIView(LoginRequiredMixin, ListAPIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ProductFilter This the url for the drf class: url(r"^filtered-products/", views.FilteredProductsListAPIView.as_view(), name="get-filtered-products") Instead of getting back the result of the filters being applied, I get all my data. -
Django settings: How to access variables from the settings folder in an app
I have a djanog project with the following structure: --|src --project --|settings --__init__.py --production.py --local.py --|app1 In my app I import the settings (from django.conf import settings) and then as I was following a tutorial they said to do this getattr(settings, VARIABLE). That doesn't work for me. Instead I can do this: settings.VARIABLE. What's the difference? Oh and I ran type(settings) and it outputted <class 'django.conf.LazySettings'>. -
In Django Rest Framework, writing a custom function to filter db
Django : Filter query based on custom function I am referencing the question and the answer at the bottom. I am trying to write a custom function to query my database for active capsules. Also, is the manager class better. model.py class SnapCapsule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) dateToPost = models.DateTimeField() image = models.FileField(upload_to=user_directory_path) caption = models.CharField(max_length=20, blank=True) def isActivae(currentDate, days=1): threshold = timedelta(days=days) dateToDelete = capsule.dateToPost.replace(tzinfo=None) + threshold if currentDate > self.dateToPost and currentDate < dateToDelte: return True else: return False views.py class SnapCapsuleViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ capsules = SnapCapsule.objects.all() validDates = [ capsule.dateToPost for capsule in capsules if capsule.isActive(datetime.now())] queryset = capsules.filter(dateToPost___in=validDates) serializer_class = SnapCapsuleSerializer The error I am getting is on list comprehension part in views.py. -
Calculate percentile rank with Python3 and Django2
I am still new to django. I am trying to display the percentile rank of each student in my database. I have two tables : quiz and student Quiz columns : id correct_answer student_id Student columns : student_id full_name Basically I want to create a new function that returns the percentile rank of each student. I started with this method that gives me the number of correct answers for each student. In my models.py file def get_correct_answers(self): correct_answers = Evaluation.objects.filter( quiz_id=self.id, correct_answer=True, ) return correct_answers In my student_detail_template.html <div class="ui list"> {% for quiz in object.quiz_set.all %} <div class="item"> {{ quiz }} - Nb correct answers : {{ quiz.get_correct_answers }} % </div> {% endfor %} </div> Can you help me to find the most efficient way to return the percentile on my student_detail.html template ? The percentile_rank formula I want to use is : R100(X) = ( ( nb_correct_answers_less_than_X + (nb_correct_answers_equal_to_X / 2) ) / nb_correct_answers ) * 100 I was thinking about making a new function in my view.py class to iterate over all students and make a dictionary of student id and number of correct answers as for example : dict = [['sutdent_id_1', 10],['sutdent_id_2', 7],['sutdent_id_3', 10], ['sutdent_id_4', 5]] … -
Failed to create superuser in django on OpenShift
I'm trying to set up a django app on the OpenShift. Trying to create superuser, having entered username, email and passwords I get a following error: TypeError: object supporting the buffer API required Is it some package missing? Am I doing something wrong? django version 2.0.7 python version 3.6.3 Full error message: (app-root) sh-4.2$ python manage.py createsuperuser Username: maciej Email address: xxx@xxx Password: Password (again): Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/app-root/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/opt/app-root/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/app-root/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/opt/app-root/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/models.py", line 161, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/models.py", line 143, in _create_user user.set_password(password) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 98, in set_password self.password = make_password(raw_password) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/hashers.py", line 80, in make_password return hasher.encode(password, salt) File "/opt/app-root/lib/python3.6/site-packages/django/contrib/auth/hashers.py", line 249, in encode hash = pbkdf2(password, salt, iterations, digest=self.digest) File "/opt/app-root/lib/python3.6/site-packages/django/utils/crypto.py", line 85, in pbkdf2 return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen) File "/opt/app-root/lib64/python3.6/hashlib.py", line 90, in inner return func(*args, **kwargs) TypeError: object supporting the buffer API … -
Getting posts from both tables?
I have 3 tables. User, Post, and Share. Post is a table that contains all posts. Post has a one to many relationship with Share. That being said, the Share table is a table where it indicates which posts a user has shared. Here's the structure of the tables: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) share_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=150) class Share(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) shared_at = models.DateTimeField(auto_now_add=True) What I want specifically is a query that gets what posts the user has shared and the posts the user has created. For example, let's say we have the same data: Post table id user status share_count created_at url 1 1 hello 32 2017-06-01 hello 2 2 What's up 22 2017-07-01 whats-up Share table post user shared_at 2 2 2017-07-02 I want a query that will get a user's shared posts + their posts. So let's say I want to do that for user 1. The result should be post 1 and post 2 since the user posted post 1 and also shared post 2 from user 2. I have made this query, but for some reason only the shared … -
Django Restful API Design Validation Logic
Here I have an endpoint to create media content for users. The endpoint works, but I have a feeling my design implementation is incorrect. Should validation logic be contained in serializers create? Is this bad practice? I attempted to move validation logic to models.py, but ran into issues with accessing the model, specifically this line - self.model(user=user, category=category). view.py from rest_framework import status from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .models import UserMedia from .renderers import UserMediaSerializerJSONRenderer from .serializers import UserMediaSerializer class UserMediaCreateAPIView(APIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserMediaSerializerJSONRenderer,) serializer_class = UserMediaSerializer def post(self, request): userMedia = request.data.get('userMedia', {}) serializer = self.serializer_class(data=userMedia) serializer.is_valid(raise_exception=True) serializer.save(user=request.user, category=userMedia['category']) return Response(serializer.data, status=status.HTTP_201_CREATED) serializers.py from rest_framework import serializers from .models import UserMedia class UserMediaSerializer(serializers.ModelSerializer): category = serializers.CharField(allow_blank=False, required=True) class Meta: model = UserMedia fields = ('category',) read_only_fields = ('category',) def get_category(self, obj): if obj.category: return obj.category return 'N/A' def create(self, validated_data): if validated_data['user'] is None: raise TypeError('User media must have a user') if validated_data['category'] is None: raise TypeError('User media must have a category.') if validated_data['category'] not in dict(UserMedia.CATEGORY_CHOICES): raise TypeError('User media category is not available.') userMedia = UserMedia(**validated_data) userMedia.save() return userMedia models.py from django.db import models class UserMedia(models.Model): user …