Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OpenEdx - AuthMissingParameter at /complete/edx-oidc/
I have installed docker devstack version of openedx ironwood.master release. When I click 'View My Records' button in profile page I got an error: AuthMissingParameter at /complete/edx-oidc/ Missing needed parameter state Request Method: GET Request URL: http://localhost:18150/complete/edx-oidc/ Django Version: 1.11.29 Exception Type: AuthMissingParameter Exception Value: Missing needed parameter state Exception Location: /edx/app/credentials/venvs/credentials/lib/python3.5/site-packages/social_core/backends/oauth.py in validate_state, line 88 Python Executable: /edx/app/credentials/venvs/credentials/bin/python Python Version: 3.5.2 Python Path: ['/edx/app/credentials/credentials', '/edx/app/credentials/venvs/credentials/lib/python35.zip', '/edx/app/credentials/venvs/credentials/lib/python3.5', '/edx/app/credentials/venvs/credentials/lib/python3.5/plat-x86_64-linux-gnu', '/edx/app/credentials/venvs/credentials/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/edx/app/credentials/venvs/credentials/lib/python3.5/site-packages', '/edx/app/credentials/credentials'] Server time: Sun, 12 Apr 2020 06:44:47 +0000 Please help me. Thanks. -
Why are class variables used in model classes?
I am learning django and reading other's code, as below: class Review(models.Model): RATING_CHOICES = ((1, '1'),(2, '2'),(3, '3'),(4, '4'), (5, '5'),) wine = models.ForeignKey(Wine, on_delete=models.CASCADE) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) comment = models.CharField(default="no comment", max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) Why are all these variables not defined in init as instance variables? They don't make sense as class variables. Right? -
Load Three JS model with gltf loader in Django
I am trying to load a Three JS model in a Django(3.0.3) app on a local environment. Template: <script> var address_to_model ="{% static 'models/matilda/scene.gltf' %}"; // Pass this variable to .js file </script> <script src="{% static 'js/matilda.js' %}"></script> matilda.js: var loader = new THREE.GLTFLoader( ); loader.load( address_to_model, function ( gltf ) { scene.add( gltf.scene ); }, undefined, function ( error ) { console.error( error ); } ); renderer.outputEncoding = THREE.sRGBEncoding; The page loads without any Django error and it shows the ThreeJS window which is working but the model is not loaded and in the Chrome error console, I get this error: GET http://127.0.0.1:8000/matilda/models/matilda/scene.gltf 404 (Not Found) I think it should not check this URL because I do not resolve it in urls.py and there is nothing in this address. It should load the model which is collected in the 'static/models/matilada' with collectstatic command. I check these links but they do not help: * Django {% static 'path' %} in javascript file * Correctly accessing django static files from external javascript * Django: External JS using framework doesn't load * https://pypi.org/project/django-js-urls/ -
Unsupported lookup 'product_name' for CharField or join on the field not permitted. Django Python ORM
When i click on the provided link it must show the products related to the particular shop but i get an error Unsupported lookup 'product_name' for CharField or join on the field not permitted. Please suggest on this product_name is the foreign key for ProductDetails and shop is the foreign key for Products this is the template <a href="{{shop.shop_slug}}"><strong>{{shop.shop_location}}</strong></a> This is views.py # first check to see if the url is in categories. categories = [c.shop_slug for c in Shop.objects.all()] if single_slug in categories: matching_series = Product.objects.filter(shop_name__shop_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Product.objects.filter(product_name__product_name=m.product_name) series_urls[m] = part_one return render(request=request, template_name='products/shop_products.html', context={"product_name": matching_series, "part_ones": series_urls}) products = [t.product_slug for t in Product.objects.all()] if single_slug in products: return HttpResponse(f"{single_slug} is a product") return HttpResponse(f"{single_slug} does not correspond") This is Models.py from django.db import models # Create your models here. # For shop in the beginning # class ShopType(models.Model): # shop_type = models.CharField(max_length=50) # shop_type_description = models.TextField() # def __str__(self): # return self.shop_type class Shop(models.Model): shop_name = models.CharField(max_length=50) shop_location = models.CharField(max_length=100) shop_opening_time = models.CharField(max_length=10) shop_slug = models.CharField(max_length = 20) # shop_type = models.ForeignKey( # ShopType, default=1, on_delete=models.SET_DEFAULT) shop_image = models.ImageField(upload_to='products', null=True, blank=True) shop_owner = models.CharField(max_length=100) shop_description = models.TextField() shop_added_date = … -
How to Fill Form with Data in DJango without Update
New to Django here. I have a link to a form in DJango. I use the CreateView to have the user enter the initial information. It all works great and the data is accurately saved to the database. My issue is this: I would like that same link to open the form (it's a one-to-one relationship) with the filled data so the user can see what they have previously entered and correct, edit or update as needed. The form currfently opens as a blank form so if the user has entered that information previously they are unable to see it. I cave researched get_or_create and update_or_create as well as a number of other topics, but can't seem to figure this out. This needs to be a user-friendly experience so multiple entires or clicking multiple buttons to access the data is not an option. How best can I implement this? -
Serializer Relations Doesn't Work in Django Rest Framework
I have two models in my application. Here is my code in models.py: from django.db import models class TblDivision(models.Model): strdivisionname = models.CharField(db_column='strDivisionName', max_length=35, blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'Tbl_Division' class TblPosition(models.Model): strpositionname = models.CharField(db_column='strPositionName', max_length=30, blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'Tbl_Position' class TblEmployee(models.Model): strname = models.CharField(db_column='strName', max_length=70, blank=True, null=True) # Field name made lowercase. stremployeeid = models.CharField(db_column='strEmployeeID', max_length=10, blank=True, null=True) # Field name made lowercase. bitactive = models.BooleanField(db_column='bitActive', blank=True, null=True) # Field name made lowercase. intdivision = models.ForeignKey(TblDivision, db_column='intDivision',related_name='division', on_delete=models.CASCADE) intposition = models.ForeignKey(TblPosition, db_column='intPosition',related_name='position', on_delete=models.CASCADE) class Meta: db_table = 'Tbl_Employee' This is my code in serializer.py: from rest_framework import serializers from .models import TblEmployee,TblDivision class DivisionSerializer(serializers.ModelSerializer): class Meta: model = TblDivision fields=['id','strDivisionName'] class EmployeeSerializer(serializers.ModelSerializer): division = DivisionSerializer(many=True, read_only=True) class Meta: model = TblEmployee fields=['id','strname','stremployeeid','intdivision','division'] And this my views.py: from .models import TblEmployee from .serializer import EmployeeSerializer,DivisionSerializer from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(["GET", ]) def api_list_employee_view(request): try: employee_list = TblEmployee.objects.all() except TblEmployee.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = EmployeeSerializer(employee_list, many="true") dataEmployee = serializer.data return Response(dataEmployee) I want to create a simple API that shows data from Employee model and its … -
Access cookies path in django
I am working on a django project where I can track the user from the cookies and the path of the website they are visiting. My question is that when I set the cookie, I have given a path attribute so that the cookie is valid for that path only. SO how can I access the path set in the cookie. Additionally if someone have any other ideas to implement this system then I'm open for suggestions. Thank you in advance. -
Django: unresolved import 'markdown'
Vscode raised a problem from this line: import markdown with unresolved import 'markdown'Python(unresolved-import) This is my env: Django 3.0.5 Markdown 3.2.1 Here I tried to integrate markdown into my blog app by creating a custom template filter. After most works done, the markdown wasn't taken into effect. I have checked the rest of my codes and they are pretty safe. The problem should lie in how to import markdown I think? Any ideas? -
Django REST Framework Error 500 when receive '&' (And Symbol)
I have been confusing with this bug, I give & symbol in json raw body and return Server Error 500. And then I removed it so it works very well. Is this code bug or Django bug ? The REST Server is not my own so I cannot show you the code. -
How to run a function in the background after my django website starts?
I have written an algorithm. And when I use python manage.py runserver, my website will run on the local server. Now I want to run my algorithm after python manage.py runserver. In other words, when I start the django website, I hope the algorithm will run in the background until it is completed. And I want to know if the algorithm is still running or the algorithm is complete. What should I do? Thanks. -
I'm writing a stock exchange for an online game. How do I ensure orders are executed in isolation, using Django and Postgres?
I'm writing an online game using Django, and I'm planning to use Postgres as the database engine. One of the features of the game is going to be a simulated stock exchange and commodity market. If User A says "I want to buy an apple for $50" and User B says "I want to sell an apple for $50", then those two orders should be matched with each other, causing User B to sell an apple to User A. However, I'm not sure how to ensure that order executions are isolated from each other and don't introduce inconsistencies. I haven't written any real code for this feature yet, but let's assume that the model classes look like this: class Account(models.Model): number_of_dollars = models.BigIntegerField(validators=[MinValueValidator(0)], default=0) number_of_apples = models.BigIntegerField(validators=[MinValueValidator(0)], default=0) class AppleOrder(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) price = models.IntegerField(validators=[MinValueValidator(0)], default=0) direction = models.IntegerField(choices=[(1, 'buy'), (2, 'sell')]) status = models.IntegerField(choices=[(1, 'open'), (2, 'canceled'), (3, 'filled')]) Certain web requests may result in the game searching for orders that match each other, and executing them. But how can I make sure that orders are executed correctly? Naively, I would want to do it like this: def execute_orders(buy_order, sell_order, price) # We assume that "buy_order" and … -
How do I update the django models on runtime?
I have a normal Django model. I want to give a certain user the ability to add custom fields. I want the model to update during runtime and the database migrations to apply and then the user can do regular CRUD operations. Example of a simple Model is class location(models.Model): AuotLocationID = models.CharField(max_length=200) LocationID = models.CharField(max_length=200) Name = models.CharField(max_length=200) The user should be able to add other model fields such as Postal Code, Population, etc. Also each instance of the model should be linked to each user. For example Bob may want to track certain fields for his location and John may want some other fields. Thank you for your help -
500 Error running Django, Apache2, PostGreSQL Ubuntu 18.04.3 LTS
Sorry if I seem lost, but I have very little experience deploying web applications and searching online isn't helping. As the title states, I am running Ubuntu, Apache2, PostgreSQL, and Django , -- and I repeatedly get error messages, most of which are either vague and/or have no clear solutions. Plus my ignorance on the specific interactions quicksands any attempt at finding a solution, so i will be very specific. Installations: - apache2 libapache2-mod-wsgi-py3 -- for python 3 - I can't remember if I installed django or if it automatically packaged with my PyCharm package. - PostgreSQL - works fine. The Application: - It is a cloud computing platform, so it needs to receive files, store files, and render files. - Works fine with Django's web server attached. - has static files and needs to write to a media folder settings.py: - DEBUG = True - WSGI_APPLICATION = 'example.wsgi.application' -DATABASES = 'default': 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'example', 'USER': 'example', 'PASSWORD': 'example', 'HOST': 'localhost', 'PORT': '', 000-default.conf ServerName FireAnts.localhost ServerAlias www.FireAnts.localhost DocumentRoot /var/www/FireAnts Require all granted WSGIDaemonProcess FireAnts python-path=/var/www/FireAnts python-home=/var/www/FireAnts/venv WSGIProcessGroup FireAnts WSGIScriptAlias / /var/www/FireAnts/FireAnts/wsgi.py ERRORS, per the log - Currently, i'm getting "No module named 'django'". - Frequently i get "populate" … -
Is it possible to create a new row in models.py for a list of items in django?
I'm trying to create a todo app, and I want to have a CharField in my models.py for each todo item. Here's my code right now: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) todo = models.CharField(max_length=1000, default='') def __str__(self): return f'{self.user.username} Profile' I want to make it so a new row in the database is created for each new todo. For example, there would be a row for one task, and another row for another task. How would I go about this? Thanks in advance! -
Django comment reply system not clearing textarea and loading scripts
I'm creating a Django comment and reply system but I am facing an issue when I comment I need to refresh the page for the jquery functions in 'post_comment' to work it seems the functions to not work without refreshing the page, also after using the modal to submit a comment I need to refresh the page for the text area to clear else it remains the same. This is my post_detail view: @login_required def post_detail(request, guid_url): data = dict() post = get_object_or_404(Post, guid_url=guid_url) comments = Comment.objects.filter(post=post,reply=None) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(False) reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment.name = request.user comment.post = post comment.reply=comment_qs comment.save() else: data['is_valid'] = False else: form = CommentForm comment_count = post.comments.count() context = {'post':post, 'form':form, 'comments':comments, 'comment_count':comment_count, } if request.is_ajax(): data['comments'] = render_to_string('home/posts/post_comment.html',{'comments':comments,'comment_count':comment_count},request=request) return JsonResponse(data) return render(request,'home/posts/post_detail.html',context) my post_detail.html {% extends "home/homepage/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content %} <style> .modal-body { min-height: calc(100vh - 510px); overflow-y: auto; } .post-border-div { border: 1px solid; opacity: 0.5; } button, textarea { outline:none !important; box-shadow: none !important; -moz-box-shadow:none !important; -webkit-box-shadow:none !important; } button:hover { opacity: 0.6; } </style> … -
Include choices with no records in grouped queryset
I'm trying to make a query in django grouping by a field with choices. I wanna get all choices values, algo choices with no records in the database. My model: CHOICES = ( ('new', 'New'), ('in_process', 'In process'), ('finished', 'Finished') ) class Task(models.Model): ... status = models.CharField(max_length=10, choices=CHOICES) My current query is: qs = Task.objects\ .values('status')\ .annotate(total=models.Count('status')) At this moment, I only have finished task in db, but I wanna get all choices values, with zero if it doesn't have records. Any idea? -
Django model shows up twice in all queries
I have three models like so: class Profile(models.Model): id = ShortUUIDField(primary_key=True, unique=True) class Bounty(models.Model): id = ShortUUIDField(primary_key=True, unique=True) creator = models.ForeignKey('Profile', related_name="bounties", on_delete=models.PROTECT) class BountyCompletion(models.Model): id = ShortUUIDField(primary_key=True, unique=True) profile = models.ForeignKey(Profile, related_name="bounty_completions", on_delete=models.CASCADE) bounty = models.ForeignKey(Bounty, related_name="bounty_completions", on_delete=models.CASCADE) url = models.URLField() So the idea is to have Profiles and Bounties, and the Profiles can create a bounty, then Complete as many bounties as they want, however many times as they want, each time they provide a different url. The problem is when I have two or more BountyCompletions with the same profile and bounty, and then I call either Bounty.objects.all() or profile_instance.bounties.all(), that bounty shows up twice (same id, same everything but it appears twice). I've tried setting it up like this as well as making the BountyCompletion table a through table for a manytomany from Profile to Bounty, but both have the same result. -
how can i call OneToOneField values in admin using list_display=[]
my model class user_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField() profile_created = models.DateTimeField(auto_now_add=True, auto_now=False) timestamp = models.DateTimeField(auto_now=True, auto_now_add=False) admin.py class UserProfileAdmin(admin.ModelAdmin): list_display = ['user','user.username','profile_created', 'timestamp'] admin.site.register(user_profile, UserProfileAdmin) it show the error: ERRORS: : (admin.E108) The value of 'list_display[1]' refers to 'user.username', which is not a call able, an attribute of 'UserProfileAdmin', or an attribute or method on 'testapp.user_profile'. how can i fetch another table values in Admin.py. -
how to server dynamic files in django?
I know there are many answer already, but unfortunately I failed to find a solution on them. Basically I am trying to serve image files stored at server|/srv/post/users/folder/PIMAGES/ACTIVE/image.jpg to client, but with the configuration I have in my settings.py file, I am getting an http 404 file not found error. my settings.py file: STATIC_URL = '/static/' MEDIA_ROOT = '/srv/post/' MEDIA_URL = '/post/' and then if I refer to http://127.0.0.1:8000/post/users/folder/PIMAGES/ACTIVE/image.jpg I just get 404 page not found. -
How to create chained select related in django admin list_filters
I use the great django suit as django admin dashboard. Otherwise, list filters will not be as select lists. Those select lists are strengthened with django's built-in RelatedOnlyFieldListFilter class which limits the select list elements. However, I couldn't achieve to make them chained selects, by which I mean that if one select has child selects, those children would show their list depending to parent. Continents (select list) --> Europe is selected Countries (select list) --> would show the countries within Europe and Italy is selected. Cities (select list) --> only Italian cities would show up, Rome is selected And as being the above selects are admin panel list filters, only the records related with Rome should be listed in admin edit list page. Possible? Did I tried any thing? Yes many things and I couldn't achieve so I am led to create an alternative edit page with vue. However, it has many other problems. -
When to use PyMongo vs MongoEngine in Django?
I'm working on a web app Project using Django with Mongo. But I'm Confused which one to approach. Should I use Pymongo or MongoEngine in Django. What is the purpose of both and when to use Pymongo & MongoEngine? -
Dealing GenericRelation and GenricForeignKey inside migrations
I have models with GenricForeigKey and GenericRelation fields. class Datasheet(models.Model): package1 = GenericRelation('PackageInstance') ... class PackageInstance(models.Model): content_object = GenericForeignKey() object_id = models.PositiveIntegerField(null=True) content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) .... I am migrating from another models, inside my migration I want to create new instance. for ds in Datasheet.objects.all(): pi = PackageInstance.objects.create(content_object=ds) However this fails TypeError: DesignInstance() got an unexpected keyword argument 'content_object' Additionally, ds.package1.all() will also fail. AttributeError: 'Datasheet' object has no attribute 'package1' How do I solve this? -
Django redirecting to detail page after creating post (FBV)
I am making simple blog right now. I am trying to redirect page after creating post. models.py from django.db import models from django.db.models.signals import post_delete from django.conf import settings from django.dispatch import receiver class FreeBoardPost(models.Model): title = models.CharField(max_length=100, null=False, blank=False) content = models.TextField(max_length=5000, null=False, blank=False) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title @receiver(post_delete, sender=FreeBoardPost) def freeboard_image_delete(sender, instance, *args, **kwargs): instance.image.delete(False) urls.py from django.urls import path from .views import FreeBoardListView, FreeBoardDetailView, create_freeboard_view urlpatterns = [ path("", FreeBoardListView.as_view(), name="freeboard"), path("<int:pk>/", FreeBoardDetailView.as_view(), name="freeboard_detail"), path("create/", create_freeboard_view, name="freeboard_create"), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import ListView, DetailView from .models import FreeBoardPost from .forms import CreateFreeBoardPost from users.models import CustomUser class FreeBoardListView(ListView): model = FreeBoardPost template_name = "bbs/freeboard/free_board.html" context_object_name = "free_board_list" def get_queryset(self): return FreeBoardPost.objects.order_by("-id") class FreeBoardDetailView(DetailView): model = FreeBoardPost template_name = "bbs/freeboard/free_board_detail.html" def create_freeboard_view(request, pk): post = get_object_or_404(FreeBoardPost, pk=pk) context = {} user = request.user if not user.is_authenticated: return redirect("login") form = CreateFreeBoardPost(request.POST or None) if form.is_valid(): obj = form.save(commit=False) author = CustomUser.object.filter(email=user.email).first() obj.author = author obj.save() return redirect("freeboard_detail", pk=post.pk) context["form"] = form return render(request, "bbs/freeboard/free_board_create.html", context) The views.py code gave me an error create_freeboard_view() missing 1 required positional argument: 'pk'. Is there way I can redirect … -
How can I see data from an already made mysql database on Django?
I'm new to Django and I am trying to use a mysql database created and filled with data by someone else I created a model with the same name as the table I want to get data from, my models is as follows class Study(models.Model): study_name = models.TextField(default='Unknown') description = models.TextField(default='Unknown') language = models.TextField(default='Unknown') number_of_years = models.IntegerField(default='0') database connected but when I go to admin I don't see the data there Please help me with this -
function detail view in django
For almost 5h I can't make detail view. My app name -movies My views: " def actor_view(request): actor_list = Actor.objects.all() context = {'actor_list': actor_list} return render(request,'movies/actor.html',context) def actor_detail_view(request,id): actorrr=get_object_or_404(Actor,id=id) context={ 'actorrr':actorrr, } return render(request,"movies/actor_detail_view.html",context) My model class Actor(models.Model): name = models.CharField(max_length=50) date_of_birth = models.DateField() age=models.IntegerField( null=True) net_worth = models.TextField(max_length=140, null=True) picture=models.URLField(default = '') children =models.TextField(max_length=140, null=True) marital_status=models.TextField(max_length=140, null=True) My actor html: {% load static %} {% block mainbody %} {% for actor in actor_list %} <!DOCTYPE html> <html> <head> <title>List of actors we have</title> <link rel="stylesheet" href="{% static 'css/style_actor.css' %}"> </head> <body> <div class="card" > <div class="card-image"> <img src="{{ actor.picture }}" alt="No poster in datebase" width="289" height="345"> </div> <div class="card-text"> <h2> <a href="/movies/actor_detail/{{actor.id }}">{{ actor.name }}</a> </h2> <p>{{movie.pilot}}</p> </div> <div class="card-imdb-score"> <p >Age: {{ actor.age }} </p> </div> </div> </body> </html> {% endfor %} {% endblock %} My actor_detail html <h6>TEST</h6> So I have no idea how to make urls and what to place in actor.html in href url.I've made many tutorials and still couldn't do it.