Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Add Aldryn Google Analytics to Django CMS
I currently have a django cms website and will like to have google analytics installed, using the aldryn-google-analytics plugin. I don't have a Divio Cloud account, and I'm really new to python. May I seek your advice on the GitHub files to be added to my project please and where the files should be placed into project. -
filter dataset not having a value
Suppose i have a schema like below : Book | Author ------------- B1 | A1 B1 | A3 B1 | A2 B2 | A5 B2 | A4 B2 | A3 B3 | A5 B3 | A6 B3 | A1 B4 | A1 B4 | A5 B4 | A6 and i want to filter out all those book whose author is not A1 (B2 in this case) This is simple SQL using group by and not having clause, what i am having tough time is getting it done usinng django queryset and annotate. Most of the annotate work around count which i am not able to fit in this particular case. any pointers is helpful, thanks! :) -
Access friendlist without taggable_friends permission in Facebook Graph API
I am trying to access the list of friends from facebook that I can display on the Django application made by me. I knoww that there is one permission required called taggable_friends but after reviewing facebook is granting it to me and giving very weird reasons that they found no login button on my application. Even though I have it they still deny. Well, my question is : Does anyone know what can be other way around for getting the facebook friends using the graph API apart from the taggable-friends. Please do not suggest me the read_custom_friendlist and user_friends, as I have checked it and tried to. It gives nothing. Kindly help me. I am using Facebook Graph API v2.10 -
Why the css file can not be found in Django template?
I have created a project in Django. Also, I am using django-allauth for sign up and login. In order to use my own templates with django-allauth, I have created a html file called signup.html in a folder called account inside a folder called templates which is outside of of all my apps (/templates/account/signup.html). That works. I tried to use some custom css file inside signup.html: <link rel="stylesheet" href="/templates/account/signup.css"> It says that the file can not be found. Though, it is located in templates/account. -
Django Rest Framework error: {"user":["This field is required."]
When posting this: curl -X POST -H "Authorization: Token sometoken" -d "url=someurl" 127.0.0.1:8000/create/ I get the error: {"user":["This field is required."] with the ItemSerializer, I have seen other posts on SO talking about using perform_create, which I am trying to use to save the user object, but it doesn´t work for some reason. Perform_create works when user is defined like this: user = serializers.CharField( default=serializers.CurrentUserDefault() ) But I want to use the user object, not only CharField storing the username Serializers: class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ('pk', 'username', 'email', 'first_name', 'last_name') read_only_fields = ('email', ) class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['cat'] class CommentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Comment fields = [ 'comment', ] class ItemSerializer(serializers.HyperlinkedModelSerializer): user = UserDetailsSerializer() category = CategorySerializer(many=True) thecomments = CommentSerializer(many=True) timestamp = serializers.SerializerMethodField('get_mytimestamp') def get_mytimestamp(self, obj): return time.mktime(datetime.datetime.now().timetuple()) class Meta: model = Item fields = [ "url", "user", "timestamp", "categories", "thecomments", ] Model: class Item(models.Model): url = models.CharField(max_length=1000) user = models.ForeignKey('auth.User', unique=False) timestamp = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=1000) categories = models.ManyToManyField(Category) View: class ItemCreateAPIView(generics.CreateAPIView): serializer_class = ItemSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) -
CronJob, django and environment variables
I have built an application for django on Openshift v3 PRO with the django-ex template. It works great. I'm using POSTGRESQL with persistent storage. I need a scheduled cron job to fire every hour to run some django management commands. I'm using the CronJob pod for this. My problem is this: I need to create the CronJob job with the same environment variables that the django pod was created with (DATABASE_, DJANGO_, and others), but don't see an easy way to do this. Any help would appreciate it. -
join two queries together as one - django
I am working on a django project and I want to basically create one query out of two queries that I was creating. I have a friends table that has the following columns user - friend - status - create ------------------------------- josh - omar - 1 - 1 steve - omar - 1 - 1 omar - tava - 1 - 1 I would create one query to grab records where the user is omar and another one to grab records where the friend is omar. is there a way to create a query that would combine the two queries like Grab all the records where omar is a friend or user and set them as one queryset object. -
Modify value of a Django form field during clean() and validate again
I want to do something like this: def clean(self): cleaned_data = self.cleaned_data self.data['cpf'] = re.sub("[\.-]", "", self.data['cpf']) clean_data_again_to_revalidate_the_field I want to change the field CPF to remove dots. After, I want to validate the field again. Is it possible? Also, the self.data['cpf'] receiving the value is not possible. it is failing with: This QueryDict instance is immutable. -
heroku django app no module named site
I'm trying to deploy my Django app to heroku, but I keep receiving an enigmatic 'ModuleNotFoundError: No Module Named lukasSite' -- lukasSite is the name of the website I'm working on. It's also the name of my project folder, and app, though I have some other folders named 'community.' I can't tell where this error is coming from, but I get it both when I try to run heroku local web and try to deploy my website to Heroku. Full error below: [OKAY] Loaded ENV .env File as KEY=VALUE Format 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18983] [INFO] Starting gunicorn 19.7.1 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18983] [INFO] Listening at: http://0.0.0.0:5000 (18983) 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18983] [INFO] Using worker: sync 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18986] [INFO] Booting worker with pid: 18986 21:33:09 web.1 | [2017-10-20 02:33:09 +0000] [18986] [ERROR] Exception in worker process 21:33:09 web.1 | Traceback (most recent call last): 21:33:09 web.1 | File "/Users/lukasudstuen/softwareProjects/lukassite/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 21:33:09 web.1 | worker.init_process() 21:33:09 web.1 | File "/Users/lukasudstuen/softwareProjects/lukassite/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 21:33:09 web.1 | self.load_wsgi() 21:33:09 web.1 | File "/Users/lukasudstuen/softwareProjects/lukassite/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 21:33:09 web.1 | self.wsgi = self.app.wsgi() 21:33:09 web.1 … -
How to read a file upload from the webpage by django?
This is the first time I develop a website project, and I don't have any experience in frontend and backend before. I've read Django's official tutorial and get some intuition about it, but I have to say frontend is such a horrible thing, I don't have time to learn it carefully because I have to finish the task before the end of this week. Here comes the problem. I have to read a file upload by any user from the webpage, the HTML code was written by other people in the lab like follow: <label>select a file &nbsp;&nbsp;&nbsp;&nbsp; <input id="photoCover" class="input-large" type="text" style="height:30px;"> <button class="btn1 btn-primary" onclick="$('input[id=lefile]').click();"><i class="fa fa-folder-open"></i>&nbsp;&nbsp;浏览&nbsp;&nbsp;&nbsp;&nbsp;</button> </label> I want to know how to process the file selected in the Django views. Here are my thoughts: 1.The selected file must be in some directory on the local machine, maybe I should directly get the path of that file. 2.Should I create a form to handle this problem? Is there anybody could give me a hand or some hints about how to solve this problem? any other resource is appreciated. -
Many foreign keys in a model, better way to do models?
I'm kind of new to django. While writing the models for an app I'm doing, I felt like I was doing something wrong because of all the foreign keys I was using for a single model (ticket model to be specific) My thinking at the beginning was that I wanted each Ticket to keep the information on it's creator, what team this ticket is assigned to and the comments made on the ticket. And other information that don't need foreign keys. Am I doing this right ? I dont know why, but I feel like there is a better way. class Team(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=2000) members = models.ManyToManyField(User, through='Team_members') def __str__(self): return self.name class Ticket(models.Model): name = models.CharField(max_length=200) creator = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) comments = models.ForeignKey(Comment, on_delete=models.CASCADE) #worker = models.ForeignKey(User, on_delete=models.CASCADE) *to be finished description = models.CharField(max_length=500) status = models.BooleanField(default=False) date_opened = models.DateTimeField('date opened') date_closed = models.DateTimeField('date closed',null=True, blank=True) def __str__(self): return self.name class Team_member: team = models.ForeignKey(Team) user = models.ForeignKey(User) date = models.DateTimeField('date joined') class Comment: text = models.CharField(max_length=2000) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.text -
Target WSGI script wsgi.py' cannot be loaded as Python module
I'm trying to scale my django project with AWS ElasticBeanstalk but i get an error, the error doesn´t appear when I deploy the proyect, but when I scale it I get this error: ValueError: Unable to configure handler 'file_log': [Errno 13] Permission denied: '/var/log/meatme/django.log' mod_wsgi (pid=4829): Target WSGI script '/opt/python/current/app/meatme/meatme/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=4829): Exception occurred processing WSGI script '/opt/python/current/app/meatme/meatme/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/meatme/meatme/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/lib/python2.7/site- packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/lib/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/python/run/venv/lib/python2.7/site- packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/lib64/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib64/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) I have this config files .ebextensions: commands: 00_create_dir: command: mkdir -p /var/log/meatme 01_change_permissions: command: chmod g+s /var/log/meatme 02_change_owner: command: chown -R wsgi:wsgi /var/log/meatme and wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meatme.settings") application = get_wsgi_application() When I do eb deploy it works perfect, but when i do eb clone 2 (to test scale) the new instance dont work. -
class: forms-control is not showing
I'm doing a Django App using Materialize. I am doing an app using ModelForms with form-control. When I run the app, the inputs don't appear. Everything works fine, just the input is not appearing. As you may see, the name of the fields are in Spanish (ignore that). forms.py: class UsuariosForm(forms.ModelForm): class Meta: model = Usuarios fields = ('Nombre', 'Apaterno', 'Amaterno', 'Telefono', 'Email', 'Passwd',) views.py: def user_create(request): context = {} NewUsuariosForm = UsuariosForm() # 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 NewUsuariosForm = UsuariosForm(request.POST) UserValid = NewUsuariosForm.is_valid() # check whether it's valid if UserValid: Usu = NewUsuariosForm.save(commit=False) Usu.Activo = True ID = Usuarios.objects.count() + 1 Usu.Usuarioid = ID Usu.save() return user_lists(request) context = { 'NewUsuariosFrom': NewUsuariosForm } return render(request, 'Usuarios/usuarios_form.html', context) # if a GET (or any other method) we'll create a blank form return render(request, 'Usuarios/usuarios_form.html', context) usuarios_form.html {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <div class="container"> <br> <h3 class="center pink-text"> Usuarios - Crear Usuario </h3> <br> <br> <br> <form method="post"> {% csrf_token %} <div class="form-group"> <div class="row"> <label for="Nombre"> Nombre: … -
about IDE, on clonning a github repository. issue: i require a "commit diff" to be cloned instead of the final project
I will explain my own problem so it is easier to understand. I have several books of Django, currently on Django Unleashed by Andrew Pinkham. On the sample project files you have this straightforward project https://github.com/jambonrose/DjangoUnleashed-1.8/ I managed to fork it to my github and clone it on Pycharm professional IDE through its VCS/checkout from version control/github, so I can do certain stuff like right click stuff and see where it leads to within the project etc... The issue I am finding, however is that when reading through the book as the code develops in each chapter, this code isn't saved in the whole parent branch divided by episodes, but it is instead saved as diff commmits, or steps of the process towards the final github project I, for example can link to certain commits as dju.link/a30e354253/organizer/views.py but when I fork this to my account, only the final project which is up gets to my profile and ends up being cloned. For example this final link to a commit I just put leads to a folder called blob which doesn't even exist when i look at the project ....github.com/jambonrose/DjangoUnleashed-1.8/blob/a30e354253/organizer/views.py While a search for blob or a30e354253 on jambonrose's project wont … -
Form not saving object a redirect to new form view
I am attempting to build an app the creates patient data, saves it, and displays it. Problem : When I populate the fields and click save it does not save the object and render data to the document object model. It reloads the page with the field data still in the fields. I am not sure what I have done wrong. The view, form and models code seem to be accurate. I welcome any useful assistance. Here is the code : models.py from django.db import models from django.contrib.auth.models import User from Identity import settings import datetime class Identity_unique(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) first_Name = models.CharField(max_length = 80, null = True ) last_Name = models.CharField(max_length = 80, null = True ) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) contact = models.CharField(max_length = 15, null = True) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView, UpdateView from nesting.forms import Identity_Form, Symptom_Form from nesting.models import Identity_unique, Symptom_relation class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_Form() Identities = Identity_unique.objects.filter(user = request.user) var … -
django-filters {{ field.label_tag }} not displaying but {{ field }} is
So I'm having a weird issue with Django-filters. I got them working a previous time but now they just aren't. I'm trying to split the fields in a for loop so I can have more control over the CSS of the label_tag. However, the label_tag isn't showing up. But the field itself is. I have absolutely no idea why. Perhaps somebody has some insight? filters.py from django.contrib.auth.models import User from django import forms from .models import Post, Comment, UserProfile, Question, Answer from university.models import University import django_filters class ClassFilter(django_filters.FilterSet): title = django_filters.CharFilter( lookup_expr='icontains', widget=forms.TextInput(attrs={ 'class': 'home_page_search', 'placeholder': 'Search by Class or University', 'id': 'list_of_post_search_box_id', 'autocomplete': 'off', }), ) university = django_filters.ModelChoiceFilter( queryset=University.objects.all(), widget=forms.RadioSelect(attrs={'class': 'list_of_class_university_filter_btn_input'}), empty_label=None ) class Meta: model = Post fields = ['title', 'university',] template {% for university in filter.form.university %} {{ university.tag }} # This is showing up fine {{ university }} # Showing up as well, I see my label tags perfectly {{ university.label_tag }} # Not showing up {{ university.label }} # Not showing up either {% endfor %} -
A lightweight django cart app
What's an up to date cart app for django that isn't years old and isn't a full blown framework? There seems to be no middle ground between something like oscar which I definitely don't need or something like satchless which I have no idea how to even start using. All I need is a cart app I plug in and I can process payments using django-payments. Essentially I just want to have a cart I can display on my site, which isn't really e-commerce, but users can create items they pay for and add them to a cart. So, the cart needs to be able to handle different model types and store the current items in the cart with the ability to remove them. I don't know how to roll my own solution for this. Hence, my question.