Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving user object to post Graphql/Apollo Vue
I am trying to save a user id to a new biz. I keep getting a 400 error and can not figure out why. I am using django for the backend with graphql and apollo client for the front with vue js. I am able to get the owner id but not able to save it for some reason. Create Biz Mutation Apollo export const CREATE_BIZ_MUTATION = gql` mutation CreateBizMutation($name: String!, $owner: ID!) { createBiz(name: $name, ownerId: $owner) { name } }` Create Biz mutation Django class CreateBiz(graphene.Mutation): id = graphene.Int() name = graphene.String() code = graphene.String() owner = graphene.Field(UserType) class Arguments: name = graphene.String() def mutate(self, info, name): user = get_user(info) or None code = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(6)) biz = Biz( code = code, name = name, owner = user ) biz.save() return CreateBiz( id= biz.id, name = biz.name, code = biz.code, owner = biz.owner ) Create Biz Component createBiz () { const owner = localStorage.getItem(DJANGO_USER_ID) if (!owner) { console.error('No user logged in') return } const { name } = this.$data this.$apollo.mutate({ mutation: CREATE_BIZ_MUTATION, variables: { name, owner } }).catch((error) => { console.log(error) }) } } -
Why do different Djano Models with JSONFields have the same values?
I've got a model with a JSONField (a Postgres only field): models.py: from django.db import models from django.contrib.postgres.fields import JSONField class Mod(models.Model): data = JSONField(default={ 'name':'Model' }) So I create 2 models – ./manage.py shell: >>> from m3d.models import Mod >>> m1 = Mod() >>> m1.save() >>> m2 = Mod() >>> m2.data['name'] = 'Model 2' >>> m2.save() But they have the same data['name'] values: >>> m1.data['name'] 'Model 2' >>> m2.data['name'] 'Model 2' Note that the values are different in the database: >>> m1a = Mod.objects.get(pk=m1.pk) # get m1 data from db >>> m1a.data['name'] 'Model' >>> m2.data['name'] 'Model 2' but the variable m1 still has the value Model 2. Am I missing something? Is this some sort behavior I'll need to work around? FYI: Using Django 2.0.1 -
Multiple Levels Of Inheritance Using Django Templates
I'm creating a Django project, where I want to use multiple levels of inheritance in my templates. E.g I want to do something like this: project_base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> Then in app_base.html I extend this. {% extends "project/project_base.html" %} {% block title %}Generic Title{% endblock %} {% block content %} <img src="/dir/sub_dir/image.jpg"> {% block app_content %} {% endblock %} {% endblock %} Finally I have my actual template {% extends app_base.html %} {% block title %}Specific Title{% endblock %} {% block app_content %} {% for obj in objects %} <a href="{{ obj.get_absolute_url }}">{{ obj.name }}</a> {% endfor %} {% endblock %} The problem that I have is that when I go to load that page I see a single heading from an entirely unrelated template, and not my list of hyperlinks. What's the correct/best way to have multiple levels of inheritance for my template files? -
Jupyter notebook gets stuck running Django shell
I set up a basic Django app, and wanted to us Jupyter notebook to run a Django shell, but when I enter !python.manage.py runserver MY.IP.HERE:8000, jupyter gets stuck running, and there is nothing returned. I tried going to http://MY.IP.HERE:8000, but there's nothing available. -
Execute Python Scripts In Apache WebServer
I have a problem when execute python scripts in apache. I config htttp.conf like <VirtualHost *:80> ServerName xhentai69.com ServerAlias www.xhentai69.com <Directory /var/www/xhentai69.com> Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec Options +ExecCGI DirectoryIndex index.py </Directory> AddHandler cgi-script .py ServerAdmin webmaster@localhost DocumentRoot /var/www/xhentai69.com ErrorLog /var/www/xhentai69.com/error.log #CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> and index.py #!/usr/bin/env python print('Content-type: text/html\n\n') print('Hello') When I access http://xhentai69.com, it show 500 Internal Server Error and in file log AH01215: (2)No such file or directory: exec of '/var/www/xhentai69.com/index.py' failed: /var/www/xhentai69.com/index.py End of script output before headers: index.py But when i change to name home.py and config again httpd.conf DirectoryIndex home.py, it work. Why? -
Including another QuerySet in a Django DetailView
I am trying to include a "Related Shows" section to my website when someone looks at a show on the website. How can I implement this in my single show page? views.py: class ShowDetailView(DetailView): model = Show slug_field = 'show_slug' def show_detail_view(request, show_slug): try: show_slug = Show.objects.get(show_slug=show_slug).prefetch_related('show_tickets').prefetch_related('show_sponsor') except Show.DoesNotExist: raise Http404("Show does not exist") -
How are Ajax/Fetch calls different on production server vs. runserver for Django app?
How things are working on my development runserver: I have a Django app that updates a progress html tag using Ajax requests (currently I am using POST but I have used GET successfully as well on my development runserver). Everything works great. The Ajax request calls a function in my view.py that returns a JsonResponse with the updated data from my business logic happening in views. I am using setInterval with setTimeout to control the number of calls and clearInterval when I reach certain values. Production deployment to Heroku: I am currently trying to deploy to Heroku and have been 99% successful. My template renders correctly, so I can see my page and submit the form for processing. The 1% problem here is that my Ajax requests are not getting updated data and I don't know why. It's like my Ajax requests are just getting the initialized variable values of zero and continue to return those values. I am console.logging the JSON returned from the Ajax call: {games: 0, progress: 0, percentage: 0} {games: 0, progress: 0, percentage: 0} {games: 0, progress: 0, percentage: 0} {games: 0, progress: 0, percentage: 0} This JSON just gets returned over and over again … -
File upload doesn't terminate in Safari
I'm running a test server under the latest Django 2 release (Python3.6) on Mac OS X. My applications seem to work well across both Safari 11.0.2 and Chrome (build 63) except for one anoying detail. I've got this file upload form: class BulkForm(AssemblyForm): # AssemblyForm itself defines a Char field. file = forms.FileField(required=True, label='Input file') That is handled by the following view (I've reduced it to the bare minimum for this example): def formtest(request): if request.method == 'POST': form = BulkForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] return HttpResponseRedirect(reverse('submissions')) bulk = BulkForm() return render(request, 'upload.html', {'bulk_form': bulk}) And the template: ... <div class="tab-pane fade" id="bulk"> <div class="container my-4"> <form role="form" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ bulk_form.as_p }} <button type="submit" name="bulk-form" class="btn btn-primary bg-dark"> Submit </button> </form> </div> ... In Safari the upload sometimes freezes even when I try the same file: sometimes it uploads successfully, sometimes it freezes. There is a correlation between file size and its chances to get stuck. To investigate this issue, I've implemented my own upload handler: class SizeLimitedUploadedFile(uploadedfile.UploadedFile): def __init__(self, name, content_type, size, charset, content_type_extra=None): file = tempfile.NamedTemporaryFile( buffering=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, delete=False, suffix=f'.upload.{name.split(".", 1)[1]}', dir=settings.FILE_UPLOAD_TEMP_DIR ) super().__init__(file, file.name, content_type, 0, charset, content_type_extra) self.error = None def … -
Django - Modifying string representation of User object globally (outside of admin, even) for use in Model Forms
My website has many ModelForms and whenever it has a Foreign Key property to the User model, the property displayed is username. How can I change that so that the representation is, instead, the user's full name (or something else)? I am preferably looking for a global solution, which will work for all model forms from here on, but I am not discarding a fix that involves customizing each form (rather than changing the model). I am working with a userprofile extension of the user model. The fix that I've tried so far is supplanting the str method in the user class. This is the snipped I have on the model class (taken from an entry of this forum, btw). This code is in the models.py file: #CUSTOMIZES REPRESENTATION OF USER def get_full_name(self): return self.first_name + ' ' + self.last_name User.add_to_class("__str__", get_full_name) Thank you! -
customizing mezzanine admin menu
I would like to make a Page type show in the left hand menu instead of the dropdown in pages. -
How do i put the django-mptt in nested dropdown
Hello guys I am really thinking hard on this one I need help. How do I put the django-mptt in a nested dropdown. the recursetree tag when I put it in a bootstrap dropdown it comes out all jumbled up. {% load mptt_tags %} <ul> {% recursetree category_list %} <li> {{ node.name}}</a> {% if not node.is_leaf_node %} <ul class="children"> <a href="{% url 'category_detail' id=node.id %}"> {{ children | lower}}</a> </ul> {% endif %} </li> {% endrecursetree %} </ul> -
Python by Example Book: url_patterns syntax deprecated
In setting up Login and Logout url patterns, the book (which I believe uses Django 1.8) cites: from django.conf.urls import url from . import views url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'), url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login',name='logout_then_login'), where login, logout and logout_then_login have corresponding .html files in the same app template/account directory. However, on Django 1.11, these give errors of: "TypeError: view must be a callable or a list/tuple in the case of include()" which I believe is because this syntax is now deprecated for 1.10 and above). Tried: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html')), url(r'^logout/$', auth_views.LogoutView.as_view(template_name='registration/logged_out.html')), url(r'^logout-then-login/$', auth_views.LogoutThenLogin.as_view(template_name='logout_then_login.html')), instead, but now getting "no reverse match" errors in my main "base.html" code, at the: <a href="{% url "login" %}">Log-in</a> line in: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %}class="selected"{% endif %}><a href="{% url "dashboard" %}">My dashboard</a></li> <li {% if section == "images" %}class="selected"{% endif %}><a href="#">Images</a></li> <li {% if section == "people" %}class="selected"{% endif %}><a href="#">People</a></li> </ul> {% endif %} <span class="user"> {% if … -
formset invalid django test
Can't understand what I'm doing wrong here and would appreciate some insight. been trying to figure it for a couple hours now. Test is simple. Just want to validate a formset. The form is invalid and shows errors for two of the attributes as per below. 1) 'account' is a foreignkey to another model. i have tried changing the values to match the PK for each account, i've tried changing the key to 'account_id', thinking i might have the wrong attribute. can't seem to make it work. 2) 'file' is a FileField, to which I'm passing the string of the file path, which isn't being recognized at all. I'm not sure if there's some different structure for file uploads that I am missing completely. Here is the output from formset.errors: [ { 'account': ['Select a valid choice. That choice is not one of the available choices.'], 'file': ['This field is required.'] }, { 'account': ['Select a valid choice. That choice is not one of the available choices.'], 'file': ['This field is required.'] } ] i found a handy helper function to put together the formset data here. The formset data looks like this: { 'form-INITIAL_FORMS': 0, 'form-TOTAL_FORMS': 2, 'form-1-account': 'RRSP' … -
Set the default value of a Model as superuser
I have the following abstract class: class UserStamp(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE) class Meta: abstract = True The Account Model inherits from it: class Account(MetaData): pass And I have a User Model with a FK to class User(AbstractBaseUser,PermissionsMixin): account = models.ForeignKey(Account, blank=True, null=True, related_name='owner',on_delete=models.CASCADE) I have the following error: django.db.migrations.exceptions.CircularDependencyError: This can be solved by adding later the FK, but in this case I need a default value for created_by for the Account. I don't want to use pk=1 as default, because is not safe, if use permissions change or is deleted. So, I need to set the default user, as the first superadmin. Take in consideration that I use a custom user model. -
unable to save data before saving models in django
i am trying to build a single custom registration form for companies, admin and staff, when i create my superuser my 'Account type' is 'admin' , but when i try registering as a company my 'Account type' is empty. i can set a default value in my model class, but i would like to add more different types of 'Account type' in future. i also dont want to have a dropdown for the field models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, account_type=None, password=None): if not email: raise ValueError('Email address is required') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, account_type = account_type ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name = first_name, last_name = last_name, account_type = 'staff', password = password ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name = first_name, last_name = last_name, account_type = 'admin', password = password ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=64) last_name = … -
Method in Django to display all attributes' values belonging to a created object?
Is there a certain method in Django which allows for retrieving/displaying all attributes' values belonging to an object created via Django? In Python shell, I used the following: print(p.first_name, p.last_name, p.software_name) p is the created object with the attributes first_name, last_name, software_name. I already created several models which were applied to a database mysql. However, I would like to learn of other ways to display such information. -
Consuming A Rest API in Django
Is it possible to create make a model field that consumes a REST API as a foreign key? I have two projects. The first project has this model in models.py from django.db import models from django_countries.fields import CountryField from django.urls import reverse class Currency(models.Model): name = models.CharField(max_length = 50) country = CountryField() code = models.CharField(max_length = 3) base = models.BooleanField() class Meta: ordering = ['code'] def __str__(self): return (self.code) def get_absolute_url(self): return reverse('currency_detail', args = [str(self.id)]) I have serialized the model with the following code in serializers.py from rest_framework import serializers from currencies . models import Currency class CurrencySerializer(serializers.ModelSerializer): class Meta: model = Currency fields = ('name', 'code') I created the following views.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from currencies . models import Currency from . serializers import CurrencySerializer def currency_list(request): currency = Currency.objects.all() serializer = CurrencySerializer(currency, many = True) return JsonResponse(serializer.data, safe = False) and provided the following in urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^currencies/$', views.currency_list), ] The url is passing the information ok in json format. There are no authentications (I am not good enough yet). when I use … -
Django: Intervention when raising errors when creating User via social authentication
I'm setting up social authentication with the package social-auth-app-django. I have the below ValueError raised when attempting to create a user when an email isn't supplied. users.py if not email: message = "Ooops, it doesn\'t look like an email was specified. If you are signing in via one of your social media account, please ensure there is an email address associated to your account." raise ValueError(message) It wasn't really necessary originally as I would handle the form validation on the front end with standard form validation. However, when integrating social sign-ins this causes an issue. In development this is great - but essentially at this stage I would like to fling the error back to an errors template which says that they must supply an email address. I believe on platforms, such as Twitter, a user can initially register without an email address associated to the account. That's where I spotted this conflict. Essentially, social-auth-app-django isn't throwing an error before this - so how at this point, do I send the user back to a specified template which I can build to handle such errors by passing them back via the context? Looking and looking through the documentation, I can't … -
'NewsImage' object is not iterable
models.py code fragment class Article(models.Model): title = models.CharField(max_length=150, verbose_name='Title') content = models.TextField() created = models.DateTimeField(auto_now=True, verbose_name='Create Date') slug = models.SlugField(primary_key=True, max_length=250, unique=True) summary = models.TextField(blank=True, max_length=250, help_text='Meta Description') img = models.CharField(max_length=10000, blank=True, null=True, default=None) tags = models.ManyToManyField(NewsTag, default=None, blank=True) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.title def get_absolute_url(self): return reverse('article', args=[str(self.slug)]) class Meta: verbose_name = 'Article' verbose_name_plural = 'Articles' class NewsImage(models.Model): article = models.ForeignKey(Article, blank=True, null=True, default=None, on_delete=False) image = models.CharField(max_length=10000, blank=True, null=True, default=None) is_main = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.article class Meta: get_latest_by = 'id' ordering = ['id'] verbose_name = 'Article Image' verbose_name_plural = 'Articles Images' views.py code def main(request): news_articles = NewsImage.objects.filter(is_main=True, is_active=True).latest('id') products_images = ProductImage.objects.filter(is_active=True, is_main=True) return render(request, 'landing/home.html', locals()) HTML file fragment <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image }}"> <div style="clear: both"></div> <span>{{ articles.article.title }}</span><div style="clear: both"></div> </a> <em>{{ articles.article.created }}</em> <div style="clear: both"><br></div> </div> {% endfor %} </div> <a href="" title="View More Articles"> <div id="btn"> <span>View More</span> </div> </a> </div> </aside> Trying to render html page gives error: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0 Exception Type: … -
How to apply upvote functionality with corresponding Model in Template?
I am developing a quora like app in Django but facing two problem.I want, in Question DetailView if user have not upvoted the answer then it will show the option of upvote and the total vote. Models.py https://paste.ubuntu.com/26333884/ {% extends 'base.html' %} {% block title %} {{ question.title }} {% endblock %} {% block body %} <h3><i>{{ question.title }}</i></h3> {{ question.description }} {% for answer in question.answer_set.all %} <br> <div> <p>{{ answer.answer_text }} <span style="font-size: 15px">by [{{ answer.user }}]</span></p> <form method="post" action="{% url 'answer:detail' question.id %}"> {% csrf_token %} <input type="hidden" name="type" value="vote"> <input type="hidden" name="answer_id" value="{{ answer.id }}"> {% for upvote in answer.upvote_set.all %} {% if upvote.user == request.user %} <input type="submit" class="btn btn-sm btn-warning" value="Downvote|{{ answer.upvote_set.all.count }}"> {% else %} {% if forloop.counter == 1 %} <input type="submit" class="btn btn-success" value="Upvote|{{ answer.upvote_set.all.count }}"> {% endif %} {% endif %} {% empty %} <input type="submit" class="btn btn-sm btn-success" value="Upvote|{{ 0 }}"> {% endfor %} </form> {% endfor %} {% endblock %} Template: https://paste.ubuntu.com/26334093/ from django.contrib.auth.models import User from django.db import models from django.shortcuts import reverse # Create your models here. class Question(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField() pub_date = models.DateTimeField() def __str__(self): return … -
Use django web app through Moodle
... I'm trying to access to my web app Django through Moodle, I tried: External Tool (LTI) External DataBase URL I'm looking for the simplest way ... the simplest is the URL, but it's poor in security. The main idea is to access to my Django web with the same Profile that the user have in Moodle. Some ideas?? Thank's for your time!!! -
No User matches the given query on django celery task
On my local, it is able to get the tasks and User model but when I have it in prod, rabbitMQ keeps giving me this error No User matches the given query, which is very weird. I suppose maybe I am missing django imports? but I am not sure. Here is what I have in the task. from celery import Celery sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) import django django.setup() from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User @app.task(name="get_photos") def get_photos(user_id, some_other_id, user_token): person = get_object_or_404(User, pk=user_id) #where user is the id The user Id does exists. I checked in the database. I checked type user_id it is an int. This task is getting called from an api. The api endpoint looks like this class UserProfileAPIView(APIView): """ Get username and return user profile """ # @cache_response(key_func='calculate_cache_key') def get(self, request, username): user = get_object_or_404(User, username=username) get_photos.apply_async((user.id, some_other_id, some_token), serializer='json') #also tried passing the user object. Didnt have errors but didn't process the task either. -
slug Django filed do we need this?
i am beginning with learn Django and get this data related "slug": A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL: https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug. why do we need this and how to use? -
Django rest ModelViewSet many-to-many create
I have my model relationships as following: A Reader will have a Wishlist and a Wishlist will have many Books: class Reader(models.Model): user = models.OneToOneField(User) ... # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) ... # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) # Record the date whenever a new book is added, it will be helpful for showing new arrivals when_added = models.DateTimeField(auto_now_add=True, blank=True, null= True) reader = models.ManyToManyField('Reader', related_name='wishlist') My serializers: class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' #depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library') def update(self, instance, validated_data): ... instance.which_library = validated_data.get('which_library', instance.which_library) instance.save() return instance def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() reader = Reader.objects.create(user=user, **validated_data) return reader class BookSerializer(serializers.ModelSerializer): wishlist = ReaderSerializer(many=True, read_only=True) class Meta: model = Book fields = '__all__' I can already perform CRUD operations with Reader, I want to now add books to a specific Reader's wishlist. My view: class ReaderViewSet(viewsets.ModelViewSet): serializer_class = ReaderSerializer def get_queryset(self): readers = Reader.objects.filter(which_library=self.kwargs.get('library_id')) return readers @detail_route(methods=['post']) def wishlist(self): return Response('OK') … -
Trigger model method on creation or field change
Assume, that I have this model in django: class Example(models.Model): name = models.CharField(max_length=100) number = models.IntegerField(unique=True) x = models.FloatField(null=True) y = models.FloatField(null=True) z = models.FloatField(null=True) v = models.FloatField(null=True) def get_z(self): z = x / y self.z = z self.save() def get_v(self): v = z * x self.v = v self.save() When I create an object with admin panel then I provide only name, number, x and y fields. I need to z and v field calculate automatically on object creation or whenever any of fields changes they value. For now it's working via making: z_value = property(get_z) and putting z_value in list_display in admin panel, then when I go there, values are saved.