Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pdfkit generates small scaled pdfs
I am using pdfkit in order to generate pdfs from html strings, rendered by my Django's views. For some reason, the output pdf is small. My pdfkit option dictionary is - options = { 'quiet': '', 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'disable-smart-shrinking': '' } and the output file is here Html code is - <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="pdfkit-orientation" content="Portrait"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Dribble</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800" rel="stylesheet"> <!-- Custom Font --> <style> body { font-family: 'Open Sans', sans-serif; } p, a { color: #002f54; } .nav { background: #002f54; color: #FFFFFF; border-radius: 5px; } .ico { padding-right: 5px; top: 3px; } .nav > li p { text-align: center; font-size: 36px; font-weight: 800; } .right-align { float: right; } .pad-mar { font-size: 18px; padding-top: 10px; padding-bottom: 10px; margin-left: 30px !important; margin-right: 30px; } .pad-mar-middle { font-size: 18px; padding-top: 78px; padding-bottom: 25px; margin-left: 30px !important; margin-right: 30px; } .pad-mar-bottom { font-size: 18px; padding-top: 10px; padding-bottom: … -
Database Error When Running Python Script - Does Not Exist
I am getting a database error that none of my models exist when running a script. If I inspect my database they are clearly there, but for some reason my script is not finding any. I've tried re-running manage.py migrate multiple times to no avail as well. Please let me know if you have any suggestions how to proceed! Error (I am getting this for the first model the script sees and all): django.db.utils.ProgrammingError: relation "betting_team" does not exist LINE 1: ...ting_team"."name", "betting_team"."sport_id" FROM "betting_t... Script (redacting info regarding API): import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'social_betting2.settings') import django django.setup() import pytz utc = pytz.UTC import requests from betting.models import Game, Team, Spread, Sport, TeamGame, Moneyline import dateutil.parser, datetime from dateutil import tz def getGame(): for x in items: sport_number = str(x['Sport']) if sport_number in sports_dict.keys(): sport_name = sports_dict[sport_number] sport = Sport.objects.get_or_create(name=sport_name)[0] team1 = Team.objects.get_or_create(name=x['AwayTeam'])[0] team2 = Team.objects.get_or_create(name=x['HomeTeam'])[0] time= dateutil.parser.parse(x['MatchTime']) from_zone = tz.tzutc() time2 = time.replace(tzinfo=from_zone) to_zone = tz.gettz('America/New_York') time3 = time2.astimezone(to_zone) identification = x['ID'] # time neutral to UTC lastUpdated2 = lastUpdated.replace(tzinfo=from_zone) lastUpdated3 = lastUpdated2.astimezone(to_zone) # create game g = Game.objects.get_or_create(identification=identification, final=False)[0] g.sport = sport g.time = time3 # g.lastUpdated = lastUpdated3 # team game create tg1 = TeamGame.objects.get_or_create(team=team1, game=g)[0] tg2 = … -
Modify Django Admin Page
I have a django admin where the name for the login was changed and after logging in the page is cut off. I went in to modify the page but it appears there is no admin/index under templates. I have looked throughout the project and can not find it anywhere. Is there an easy way to locate the files needed to proceed with the project? -
Django autocomplete
I am trying to put searchbar with autocomplete function using django-autocomplete-light Here is my view: class SearchAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Trip.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs my form: class SearchForm(forms.Form): keyword = forms.ModelChoiceField( queryset=Trip.objects.all(), widget=autocomplete.ModelSelect2(url='search-autocomplete') ) and my url: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', home, name='home'), url( r'^search-autocomplete/$', SearchAutocomplete.as_view(), name='search-autocomplete', ), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) However, whenever I am starting to type anything I get The results could not be loaded, despite corect queryset object precense. Example: -
Django - changes which I do in static files don't appear immediately
Something really strange happening with my Django environment, recently. After I updated Django from 1.9 to 1.10 and updated PyCharm to latest version I have a problem with static files. When I writing change both in css or js files, I don't see those changes immediately on apps. I need manually run direct link to one of those files in browser(for example http://127.0.0.1:8000/static/css/main.css) and after that I can see changes. Before updates all worked correctly and I have seen all changes in static files immediately. settings STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '/static/', ) urls urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Python(Django) - KeyError: 'user_type'
I'm working on a django project and stumbled upon this error when i try to authenticate a user using Facebook Auth "" Key error at api/social/convert-token 'user_type' "" I would like to add that I'm using the django-rest-framework-social-oauth2==1.0.5 as well as the SOCIAL_AUTH_PIPELINE and I'm running tests through PostMan through which I'm passing "user_type" as a parameter Here is the code troubling me the problem and I'm also adding the (models.py ). Feel free to ask any question and thanks in advance for your help function with the "key_error" models.py -
django ajax request dont get data
<form id="searchform"> {% csrf_token %} <div class="col-md-8"> <input type="text" id="question" class="form-control" placeholder="Ask your foody question......" name="question"> </div> <div class="col-md-2"> <input class="btn btn-primary" type="submit" value="ASK"> </div> <form> </div> </div> I have this template and bellow ajax request to get data to view <script type="text/javascript"> $("document").ready(function(){ $("#searchform").submit(function() { $.ajax({ type: "POST", url : "results", data:{ input:$("#question").val(), csrfmiddlewaretoken: '{{ csrf_token }}' } , success : function(data){ $('#answer').html(data); } },"json"); }); }); </script> and view is below def results(request): if request.method == "POST": resource = request.POST['input'] return render(request, 'index.html',{"resource" : resource}) the thing i sumbit in form can be seen in url.but does not print result in template.What is the problem in this code?thanks in advance :) -
How to create notification date field in DjangoORM using annotate
I would like to create a new field named notification_date using annotate in DjangoORM. Here is my model: SpeciesType(models.Model): # ... some species type setting fields. heat_lapse = IntegerField() estrous = IntegerField() Breeding(models.Model): # .. some breeding fields species_type = ForeignKey(SpeciesType, related_name="breedings", on_delete=CASCADE) created_at = DateTimeField(auto_add_now=True) Now the formula of date notification of breeding is Breeding.created_at + (SpeciesType.heat_lapse * SpeciesType.estrous) in days e.g. 1/29/2017 11:21PM + (3 * 21) in days = 4/2/2017 as notification date So in order to achieved this i created this query filter with timedelta, F() object, and ExpressionWrapper: from django.db.models import F, ExpressionWrapper, DateField from datetime import date, timedelta Breeding.objects.annotate( notification_date = ExpressionWrapper( F('created_at') + timedelta(days=( F('species_type__heat_lapse') * F('species_type__estrous') )) , output_field=DateField()) ).filter( notification_date__lte == date.today() ) but this wont work because you cannot do an F() inside a timedelta. Anyone knows how to formulate this desired query? it would be a great help for me. -
Passing expressions and getting results from Pyton interpreter back to Django?
How do you pass and get results to a python interpreter where the input is coming from a website form? For instance if you have a web form populated with basic arithmetic expressions like addition, subtraction, multiplication and division. If you want to pass that expression like 1+1 or 4/6 to the python interpreter and get the result back to show on the web page is that possible? I'm using Django as framework. -
form not visible on browser even with my get and post methods implemented in django 10.5
class Profile(View): """User Profile page reachable from /user/ URL""" def get(self, request, username): params = dict() user = User.objects.get(username=username) tweets = Tweet.objects.filter(user=user) params["tweets"] = tweets params["user"] = user return render(request, 'profile.html', params) class PostTweet(View): """Tweet Post form available on page /user/ URL""" def post(self, request, username): form = TweetForm(self.request.POST) if request.method == 'POST': if form.is_valid(): user = User.objects.get(username=username) tweet = TweetForm(text=form.cleaned_data['text'], user=user, country=form.cleaned_data['country']) tweet.save() words = form.cleaned_data['text'].split(" ") for word in words: if word[0] == "#": hashtag,created=HashTag.objects.get_or_create(name=word[1]) hashtag.tweet.add(tweet) return HttpResponseRedirect('/user/'+user) else: form = TweetForm() return render(request, 'profile.html',{'form':form}) -
TemplateDoesNotExist at /accounts/regist_save/ error
I got a error . I think urls.py or templates is wrong,but I do not know how to fix it. Furthermore,I think urls.py & templates do not have any bad point.How can I fix them? I wrote in urls.py, from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, {'template_name': 'registration/accounts/login.html'}, name='login'), url(r'^logout/$', logout, name='logout'), url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), ] in views.py @login_required def profile(request): context = { 'user': request.user, } return render(request, 'registration/accounts/profile.html', context) def regist(request): form = RegisterForm(request.POST or None) context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('registration/accounts/profile.html', context) context = { 'form': form, } return render(request, 'accounts/regist.html', context) in profile.html (templates) {% extends "registration/accounts/base.html" %} {% block content %} user.username : {{ user.username }}<hr> user.is_staff: {{ user.is_staff }}<hr> user.is_active: {{ user.is_active }}<hr> user.last_login : {{ user.last_login }}<hr> user.date_joined: {{ user.date_joined }} {% endblock %} -
Django model nullable field error makemigrations
Hello I'm building my own blog and I've been trying to add photos to my blog posts. For now, I can upload photos to the media/documents folder however I'm having problems assigning these photos to posts. This is how my models.py looks like class Document(models.Model): post = models.ForeignKey('blog.Post', related_name='documents', null = True) description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document') views.py @login_required def model_form_upload(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.post = post form.save() return redirect('/') else: form = DocumentForm() return render(request, 'blog/model_form_upload.html', { 'form': form }) inside post_detail.html {% for document in post.documents.all %} <div style="padding: 10px;"> <p> {{ document.description }} </p> <img src=""/> </div> {% endfor %} ... {% if user.is_authenticated %} <a class="btn btn-default" href="{% url 'model_form_upload' pk=post.pk %}">Add photo</a> {% endif %} For now, I'm trying to print out the description and then dealing with the urls will be easier. The photos are being uploaded, they just aren't connected to the posts. When I remove the null = True I can't pass makemigrations on the command line. Can anyone … -
django-autocomplete-light 3.2.1 select_outside_admin
I am trying to use django-autocomplete-light 3.2.1 in my Django (1.10) project with python (3.5) and I found great difficulty in using it. Then I try to follow the live demo shown in the tutorial and pull down all file to my local drive for replication (like the one on http://dal-yourlabs.rhcloud.com/select2_outside_admin/), however in vain. To me, I want to make my local demo work so that I can work my own one based on this. Specifically, when I follow the following codes and run the site, it shows the errors of NoReverseMatch at /select2_outside_admin/ with description of Reverse for 'linked_data' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have no idea what is going wrong. I attached my codes as below and please advise what to do if you know the solution. Many thanks: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'select2_outside_admin', # Autocomplete 'dal', # Enable plugins 'dal_select2', 'dal_queryset_sequence', ] urls.py: from django.conf.urls import url, include from django.contrib import admin from .views import UpdateView urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^select2_outside_admin/', include('select2_outside_admin.urls')), url( r'^select2_outside_admin/$', UpdateView.as_view(), name='select2_outside_admin', ), ] models.py: from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class TModel(models.Model): … -
Getting model instance by variable model name and pk
I am using Django 1.9, and now trying to override save method behaviour. The problem is that when I do instance.some_field = some_value, the self object is already modified, whereas I need to know that was the original value of some_field. To do this, the only way out seems to be fetching object from database by self's pk. So I wonder what is GENERIC syntax - if there's any - to fetch instance from the database? By saying GENERIC, I imply that I don't want to explicitly type the model name (like MYMODEL.objects.get(...)), but rather make Django figure out the right model based on target instance's model. To make the question clearer, let me illustrate my goal in a pseudo-code: def save_extented(self, *args, **kwargs): original_object = (self model).objects.get(pk = self.pk) Is it possible ? Or maybe I don't need this, and there's some smart Django hack to fetch the instance with rolled back field values ? -
Sending Emails with Django using local server is successful. When uploading to heroku it failed
So my team is using Django built-in function to send emails to users with gmail accounts, and it worked on my local server. My team deployed our django app on heroku before and it also worked. However, I have redesigned and thus re-deployed my django app with a clear database (but without changing email functionality), and I am not receiving any email this time. Would it be possible that this fails gmail authentication, or I have to adjust some settings on my computer, because I downloaded the previous work on GitHub. Can someone help me plz? -
How to write these Django Models?
I am new to django I need some help in building the models. This is how the models should be inter connected. I'm building an online quiz app. Kindly help thanks! :) Set (Model 1) 1) Set name 2) Set of Questions 3) Number of chances to attempt answering the questions 4) Points scored Question (Model 2) 1) Question 2) Set of Choices 3) Time to answer a question 4) Correct Solution to the question Choice (Model 3) 1) Choice Please do suggest me with the fields as well like, CharField like that. Thanks! -
Sqlite3 support for CTE and WITH clause on pythonanywhere
I've just deployed my project on pythonanywhere.com. I'm using Django 1.10.4 with sqlite3 as database. I've used some raw queries inside my application which make use of CTE and WITH clause. Sqlite3 supports them from version 3.8.3 (see docs), unfortunately on pythonanywhere the available version of sqlite3 is 3.8.2. Do any of you know how to solve the problem? -
Multiple types of update operations for a model in django rest framework
Follwing is my model class Group(Log_Active_Owned_Model_Mixin): group_name = SafeCharField(max_length = 100, null=False, blank=False, sanitize_cb=safe_name_sanitizer) group_creator = ForeignKey(to=PSS_User, null=False, related_name="group_creator") members = ManyToManyField(to=PSS_User, through="GroupMemberShip", related_name="group_member") class Meta: ordering = ("Meta", ) ## other methods also exists in this class. class GroupMemberShip(Log_Active_Owned_Model_Mixin, ResolvableModelMixin): MEMBER_NONE = 1 MEMBER_ADMIN = 2 MEMBER_STANDARD = 4 VALID_MEMBERSHIPS = ( (MEMBER_ADMIN, "Admin" ), (MEMBER_STANDARD, "Standard" ), (MEMBER_NONE, "None" ) ) member = ForeignKey(to=PSS_User, null=False, related_name="groups") group = ForeignKey(to=Group, null=False, related_name="members") membership_type = SmallIntegerField(editable=False, null=False, blank=False, choices=VALID_MEMBERSHIPS) membership_request = ForeignKey(to=GroupMemberShipRequest, null=True, blank=True) # null True for group creator class Meta: ordering = ("date_created") unique_together = ("member", "group") ## other methods also exists in this class. class GroupMemberShipRequest(Log_Active_Owned_Model_Mixin): GRP_MEMBERSHIP_REQ_STATUS_ACCEPTED = 1 GRP_MEMBERSHIP_REQ_STATUS_REJECTED = 2 GRP_MEMBERSHIP_REQ_STATUS_PENDING = 4 VALID_REQUEST_STATUSES = ( (GRP_MEMBERSHIP_REQ_STATUS_ACCEPTED, "Accepted"), (GRP_MEMBERSHIP_REQ_STATUS_REJECTED, "Rejected"), (GRP_MEMBERSHIP_REQ_STATUS_PENDING, "Pending") ) # TODO :- # Add a field in request-type. There are two types of requests :- # User can request admin to include him in the request. # Admin can request other user, to become part of given group. GRP_REQUEST_ACTIVE = 1 GRP_REQUEST_PASSIVE = 2 VALID_GRP_REQUESTS = ( (GRP_REQUEST_ACTIVE, "Active"), (GRP_REQUEST_PASSIVE, "Passive") ) request_initiator = ForeignKey(to=PSS_User, null=False, blank=False) request_acceptor_rejector = ForeignKey(to=PSS_User, null=True, blank=False) request_status = SmallIntegerField(null=False, editable=False, choices=VALID_REQUEST_STATUSES, default=GRP_MEMBERSHIP_REQ_STATUS_PENDING) target_group = ForeignKey(to=Group, … -
Do I have to set cronjob to reboot everyday on my web application server?
I run my django web application on AWS EC2(t2 micro) I have run it for 3 days and it occured "Not enough memory space" error. So I did swap on so that server can use part of instance storage as a memory. My question is that, is it good idea to set cronjob for rebooting server every day in specific time so that memory could be clear in each day? Thanks. -
django custom.css file is not loading
I am trying to add css to my django project I have called my style sheet custom.css, I am extending base.html in my index.html which is located in my templates folder. when I view the page source and click on the link to the css file, I get the error custom.css could not be found. My file structure is: tweet (main Directory) post (sub directory of tweet) static (sub directory of tweet) css (sub directory of static) custom.css (file in css folder) templates ( sub directory of tweet) base.html(file in templates folder) index.html(file in templates folder) base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>{% block title %}{% endblock title %}</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/custom.css' %}" /> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> {% … -
super() takes at least 1 argument (0 given) when cleaning data in form
Trying to validate input in my form and I am getting super() takes at least 1 argument (0 given) cleaning a form class LeaseTermForm(forms.ModelForm): ...... def clean(self): cleaned_data = super().clean() start = cleaned_data.get("start_period") end = cleaned_data.get("end_period") if start and end: # Only do something if both fields are valid so far. if start.order > end.order: raise forms.ValidationError( "Start Term Period cant come after End Term Period." ) How Can it be fixed? -
Enable Django admin functionality at frontend with inlines
I have decided to move some functionality from my admin website into the frontend. Functionality includes the administration of one model with some foreign key inlines. For that I have installed django-dynamic-formset JQuery plugin (link git) and struggling with it already for couple of days. Here is one of the problems. The same functionality is already implemented in Django admin. I can add, modify, remove inlines and modify model instance as I want. I am wondering why should I use this JQuery plugin and why there are not so many good tutorials on the topic in the Internet? I need a good and recent example of how to use django formsets or inline formsets at the frontend side without JQuery. I whould be glad if it has links (not checkboxes) to remove inline items and add button which will correctly add new inline. P.S. I have read this outdated question and more recent without answers. -
Django add primary key before saving new object
I'm new to Django and have a Q&A project. For each question you may have multiple tags which already exist or put new ones. The new tags should be created before the question is saved. How do I solve this properly? So far I have: def question_add(request): # redirect user to login page if not authenticated if not request.user.is_authenticated(): return render(request, 'account/login.html') # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = QuestionForm(request.POST) if form.is_valid(): # process the data in form.cleaned_data as required instance = form.save(commit=False) instance.created_by = request.user instance.save() messages.success(request, 'Question added with success.') # redirect to the main page: return HttpResponseRedirect('/') else: messages.warning(request, 'Please correct the errors.') # if a GET (or any other method) we'll create a blank form else: form = QuestionForm() return render(request, 'question/add.html', {'form': form}) This should be done prior form.is_valid() or does it exist a magic method for doing this? -
Django- Feeding **kwargs into .aggregate()
Is it possible to do something like this? outputs = {"total_kgs": "kgs"} Model.objects.all().aggregate(**outputs) in place of: Model.objects.all().aggregate(total_kgs="kgs") Right now I am getting: AttributeError: 'str' object has no attribute 'resolve_expression' -
Django - making child class inherit overloaded save method of its parent abstract class
I am newbie in Django and notably its inheritance tools. I have the following architecture: class BaseMixin(models.Model): effective_from = models.DateTimeField(blank = True, null = True) class Meta: abstract = True class QuerySetManager(models.Manager): def get_queryset(self): # ... def __getattr__(self, attr, *args): return getattr(self.get_queryset(), attr, *args) def save(self, *args, **kwargs): # I want this method to be deployed for my_model_instance.save() class MyModel(BaseMixin): # ... objects = QuerySetManager() class Meta: managed = False db_table = 'my_model' class QuerySet(QuerySet): # ... So my goal is to call QuerySetManager's save method when trying to save changes to my_model_instance. The question is, should I overload save method in BaseMixin ? Or in QuerySetManager ? I tied both, and as for now, Django ignores my custom save method in both cases.