Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple lookup fields for DetailAPIView in Django Rest Framework 3.7
I have an api list of posts with Django Rest Framework. Knowing that I slugify my post title, which a non-required attribute for my Post model, I want to make a lookup for the post api detail by either searching the pk (the lookup default in DRF) or the slug field if there is a one. In my api folder of the post application, I wrote the following views.py: class PostDetailAPIView(generics.RetrieveAPIView): queryset = Post.objects.all() serializer_class = serializers.PostDetailSerializer try: lookup_field = 'slug' except: lookup_field = 'pk' And proveded the corresponding urls.py: urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name='list-api'), url(r'^(?P<slug>[\w-]+)/$', PostDetailAPIView.as_view(), name='detail-api'), url(r'^(?P<pk>\d+)/$', PostDetailAPIView.as_view(), name='detail- api'), ] This approach works perfectly when a post has a slugified (title) lookup. But the post detail view for a post with no slug shows the following: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } I want a suggested approcah to show the post api detail for a both the pk and the slug fields lookup, preferably with no code repitition in the urls.py. -
Django LoginView doesn't override attributes
I'm trying to override attributes in my Django application and for some reason I cannot override some attributes of the LoginView. I've tried to do that both as my own class based view and directly on the urlconfig, passing the attributes as arguments to the as_view function, nothing worked. To be more specific, i'm trying to override the template_name but it seems like Django ignores my argument and still trying to look to 'registration/login.html', even though i've passed another path of my own HTML template in another directory. What am I doing wrong? Here is my code, or how I tried to use it: url(r'^accounts/logout/$', auth_views.LogoutView.as_view(template_name='accounts/login.html')), or class SigninView(LoginView): template_name = 'login.html' def get(request): form = LoginForm return render(request, self.template_name, {'form':form}) I've already tried to change the name (or the path) of my template name, both as the as_view function or on my created class based view, but Django looks always for this specific path - '/registration/login.html' - basically to the origin path. Therefore I assumed that Django doesn't recognise for some reason my overriding and looks for the original attributes as it's set in the LoginView. The error: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://localhost:8000/accounts/login/ Django … -
Django - static files is not working
I'm new to Django. I want to add my CSS file in template/index.html, but I don't know how to do it except in DEBUG mode. Project name: mercury App name: gamma /root/workspace/django/mercury/mercury/settings.py STATIC_URL = '/static/' STATIC_ROOT = '/root/workspace/django/mercury/static/' STATICFILES_DIRS = [ '/root/workspace/django/mercury/bootstrap/dist/', ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) /root/workspace/django/mercury/gamma/templates/gamma/index.html <link href="{% static 'css/dashboard.css' %}" rel="stylesheet"> Full path of the originally dashboard.css file /root/workspace/django/mercury/bootstrap/dist/css/dashboard.css After running 'python manage.py collectstatic' /root/workspace/django/mercury/static/css/dashboard.css The output: [20/Oct/2017 12:27:48] "GET /static/css/dashboard.css HTTP/1.1" 404 98 I'm missing something? I tried numerous things but didn't helped. Thanks in advance! -
Django: can't reset superuser password if not set at installation [duplicate]
This question already has an answer here: How to automate createsuperuser on django? 8 answers I'm deploying Django automatically. I create a superuser at installation with the command : python manage createsuperuser --username me --email me@example.org --noinput When I do this no password is set for the account and I'm not able to change the password with the "Forget password" functionality. If I do : python manage changepassword me Then I can reset the password. This behavior comes from this code : return (u for u in active_users if u.has_usable_password()) What would be the way to "activate" the reset function for all users without hacking the core ? -
Django - Change a popup to a internal popup
I would like to change an external popup to an internal popup. Here my HTML code : {% for i in disabled_41 %} {% if i.workshop_id == wk.id %} <span onclick="return popup('disabled/check/{{ i.id }}')" id=redcircle></span> {% endif %} {% endfor %} Here my JS code : function popup(page) { window.open(page, "popup_test", "menubar=no, status=no [...]"); } I would like that everything in this popup appears in a little information's box near the red circle we clicked before. If possible, I would like to keep the url with {{ i.id }}, because this is one of the parameters of the function I used. Thanks a lot ! -
Django query with __range and F
I am trying to write a query that filters based on particular date. Let say i have three data in the db target_date = 28th of october today = 23rd of october data one publish_date = 26th of october data two publish_date = 24th of october data three publish_date = target_date # 28th of october My query needs to fetch all data that is three or less days before the target date. since target date is 28th of october, any data within the range of 26th, 27th and 28th (target date) should be fetched. query MyModel.objects. filter(publish_date__range= [F('publish_date'), F('publish_date') - timedelta(days=3)]) I am getting unexpected result. -
How to check if current url in list of urlpatterns?
I am a bit puzzled. I want to check if the current url of the website is in a specific subset of my urlpatters. Which function of django would do this? This is for a middleware that requests additional information before moving to a specific part of my website. class AuthorityMiddleware(object): def process_request(self, request): current_url = request.path_info if not request.user.is_anonymous() and current_url not in exclude_list: if not request.session.get('authority'): return get_the_authority(request) How should exclude list relate to the urlpatterns defined in urls.py? -
Django - context process query being repeated 102 times
I have built a context process that sends the logged on users permissions as a string into a template. Then based on that users perms I show or hide urls. However using the debug toolbar ive just seen that the query is run 102 times for a reason I do not know The debug (the ID changes and it looks as if there are 3 of each ID in the duplicates) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`id` = 35 Duplicated 102 times. 0.6862959744274587% 23.41 Sel Expl Connection: default /itapp/itapp/sites/views.py in site_detail_files(214) 'PageType' : 'files', /usr/local/lib/python3.6/contextlib.py in __enter__(81) return next(self.gen) /itapp/itapp/itapp/context_processors.py in UserPerms(34) 'Perms': str(all_perms), the function: def UserPerms(request): from django.contrib.auth.models import Permission all_perms = [] if str(request.user) != 'AnonymousUser': permissions = Permission.objects.filter(user=request.user) group_permissions = Permission.objects.filter(group__user=request.user) all_perms = [] for p in permissions: all_perms.append(p) for p in group_permissions: all_perms.append(p) return { 'Perms': str(all_perms), } added to templates in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR + '/templates/', ], 'APP_DIRS': True, 'OPTIONS': { 'debug' : DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'django.template.context_processors.static', 'itapp.context_processors.breadcrumb_history', 'itapp.context_processors.UserPerms', ], }, }, ] usage example: <li><a href="{% url 'sites:site_detail_circuits' SiteID %}">Circuits</a> {% if "Permission: sites | Circuit Data | Can add … -
Not able to change primary key name of authentication table
when i execute the command python manage.py makemigrations the result is You are trying to add a non-nullable field 'pk_bint_user_id' to appuser without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py And my model is look like as follows: class AppUser(AbstractBaseUser): pk_bint_user_id = models.BigIntegerField(primary_key=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) fk_bint_travel_agency_user_id_or_corporate_user_id= models.BigIntegerField(blank=True,null=True) chr_travel_agency_user_or_corporate_user =models.CharField('Agency user or Corporate user',max_length=5,blank=True,null=True) chr_user_type = models.CharField('User type code',max_length=5,blank=True,null=True) vchr_account_type=models.CharField('Account type',max_length=5,blank=True,null=True) vchr_account_status=models.CharField('Account status',max_length=5,blank=True,null=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table='tbl_user' All i want to customize the primary key into different name than "id", -
Django Class Based View with get_queryset()
I would like to use get_queryset() with Class Based View but I don't overcome to display variables in my template. The function is very simple : class MyClassView(LoginRequiredMixin, ListView) : template_name = 'my_template.html' model = Foo def get_queryset(self) : foo = Foo.objects.order_by('-id') bar = foo.filter(Country=64) return foo, bar And my template : <table style="width:120%"> <tbody> <tr> <th>ID</th> </tr> {% for item in foo %} <tr> <td>{{ foo.id }}</td> </tr> {% endfor %} </tbody> </table> <br></br> <table style="width:120%"> <tbody> <tr> <th>ID</th> </tr> {% for item in bar %} <tr> <td>{{ bar.id }}</td> </tr> {% endfor %} </tbody> </table> I have to use Context dictionary ? -
How to manage user content in django?
I want manage user posts. When someone create new post it's should display on admin, but not on html. If content is valid i want push on allow button and it will display on html for all users. i was try to google something, but nothing helpfull. I suppose logic must be like this: User create new post. Post displayed on admin panel. Admin allow the post. Post displayed in html. How it should work? -
Is it possible to combine a web dyno and bot dyno on Heroku django app?
I'm building a discord bot that gathers links from discord chat stream of specific server and channel. Bot is then suppose to publish the links on the website so they are not lost in discord but plain sight on website. This is school project where I don't want to put my money on. The problem this time is that I have a web dyno and bot (worker?) dyno on heroku and they both consume my dyno time so it cannot handle both because there are only 1000 free hours in Heroku. My guess is that the project could be ran in one dyno but I couldn't find out how so at the moment it's working as follows: Bot dyno: Bot is just one file that can be run as a script that runs 'forever'. So I run it with command python manage.py bot. Here's how the script works Web duno: Website is running with runserver like normal web dyno on heroku. In free heroku the dynos fall asleep after 30mins of inactivity so I have configured another free service to ping the website every half an hour to keep the bot online. This is odd behaviour in my opinion. Why … -
Django query - get first x elements which together exceed a specific amount for a field
I want to request the first x elements which together exceeds a specific amount, and I don’t know if this is somehow possible. Assuming that this is my model: class Article(models.Model): price = models.DecimalField(default=0.0, max_digits=7, decimal_places=2) If I order the „Articles“ by the „price“, I want the first „Articles“ which together exceed the „price“ of let’s say 100 Dollars. Is this somehow possible with annotating, summing, extra() or whatever?? Article.objects.order_by(„price“) ?????? Thanks for any help!!! -
How to extend django-registration form's clean_email() method?
from django import forms from registration.forms import RegistrationFormUniqueEmail class NewRegistrationForm(RegistrationFormUniqueEmail): # def __init__(self, *args, **kwargs): # super(NewRegistrationForm, self).__init__(*args, **kwargs) def clean_email(self): cleaned_data = super(NewRegistrationForm, self).clean_email() if "@iiitvadodara.ac.in" not in cleaned_data: raise forms.ValidationError("You must have a IIIT Vadodara email address to register.") return cleaned_data I want to extend the RegistrationFormUniqueEmail in django-registration to accept only email address which end with @iiitvadodara.ac.in. The method works but when I click on the activation link which is sent to my email address. It shows activation failed even when I do activation within time limit. Please help me my showing me the correct method to do this. -
Disable logging except in tests
Throughout my app I am using the following logger: logger = logging.getLogger() However, I want to disable it and disabling logging in general when running tests, so ontop of the tests.py file I included: logging.disable(logging.CRITICAL) But I would like to be able test-specific messages. I tried getting a new logger and setting a different level: logger = logging.getLogger('TestLogger') logger.setLevel(logging.DEBUG) But the disable call seems to affect it too. How can I disable all other loggers except for my logger using in the tests file? -
Django how to set input element's value attribute from views?
I want to set HTML input element's value attribute from Django views. Here is the code for that element: <input name="predict_file" type="text" id="photoCover" class="input-large" value="{{ fn }}" style="height:30px;"> and my view's code: def upload_predict(request): if request.method == 'POST' and request.FILES['predict_file']: predict_file = request.FILES['predict_file'] fs = FileSystemStorage() filename = fs.save(predict_file.name, predict_file) predict_file_location = fs.url(filename) return render(request, 'predict.html', {'fn':filename}) return render(request, 'predict.html', {'fn': 'No file uploaded yet'}) Is there anyone could help me to give out of this problem? -
Django vs PostgreSQL: how to queue write and read?
I have got the following problem: We have 3 components in the system - say, front-end, a Ruby app that deals with database write requests and a Django app that handles the read requests (from the same PostgreSQL database). At some point, the front-end updates (PUT) a record in the database via Ruby app and after that request, asynchronously sends another request to fetch the updated version of that record via Django app (GET). The problem is that the GET requests sometimes returns the old version of the record (not updated), that is, the Ruby app takes too long to update the database and before it is done, Django fetches the old version of the record. I am aware that my server is too "weak" for this kind of job and with a proper serving computer it will be fine, but it is not 100% guaranteed. I can think of few ways of dealing with that, just wondering if there is a proper way of fixing it? Thanks! P.S.: The Ruby and Django apps do not interact with each other and it is one of the important requirements! -
Error in showing user profile link in homepage in Django
This is my models.py class Post(models.Model): topic = models.CharField(max_length=200) description = models.TextField() created_by = models.ForeignKey(User, related_name='posts') created_on = models.DateTimeField() class Comment(models.Model): commented_by = models.ForeignKey(User, related_name='comments') commented_on = models.ForeignKey(Post, related_name='comments') commented_text = models.CharField(max_length=500) commented_time = models.DateTimeField(auto_now_add=True) class Blogger(models.Model): username = models.OneToOneField(User, related_name='bloggers') blogger_bio = models.CharField(max_length=1000) URL.py for username url(r'^(?P<username>[a-zA-Z0-9]+)/$', views.author_desc, name='author_desc'), Views.py from django.shortcuts import render, get_object_or_404 from .models import Post, User, Comment, Blogger from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def home(request): posts_list = Post.objects.all() return render(request, 'home.html', {'posts': posts}) and my home.html where i want to display: <!DOCTYPE html> <html> <head> <title>HOME</title> </head> <body> <h2>All Blogs</h2> {% for post in posts %} <a href="{% url 'post_desc' pk=post.pk %}"><b>Post Topic: </b>{{ post.topic }}</br></a> <b>Published Time: </b>{{ post.created_on }}</br> <b>Author: </b><a href="{% url 'author_desc' blogger.username %}">{{ post.created_by }}</a></br></br> {% endfor %} </body> </html> I want to show each blogger's page from a link from the home. But it is getting problem. What i'm doing wrong here? -
signing api calls from frontend to backend
I am implementing a secure way for the frontend to communicate with the backend using a secret key. The backend is a sensitive service (mobile banking.) First I was thinking JWT, but the token-based appoach has two disadvantages: The frontend has to obtain the token, this means it has to send some auth data to the backend - and this request can be reproduced. Even if there is some secure way of obtaining the token, anyone can fire up Chrome dev tools and use it while it's not expired. So the alternative approach is to sign each request from a frontend with a secret key. The key is known to backend and frontend; the frontend is bundled and uglified so as to keep the key secret. We contatenate the request URL and its payload, encrypt them with a secret key and send the resulting hash in a header. The backend gets the request, does the same encryption and compares the headers; if they are equal - it makes the request. This leads me to three questions: Does this really mean that even if the request is sniffed it cannot be reproduced unless the url+payload is the same? Is there something … -
Sample code of a get and post method on swift to access a django server requiring csrf token
I am building an app that need a loggin to a django web server. However this server requires a csrf token for loggin. I've looked at the doc and I couldnt find anything except this post here which seems outdated POST with CSRF token to Django Server from iOS -
Setting choices by foreign keys parent model's field
I want to set the choices according to a foreign keys parent model's field's value. I.e. "QuestionAnswer" models foreign key "question" is set to model "Question" and that model contains a field "question_type". If the "question_type" value is 1 then set the choices as a, b, c, d, e or if the value is 2, set the choices as f, g, h, i, j. Forms are built as formset but that shouldn't affect how it is done? First of all do I set the choices as a function and where do I set it? Forms.py, models.py or views.py? If in the forms.py do I do it with the init method? How do I get the correct question and the correct choices together? If you need more info, please ask. Django version is 1.11.5 and python version is 3.6.0 forms.py class AnswerForm(forms.ModelForm): class Meta: model = QuestionAnswer fields = ['question', 'answer_text', 'questionnaire_key'] exclude = [] widgets = { 'question': HiddenInput, 'answer_text': RadioSelect(choices=CHOICES, attrs={'required': 'True'}), 'questionnaire_key': HiddenInput } models.py class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire) question_text = models.CharField(max_length=200) question_type = models.CharField(max_length=2) def __str__(self): return self.question_text class QuestionAnswer(models.Model): questionnaire_key = models.ForeignKey(Questionnaire, null=False, blank=False) question = models.ForeignKey(Question, null=False, blank=False) answer_text = models.CharField(max_length=1, null=False, default=None) def … -
Cannot install cherrypy on python 3.6
I am not able to install cherrypy on python 3.6 as it shows error "missing paranthesis " while installingThis is the snapshot of my problem -
How can I use Fuse.js to search object in GeoJSON outside of map?
I have a search box outside of a Leaflet Map as follows: <div> <input id="search" name="search" type="text" class="query-search form-control input-sm" style="width:320px;" placeholder="Search route name..."> <span> <button class="query-search btn btn-default btn-sm" type="button" /> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> I wanted to use Fuse.js in this search box from a geojson object that was passed from a Python Django View. This is how I load it: var geojsonFeature = {{ route_geojson | safe}}; L.geoJSON(geojsonFeature,{ style:function(feature) { switch (feature.properties.route_type) { case '1': return {color: "#2db22d"}; //Green case '2': return {color: "#1d4fd6"}; //Blue case '3': return {color: "#e3803d"}; //Orange } } }).addTo(map); I can't seem to find a tutorial about Fuse.js. If there is one, kindly point me to the website :) Thanks in advance! -
How do i edit the favicon in the Browsable API in Django REST framework?
I need to edit the favicon of the Browsable API. Is it possible to do that by overriding api.html in templates? -
Tagging and posting on Facebook using Graph API and Python 2.7 with Django Allauth
I am trying to create an application in Django with Django-Allauth and Python 2.7, where I can post the message on Facebook with my friends tagged in. I know that the taggable_friends can get me the names of my friends. But could not able to figure out how I can post that message on my wall and tag my friend with it using the graph API. Here is teh Graph API I tried to access my friend: https://graph.facebook.com/v2.10/me?access_token=xxxxxxx&fields=taggable_friends Kindly, help me in how I can post the message: I am your best friend on the wall and tag my friend with it.