Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement django session authentication in thrid party website?
Help me implement Django session based authentication in thrid party website. I'm building the javascript library that served from django server but client can place it in any website and think of this like google oauth popup where you click the login with google button and the popup will appear once you logged in popup will disappear and whenever you make the call server identifie as the authenticated request. Whatever I tried after the popup closed I can't able to make the authenticated request even though user is logged in when I browse it in the new tab. For your information I'm making this call using fetch credentials: include So far I've this in my settings.py file. I'm using django-cors-headers and I've these settings. CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True WHITENOISE_ALLOW_ALL_ORIGINS = True I need to know what settings should I adjust so that I can make the authenticated requests from another domain to django server. -
TypeError when redirecting to Django URL
Very simple one but cannot seem to find the issue : TypeError at /userlookup/foo userlookup() got an unexpected keyword argument 'username' views.py def userlookup (request, username): if request.method == "GET": UserId = User.objects.get(user=username).id UserPosts = Post.objects.filter(user=UserId) UserPosts = list(UserPosts.order_by("-timestamp").all()) p_all = Paginator(UserPosts, 10) page_number = request.GET.get('page') page_obj_all = p_all.get_page(page_number) return render(request, "network/userlookup.html",{ "page_obj_all": page_obj_all, "allposts": UserPosts, }) url.py path("user/<str:username>", views.userlookup, name="userlookup"), html (Properly looping, but shortening for visibility) (Some Stuff) <div class="card-body"> <h5 class="card-title" id="Username">{{ allpost.user }}</h5> <a href="{% url 'userlookup' allpost.user%}">{{ allpost.user }} 's profile</a> <p>User ID = {{ allpost.user.id }}</p> </div> (Some Stuff) Question : Why the error? I understand that allpost.user = foo. I pass "foo" to the URL called userlookup. The URL do accept a STR called username. My function then grab the username, fetch the data based on the username and (should) return "username/foo" with the relevant data. Hope you can help! -
Django: How to dynamically store user data in sessions?
I am trying to create different django-allauth signup forms for different types of users. So different forms for different user types. Once a user selects a user type (example: "I want to sign up as a vendor"), they should be redirected to a different form where they will fill up other signup and profile details before email confirmation and login. I have one signup form working, but not multiple. Currently I have a general purpose form assigned to users/accounts/signup/ but I also want a vendor specific signup form assigned to users/accounts/signup_vendor/. The best possible solution I've found is provided by the django-allauth author, stating: "There are multiple ways to approach this. You could store the desired user type into the session, and dynamically construct your form fields depending on that. Or, you could allow for the user to make up his mind at any time by simply adding a "profile type" to the sign up form. Basically, the fields in the signup form would have to be the union of all possible fields, and perhaps you would want to add some Javascript to dynamically show/hide some fields depending on the type chosen. I would recommend an approach where the user … -
Why Django Validates Multiple Forms
I have a settings template which includes different forms. When I submit a form and it is not valid, other forms are asigned as invalid and shows validation errors. What I want is showing error just for the form which is submitted. Is there a solution for this problem? Here is my code. I can share html and form codes if needed. user = request.user if request.method == "POST": edit_profile_info_form=EditProfileInfo(request.POST or None) edit_account_form=EditAccountForm(request.POST or None) context = { "profile_info_form" : edit_profile_info_form, "account_form" : edit_account_form, } if "profile_info_submit" in request.POST: if edit_profile_info_form.is_valid(): first_name=edit_profile_info_form.cleaned_data.get("first_name") last_name=edit_profile_info_form.cleaned_data.get("last_name") user.first_name=first_name user.last_name=last_name user.save() messages.success(request,"Changes saved") return redirect("user:settings") return render(request,"settings.html",context=context) if "account_submit" in request.POST: if edit_account_form.is_valid(): username = edit_account_form.cleaned_data.get("username") user.username = username user.save() messages.success(request,"Changes saved") return redirect("user:settings") return render(request,"settings.html",context=context) else: edit_profile_info_form=EditProfileInfo(initial{"first_name":user.first_name, "last_name":user.last_name}) edit_account_form=EditAccountForm(initial={"username":user}) context = { "profile_info_form" : edit_profile_info_form, "account_form" : edit_account_form, "password_form" : edit_password_form, "delete_form" : delete_account_form, } return render(request,"settings.html",context=context) -
django ArrayField PositiveSmallInteger admin multiple choice widget
I'm using PostgreSQL and I have the following model: STUDY_LANGUAGES = ( (1, "1st"), (2, "2nd"), (3, "3rd") ) class Test(models.Model): test_field = ArrayField(models.PositiveSmallIntegerField(), choices=STUDY_LANGUAGES, size=3, null=False) Because I used choices kwarg in the field's definition, I have a single select widget displayed on my admin site. I'd like to have a multi-selection widget. In order to do this, I tried all of the mentioned solutions in here and here but none of them works. I receive the following error. How could I achieve my goal? I'm using python 3.7 and django 3.1.5 Traceback (most recent call last): File "python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "python3.7/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "python3.7/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "python3.7/site-packages/django/contrib/admin/options.py", line 1656, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "python3.7/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, … -
Google map not showing in Django index html page
I am using django 3.0 and i have the index.html below. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- GOOGLE MAPS --> <script src="https://maps.googleapis.com/maps/api/js?key=KEY_HIDDEN&callback=initMap" async defer></script> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <script> // Initialize and add the map function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.036 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } </script> <title>Hello, world!</title> </head> <body> <h3>Map</h3> <div id="map"></div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script> --> </body> </html> This is just a test but google map is not rendering on the page. Is there something that i am doing wrong? i checked console.log, no Error message. Any help would be much appreciated. -
How i can to implement django like a admin site?
I have a implement project about collect data from anywhere in company. The description of project following these below. some user can be create "Collect Data Forms" for every employee in company to fill out infomation. UI for every employee look like admin page such as table and "Add Button" and pagination every employee have seen data of themself only,but owner (The user who created the form)will see all data from every employees. The index page must show all forms. and I would like the form to be show only user who have permission. def get_app_user_list(request): app_list = admin.site.get_app_list(request) for app in app_list: for model in app['models']: model['model_name'] = model['admin_url'].split("/")[-2] return app_list class IndexList(View): def get(self, request): context = { "app_list" : get_app_user_list(request) } return render(self.request,'collectdata/index_list.html',context) I stuck in views.py when pass parameter to view. a parameter is a string of model. i don't know how to match between string and model. class TableList(View): def get(self, request,model_name): context = { "model_name" : model_name, "table" : XXXXXXX.objects.all() } return render(self.request,'collectdata/table_list.html',context) It seems to be a problem in this below path("",IndexList.as_view(),name="index") path("<model_name>/list/",TableList.as_view(),name="list") path("<model_name>/add/",View.as_view(),name="add") path("<model_name>/view/<di>",View.as_view(),name="view") path("<model_name>/edit/<id>",View.as_view(),name="edit") path("<model_name>/delete/<id>",View.as_view(),name="delete") This project will does not use django admin site for some reson. If you have the … -
django_countries not discovered by django in installed apps
Seems I'm following the instructions, but somehow Django doesn't see django_countries as an app. Error: System check identified no issues (0 silenced). February 18, 2021 - 23:56:01 Django version 3.1.4, using settings 'django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/run/media/fv/hdd-1/PROJECTS/django-receipes/django_template/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: (WSGI stuff...) settings.py: INSTALLED_APPS = [ 'django_countries', 'registration.apps.RegistrationConfig', ..... Project tree: . ├── db.sqlite3 ├── django_project │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── myapp │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── readme.rst ├── registration │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── requirements.txt ├── static │ … -
Django REST Framework PDF Generation
I am currently developing the back-end for a mobile application using Django REST Framework. The app has a feature where the user can request a pdf report. I am not sure whether to use ReportLab to generate the report or to create an html template and then convert that to a pdf. -
Django Channels - Duplicates with consumers on multiple servers with load balancer with separate redis server
Issue concerns duplicate messages received thanks to having multiple Django servers, with django channels consumers, accessing a separate redis server. I am running 2 identical instances of my Django server with a load balancer. The channels consumers in these servers access a separate redis server. The issue is that currently I am receiving duplicate messages as I think each consumer is separately fetching from redis and sending to the destination. (If I turn one of the servers off my duplicate messages go away). Wondered what the common / best solution to this was? One thought was trying to target different databases redisurl/0, redisurl/1 for each server ... however this raises issues as I don't know to which one my load balancer will direct traffic for other parts of the application. Thoughts appreciated hahah! Using: Django 2.2 Channels 2.4.0 Channels-Redis 3.1.0 Redis 6 -
Django pagination by date (week)
I am making a website that displays this week's soccer games from the day you open the website to six days later (current week), and i want to paginate by date. example <previous> <19 feb - 25 feb> <next> then when i press next <previous> <26 feb - 4 march> <next> in views.py. matches is a list of dictionaries, each dictionary is a single game that contains the date of the game and other info and its sorted by date def home(request): start = datetime.now().date() end = today + timedelta(6) matches = request_games(today, after_week) return render(request, "sporty/home.html",{ "matches": matches, "start" : start, "end": end }) in home.html {% for match in matches %} //match info {% endfor %} -
Django Logging: Output all Logger messages to a file
I'm trying to do some debugging and cannot figure out how I can get all the usual server output that I would normally get on a development server. Here's my logging file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'catch_all_logger': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'somelogfile.log'), }, }, 'loggers': { 'django': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.server': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.security.DisallowedHost': { 'handlers': ['catch_all_logger'], 'propagate': True, }, 'django.security.csrf': { 'handlers': ['catch_all_logger'], 'propagate': True, }, }, } When I do cat somelogfile.log, I get almost useless information: Bad request: /url/where/bad/request However, the documentation says that django.server for instance will show status code and a message with it as extra context on the INFO level with HTTP 5XX as ERROR and 4XX as WARNING. Do I have the logging level setup incorrectly? Would love some guidance as I'm puzzled. -
Multiple Values into initial form data
I am attempting to render a form which will have certain fields prefilled based on the Primary Key. Im currently only able to successfully prefill one field (Project). Do I have to define all the other fields in my view? This is my Model class Document(models.Model): DOC_TYPE = ( ('Proposal', 'Proposal'), ('Invoice', 'Invoice'), ('Receipt', 'Receipt'), ('Other', 'Other') ) docName = models.CharField("Document Name", max_length=1000, null=True) docType = models.CharField("Document Type", max_length=10, null = True, choices=DOC_TYPE) company = models.ForeignKey('project.Company', on_delete=models.PROTECT, blank = True, null = True) customer = customer = models.ForeignKey('customer.Customer', on_delete=models.PROTECT, null = True) project = models.ForeignKey('project.Project', on_delete=models.PROTECT, blank = True, null = True) docFile = models.FileField("Document", upload_to='newdocuments/') note = models.TextField("Note About Document", blank = True, null = True) dateUpload = models.DateTimeField(auto_now_add=True) This is my View def ProjectAddDocument(request, pk): project = Project.objects.get(id=pk) form = ProjectAddDocumentForm(initial={'project':pk}) if request.method == 'POST': form = ProjectAddDocumentForm(request.POST) if form.is_valid(): form.save() return redirect('file_list') context = {'form':form} return render(request, 'project/adddocument.html', context) This is my URL path('adddocument/<int:pk>/', views.ProjectAddDocument, name='proj_document'), This is my Form class ProjectAddDocumentForm(ModelForm): class Meta: model = Document fields = ['docName', 'docType', 'company', 'customer', 'project', 'note', 'docFile'] -
How to validate and redirect on fail in CreateView get
I am trying to do some sanity checks in a CreateView get request and want to redirect user to a different URL in case the sanity checks fail. How can I achieve this? For example: class JobCreateView(LoginRequiredMixin, CreateView): model = Job form_class = JobFormClass # This does not let me redirect on return since a dictionary return is expected and redirect is not acceptable def get_context_data(self, **kwargs): if not self.request.user.is_superuser: messages.add_message( self.request, messages.ERROR, _("You are not authorized! Bugger off!") ) return redirect("home") # The user is good to proceed return super().get_context_data(**kwargs) This gives me back the following error: context must be a dict rather than HttpResponseRedirect. I am using get_context_data because I don't know what to use to be honest. Feel free to suggest something better. My use case in not really a super user check, that just felt like a better example -
Best practice for saving new model instance in Django Rest Framework
I'm new to DRF and I can't wrap my head around where to save new model instances when I POST to my endpoints. I need to overwrite my def create() method because I'm managing nested objects in my queries. I've noticed that I can save new instances from the model Serializer ( def create(self, validated_data)) but also from the associated class view ( def create(self, request)) What's the best practice here? I'm pretty sure I'm confusing major concepts, please indulge me! -
I try to build Follow system, I have error when i try to get the pk of the vested account
I try to build follow system in Django, My code Filed when I try to get the pk of the current vested account which I try follow them The Error message NoReverseMatch at /account/3/ Reverse for 'add-follower' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/follower/(?P[0-9]+)/add$'] my models class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="follow") My views class AddFollwers(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): account = Account.objects.get(pk=pk) account.following.add(request.user) return redirect('account', pk=account.pk) The urls urlpatterns = [ path('<int:user_id>/', account_view, name="view"), path('follower/<int:pk>/add', AddFollwers.as_view(), name='add-follower'),] The Template <form action="{% url 'account:add-follower' pk=pk%}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-success">Follow</button> </form> -
Heroku Django APScheduler not releasing memory after job completes
I have a django site that is running some heavy computational stuff that is scheduled with APScheduler hosted on Heroku. Everything is working as intended however Heroku is throwing error "Error R14 (Memory quota exceeded)" I have found other posts similar to this, link, issue but they are outdated and I haven't been able to get them to work. My code is listed below. I want this to run Mon-Fri between the hours of 800 and 1600. I am using heroku's PostgreSQL database. Eventually memory usage will get so high it will crash and restart. sched = BlockingScheduler( executors={ 'threadpool': ThreadPoolExecutor(max_workers=1), 'processpool': ProcessPoolExecutor(max_workers=1) } ) @sched.scheduled_job('cron', minute='*/30', day_of_week='mon-fri', hour='8-18', max_instances=1, id="server", executor='threadpool') def _server(): print('Start server') server = Server() server.get_stocks() del server gc.collect() sched.start() I know this is leaking memory because this clock.py memory usage before the server starts. This is after the server has done its' work and rests. If anyone can point me in the right direction I am open to trying anything. Thank you in advanced. -
ModelForm and using a specific queryset
I am creating a form for a model, one of the fields of the model is a ForeignKey. I want the options of the ForeignKey to be the ones related to that instance of the model. to make it clearer, here is some code: views.py def AddOrderDetail(request, pk): Product = Products.objects.get(ProductID=pk) order = Orders.objects.last() locations = Product.productqtys_set.values_list('Sublocation', flat=True).distinct() form = OrderDetailForm(request.POST or None) forms.py class OrderDetailForm(forms.ModelForm): class Meta: model = OrderDetails fields = ( ... 'Location', ... ) now I want the data retrieved from the query that I am performing in the view: locations = Product.productqtys_set.values_list('Sublocation', flat=True).distinct() to be the data that the user can select from while selecting the location of the OrderDetail. Moreover, I have another problem. I want to initialize some fields, I tried using the initial={} while defining the form in view, as shown below: form = OrderDetailForm(request.POST or None, initial={"ProductCode": Product, "OrderID": order, "Location": locations}) but when I do that I get the following error, 'OrderDetailForm' object has no attribute 'ProductCode'. I tried another way in the Function in the view.py file which is the following: form.fields['ProductCode'].initial = Product form.fields['OrderID'].initial = order but sadly, I still get the same error 'OrderDetailForm' object has no … -
Changing the import statement of a 3rd party app
I've a django application where I'm importing a 3rd party app. The app is written for python3, however my application environment is python 2.7 and django 1.11.16 . The 3rd party app works very well with python2 except for one line in the beginning. One of the file of the 3rd party app contains this: from urllib.parse import urlencode, quote . If I change this line to from urllib import urlencode, quote in the virtualenv, it works perfectly, however this is a very bad solution. I don't want to fork the whole application, but is there any other way for the workaround? -
Test webhook error: TLS failure - Stripe connection problem with Django API on Google App Engine
I try to send a test event to a webhook endpoint to my Django Stripe endpoint path('stripe/', views.StripeView) however I get an error Test webhook error: TLS failure. There is no more information and just link to ssllabs when my website has B overall rating. When I was using local testing with stripe listen --forward-to localhost:8007/stripe/ everything was working properly. All my certificates which are set on Google App Engine with flexible environment seems to be working properly. I thought that maybe the problem is associated with CSRF therefore I removed GenericAPIView and I added decorator @csrf_exempt in accordance to the Stripe documentation however it still does not work. Does anyone have an idea how can I solve this problem? @require_POST @csrf_exempt def StripeView(request): # serializer_class = StripeSerializer # def post(self, request): payload = request.body try: sig_header = request.META['HTTP_STRIPE_SIGNATURE'] except: return HttpResponse(status=400) ... -
How to make choosing group in admin.py mandatory?
In admin.py, I am adding groups as fieldset to one of my model. fieldsets = ( (None, {'fields': ('username', 'first_name', 'last_name', 'email',)}), ('Permissions', {'fields': ('groups',)}), ) The issue I have is that I do not know how to make choosing them mandatory - user can be in each or both of them, but cannot be blank. How can I force it, to ensure that user added will be in a group? -
Django migration is not changing database in AWS Elastic Beanstalk
I have deployed my Djnago app using AWS Elastic Beanstalk. I have added some data and everything was working fine. Then I have increased max_length of one of the CharField in model.py. I have deployed the app again using 'eb deploy' command. But it did not increase the field length in database. If I try to add subject_id greater than 10, I get this error: django.db.utils.DataError: value too long for type character varying(10) Model.py: class Subject(models.Model): #subject_id = models.CharField(max_length=10, blank=True) subject_id = models.CharField(max_length=50, blank=True) 0001_initial.py: #Generated by Django 3.0.4 on 2021-02-18 18:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'),] operations = [ migrations.CreateModel( name='Subject', fields=[('subject_id', models.CharField(blank=True, max_length=50)),],),] I have added migration command in .ebextensions/django_build.config file. The 0001_initial.py file inside migration folder shows the changes. But it is not updated in the database(AWS RDS postgresql). I have checked django_migrations table in postgresql database. It's showing the last migration happened when I first created the instance. I need to change subject_id field length of Subject model in existing database. Any help will be appreciated. .ebextensions/django_build.config: container_commands: 01_create_log_folder: command: "mkdir -p log && chown webapp:webapp -R log" 02_source_env: command: "source /etc/profile.d/sh.local" leader_only: true … -
Got AttributeError when attempting to get a value for field `content_object` on serializer `ProjectActionSerializer`
The serializer field might be named incorrectly and not match any attribute or key on the Activity instance. Original exception text was: 'Activity' object has no attribute 'content_object'. These are the Serializers I used class ProjectVoteSerializer(serializers.ModelSerializer): class Meta: model = Activity fields = ( 'voter', 'created', 'id', ) class ProjectActionSerializer(serializers.ModelSerializer): content_object = GenericRelatedField({ Activity: ProjectVoteSerializer(many=False) }) class Meta: model = ActivityObject fields = ( 'id', 'content_object', ) These are the models: class ActivityObject(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Activity(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, related_name='vote_project') comment = models.OneToOneField(ProjectComment, on_delete=models.CASCADE, related_name='vote_comment',null=True) voter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='voted_by') UP_VOTE = 'U' DOWN_VOTE = 'D' ACTIVITY_TYPES = ( (UP_VOTE, 'Up Vote'), (DOWN_VOTE, 'Down Vote'), ) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) created = models.DateTimeField(editable=False, db_index=True) modified = models.DateTimeField(db_index=True, default=timezone.now) activity = GenericRelation(ActivityObject) class Meta: unique_together = ['project', 'voter'] API views.py print(project_votes) This is the output data before serializing <QuerySet [<Activity: Activity object (12)>, <Activity: Activity object (10)>]> Getting error at this line when serializing project_votes_serializer = ProjectActionSerializer(project_votes, many=True, context={"request": request}) -
How to Preserve White Space and line breaks in Django?
I am making a project where I want to display a user's code. I am using Django's forms. But when I post that form, the form doesn't preserve the white space and the line breaks. Can you please help me? # this is my form class VigenereCipherDiscussForm(forms.ModelForm): class Meta: model = VigenereCipherDiscuss fields = ['text', 'share'] widgets = { "text": forms.Textarea(attrs={"class":"form-control", "rows":4}), "share": forms.Textarea(attrs={"class":"form-control", "rows":5, "placeholder": "Put in your cipher text or code in here to share with others"}) } # (stackoverflow preserves the line breaks, the "class Meta" is indented nicely) If i have this code: x = 2 if x == 2: return "2" else: return None # I want this code to be outputted in the form the way it is right now! But django gives me x=2 if x==2: return "2" else return None -
Queryset filter by variable that's in another queryset
I am trying to filter a queryset by a variable in another queryset that hasn't been set yet. I know it sounds confusing so let me show you. Views.py def ViewThreadView(request, thread): posts = Post.objects.filter(post_thread=thread) thread = Thread.objects.get(pk=thread) form_class = QuickReplyForm thread_name = thread.name return render(request, 'thread/viewthread.html', {'thread': thread, 'posts': posts, 'thread_name': thread_name}) As of now, if I want to access the post author in the template, I'd do this {% for post in posts %} post.author {% endfor %} My question is, how do I access the tables of post.author. So if I want to filter how many posts that author has, I want to do something like user_posts = Post.objects.get(author=post.author). But that can't work in the views because "posts" is a queryset and not a value. How can I do this?