Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relating OnetoOneField inside the views
I have 4 models, Patient,MedicalInfo,InsuranceInfo and RelativesInfo... the last three models are being related to the Patient model through a OnetoOne field, and the form for each of these is shown in a single template, when filling the form each of their info is uploaded to the database, However when entering through the admin interface and entering each of the last three models mentioned before there is no user assigned to that field, it just opens up a dropdown menu to choose which patient you want to assign that information, i will show you the code i've written and please help me telling me what i am doing wrong. Models class Patient(models.Model): Codigo = models.CharField(max_length=20,default=None,null=False) Nombres = models.CharField(max_length=100,null=False) Apellidos = models.CharField(max_length=100,null=False) Fecha_Nacimiento = models.DateField() Numero_Telefonico = models.CharField(max_length=200,default=' ') Email = models.CharField(max_length=256,unique=True,blank=True,default=' ') Genero = models.ForeignKey(Gender,on_delete=models.DO_NOTHING,default=None,null=True) Nacionalidad = models.ForeignKey(Nationality,on_delete=models.DO_NOTHING,default=None,null=True) Estado_Civil = models.ForeignKey(CivilStatus,on_delete=models.DO_NOTHING,null=True) Ocupacion = models.CharField(max_length=200) Lugar_de_Procedencia = models.CharField(max_length=200) Lugar_de_Residencia = models.CharField(max_length=200) def __str__(self): return self.Nombres + ' ' + self.Apellidos class MedicalInfo(models.Model): Expediente = models.CharField(max_length=500,blank=True) Sangre = models.ForeignKey(BloodType,on_delete=models.DO_NOTHING,default=None,null=True) Peso = models.FloatField() Estatura = models.FloatField() Paciente = models.OneToOneField(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) class InsuranceInfo(models.Model): Seguro = models.ForeignKey(InsuranceCompany,on_delete=models.DO_NOTHING, default=None,blank=True,null=True) Tipo_de_Poliza = models.ForeignKey(Policy,on_delete=models.DO_NOTHING,default=None,blank=True,null=True) Numero_Poliza = models.IntegerField(default=None,blank=True,null=True) Vencimiento = models.DateField(default=None,blank=True,null=True) Paciente = models.OneToOneField(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) class Relatives(models.Model): Parentesco = models.ForeignKey(Family_relation, on_delete=models.DO_NOTHING,default=None,blank=True,null=True) … -
Setting up Docker, Django, React app with CI/CD
I'm currently setting up a Django (backend) , React (frontend) app using Docker. I'm using Dockerfiles in the respective directories, and then building the project with docker-compose.yml. I'd like to set up CI/CD to push my app to production for my Github repository, but I'm not entirely sure the best way to approach it as I wanted to use Docker in production as well. Do I need to serve my apps together in a production environment or separately? Could I use another docker-compose (docker-compose.prod), a dockerfile, or is there a better way to approach it? What are the best practices? I was thinking about trying to use Github actions or Travis CI. Any help or guidance would be appreciated! -
I'm studying Django, but I don't understand that part
Good morning. The content of the blog below is 1.x version, so I am working on a 3.x version, but it is not blocked. It looks like an url pattern error when I saw it, but please tell me what went wrong. site : https://matthewdaly.co.uk/blog/2012/03/24/yet-another-tutorial-for-building-a-blog-using-python-and-django-part-3/ Git Repositories : https://github.com/ankiwoong/django_blog_tutorial \blogengine\models.py from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField() text = models.TextField() slug = models.SlugField(max_length=40, unique=True, allow_unicode=True, null=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('getPost', kwargs={'year': self.pub_date.year, 'month': self.pub_date.month, 'day': self.pub_date.day, 'slug': self.slug}) \blogengine\urls.py from django.urls import path, re_path from . import views appname = 'blogengine' urlpatterns = [ path('', views.getPosts), path('<int:selected_page>/', views.getPosts), path('<int:year>/<int:month>/<int:day>/<str:postSlug>/', views.getPost, name="getPost"), ] \blogengine\views.py from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage from blogengine.models import Post def getPosts(request, selected_page=1): # Get all blog posts posts = Post.objects.all().order_by('-pub_date') # Add pagination pages = Paginator(posts, 5) # Get the specified page try: returned_page = pages.page(selected_page) except EmptyPage: returned_page = pages.page(pages.num_pages) # Display all the posts return render(request, 'posts.html', {'posts': returned_page.object_list, 'page': returned_page}) def getPost(request, postSlug): # Get specified post post = Post.objects.filter(slug=postSlug) # Display specified post return render(request, 'posts.html', {'posts': post}) \templates\posts.html <html> <head> <title>My Django Blog</title> </head> <body> … -
I can't do this Django correlated query
So my problem is the same as this one https://stackoverflow.com/questions/17038193/select-row-with-most-recent-date-per-user/17038667#= Its working very great on MYSQL (emphasis on mysql because I can't use DISTINCT ON) there. I was wondering how I could convert this to a Django ORM statement. -
How to convert a list to tuple without manually [closed]
Instead of doing this manually like appending the tuple one by one.Is there any other way? -
What happen to the request arg in django class based views?
how can i acces the request in a generic built-in class bassed view? im pretty new to the frame work and i don't fully understand how to access my request, reading code (and copy-pasting) i handle to access the request via def's like above: def dispatch(self,request,*args,**kwargs): if request.user.is_authenticated: return HttpResponseRedirect(self.get_success_url()) else: return super(UserSapLoginView,self).dispatch(request,*args,**kwargs) but then i'm not sure how to handdle the next idea: i have a book model form and i need to initialize the user field to the one user loged on, and hide the field in the form. My view looks like: class BookUpdateView(UpdateView): template_name = 'book/book_update.html' form_class = BookModelForm(initial={'user': request.user}) queryset = Book.objects.all() def form_valid(self, form): return super().form_valid(form) def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Book, id=id_) forms.py like: user = forms.ModelChoiceField(queryset=UserSap.objects.all(), label="Autor", empty_label="Seleccionar autor principal", widget=forms.MultipleHiddenInput( attrs={ "class": "my-selectpicker form-control", "data-style": "btn-outline", "multiple data-live-search": "true", "data-max-options": "1", "data-size": "5", "data-live-search-normalize": "true", "id": "id-select-user"})) The forms rigth now have a lot of code because i was not hidding the field so far. i alredy tried initializing the field using javascript and hidding the input in the template with {{form.user.as_hidden}} but that way raises an error (user field is requiered) my apologies about my bad english i'm desperate … -
How to update class variables when a function is called by map()
I need to update my class variable, but when i use map() it is not getting updated Here is my code class HomeworkDashboardModule(): def get_student_hw_details(self, st): ----doing some stuff --- # updating submission value self.totally_submitted = self.totally_submitted + 1 def getPartiallySubmittedHW(self, students): self.totally_submitted = 0 map(self.get_student_hw_details, branch_students) print("Total submission = ",self.totally_submitted) output: Total submission = 0 # i am getting the inital value If i convert to a list(map(...)) then the value gets updated but the excution is too slow. -
Jumbotron background image not working. What am I doing wrong?
So I'm not sure what I'm doing wrong here. Tried a couple different things and if I manually pug in my photo through my html where Jumbotron is, my pictures does load, although with padding which I don't want AND it's not in the background. I don't understand what I am doing wrong here. I tried two different ways and neither of those work. Only thing that works is doing img src= straight into the Jumbotron section but like I said that's what I want. So what am I doing wrong here? home.html/styles .JumboHeaderImg{ background-image: url("/Users/papichulo/Documents/DatingAppCustom/dating_app/static/images/jumbo.jpg"); } .JumboHeaderImg{ background-image: "{% static 'images/jumbo.jpg' %}"; home.html/jumbotron <div class="jumbotron JumboHeaderImg"> -
django : Failed to save object in database
First of all I should mention that I'm new to Python as well as Django. i tried to follow instruction from here my models.py contains following : from django.db import models from django.contrib.auth.models import User class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics',on_delete=models.CASCADE) starter = models.ForeignKey(User, related_name='topics',on_delete=models.CASCADE) class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) updated_by = models.ForeignKey(User, null=True, related_name='+',on_delete=models.CASCADE) def __str__(self): return self.name then, when i tried to save it with board.save(), this error messages appears: Traceback (most recent call last): File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: board_board.name The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base updated = self._save_table( File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/models/base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/models/base.py", line 924, in _do_insert return manager._insert( File "/home/rierii/Applications/ProjectPython/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, … -
Django Rabbitmq and Celery issues
I installed RabbitMQ on Windows 10, fist Erlang then RabbitMQ. My book says that after that i launch RabbitMQ with this command in the shell: rabbitmq-server but it says bash: rabbitmq-server: command not found (im using git bash on w10) i couldnt make it work but i suposed that if i open Start and run the "RabbitMQ service - start" it was okay to work...(idk if its like that) Then the book tells me to add Celery to my project, this is the code in celery.py inside myshop directory (the instructions said "Create a new file next to the settings.py file of myshop and name it celery.py", idk why it says "next to settings.py" instead of only create celery.py, so may b im missing something): celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Then it says "You need to import the celery module in the init.py file of your project to make sure it is loaded when Django starts. Edit the myshop/init.py file and add the following code to it:" from .celery import app as celery_app Next it says "Adding asynchronous tasks … -
I have an error in django with the command manage.py makemigrations
enter image description here And this is the models that I have of the project: enter image description here enter image description here -
How to solve django error: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
I am using Django 3+... I am trying to render a template of the blog on my page, but I am receiving a error: Internal Server Error: /postsblog Traceback (most recent call last): File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: posts/blog.html, posts/post_list.html [13/May/2020 22:57:09] "GET /postsblog HTTP/1.1" 500 93437 This error occurs when I try to access the blog URL. I have some apps in my project like app base, app posts, app blog, and app categorias My directory file to be looks like the image: My files in app base: urls urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('posts', include('posts.urls')), path('summernote/', include('django_summernote.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.edit import UpdateView def home(request): return render(request, 'home.html') My files in app posts: … -
Django 2.2 TypeError at /cart/checkout __init__() missing 1 required positional argument: 'request'
I'm trying to make an eCommerce site with Django and I've been following along with this online course as well as the docs. And as I was updating the login forms to have better UX I came across an error in my carts view. Which I thought was strange because I didn't change anything in the order or the checkout view in my cart app. So here is the full traceback: >Environment: > > >Request Method: GET >Request URL: root/cart/checkout/ > >Django Version: 2.2.12 >Python Version: 3.6.9 >Installed Applications: >['django.contrib.admin', > 'django.contrib.auth', > 'django.contrib.contenttypes', > 'django.contrib.sessions', > 'django.contrib.messages', > 'django.contrib.staticfiles', > 'storages', > 'accounts', > 'addresses', > 'analytics', > 'billing', > 'carts', > 'marketing', > 'orders', > 'products', > 'search', > 'tags'] >Installed Middleware: >['django.middleware.security.SecurityMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware', > 'django.middleware.common.CommonMiddleware', > 'django.middleware.csrf.CsrfViewMiddleware', > 'django.contrib.auth.middleware.AuthenticationMiddleware', > 'django.contrib.messages.middleware.MessageMiddleware', > 'django.middleware.clickjacking.XFrameOptionsMiddleware'] > > > >Traceback: > >File "/home/ray/Dev/rxvenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in >inner > 34. response = get_response(request) > >File "/home/ray/Dev/rxvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in >_get_response > 115. response = self.process_exception_by_middleware(e, request) > >File "/home/ray/Dev/rxvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in >_get_response > 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) > >File "/home/ray/Dev/rxvenv/src/carts/views.py" in checkout_home > 79. login_form = LoginForm() > >Exception Type: TypeError at /cart/checkout/ >Exception Value: __init__() missing 1 required positional argument: 'request' According … -
Django handle multi step form
In multi-step forms what I want to do is when the user clicks on the NEXT button the view should be called in Django and the data is stored in the database and then the next form opens? -
Django: filter a query with an object attribute
I'm trying to build a filter depending on if an object attribute is empty or not. Below my 2 class tables: Buy model item buy_price sell_price 10 15 50 20 30 110 30 80 250 Sell model item buyer* 10 Ana *This is an OneToOneField(Buy) What I really need is to query a sum of the buy_price and sell_price that are NOT listed in Sell model (my_buy_object.sell.buyer == '') I tryied the code below but it's not working properly: buys = Buy.objects.order_by('-id') sum_price = [buy.buy_price for buy in buys if buy.sell.buyer == ''] sum_price = sum(sum_price) The correct answer for this code should be sum_buy_price: 110 and sum_sell_price: 360 Thank you! -
How do you allow users authenticated by python social auth to access the Django admin page?
I recently created a simple blog using Django for a school assignment. I got it up and running and configured user authentication via python social auth using my school's user API. However, the last thing I need to do is allow authenticated users to add posts to the blog. My solution is to add posts through the admin page, in which case I need a way to allow users authenticated via social auth to access the admin page. As of now, this solution doesn't work as standard Django superuser logins don't work and it says that my account isn't authorized to view it, so I need a way to allow authenticated users to access the admin page. I also realize that there may be a better/more practical way of doing this, so all suggestions are welcome! -
Django if condition
I want to do it with django in template if condition {% if object.count <= item.min_count %} <tr class="bg-warning"> {% else %} <tr> {% endif %} this works well, but if i do the below attemp, django fails raising no errors {% if object.count <= item.min_count %} <tr class="bg-warning"> {% if object.count <= (item.min_count/2) %}. # how can i do it? <tr class="bg-danger"> {% else %} <tr> {% endif %} -
Python/django firebase phone number verification?
I'm looking to integrate firebase phone verification into DRF authentication. However, everything I'm looking at seems to be exclusively for mobile device. Is there something built for python? For clarity, I'm only looking to bind the user to the provided phone number so I will only be performing the "phone authentication" once. I could settle for the phone verification returning some unique id to bind a the firebase account to a django user. Thanks! -
the process of listing similar users on a movie site based on the votes that users cast on movies?
I designed a movie site interface, my users can vote for movies. What I want to do is to list users similar to the user on the system. How can I do it. -
Get values from Django's form in efective way
I'm getting values from form in django like this: tantou1 = request.POST.get("1tantou", "") tantou2 = request.POST.get("2tantou", "") tantou3 = request.POST.get("3tantou", "") tantou4 = request.POST.get("4tantou", "") hidzuke1 = request.POST.get("1hidzuke", "") hidzuke2 = request.POST.get("2hidzuke", "") hidzuke3 = request.POST.get("3hidzuke", "") hidzuke4 = request.POST.get("4hidzuke", "") which works, but I have a lot of values to get and this way took too much space in my code. I would like to ask, if there is not a way to define this variables in (for example) loop? Something like: data_vars = [tantou1="", tantou2="", tantou3="", tantou4="", hidzuke1="", hidzuke2="", hidzuke3="", hidzuke4=""] for var in data_vars: var = request.POST.get(str(var.__name__), "") or so? -
How can i select from 2 tables some relationed fields in django?
Im new in python-django and i really need some help. This is my first question here. I´ve searched a lot on similar questions here but didnt find my needs. I am working on a restaurant website, developing in python and django and im facing very difficulties to make the restaurant menu. This data of the menu stays in a mysql db. I searched for select_related and prefetch related a lot, i imagine one of these will help, but its not workig. So, i have 2 tables, category_menu and menu. I have to list all categories and all the items of these categories. I have 2 models, category_menu and menu: class category_menu(models.Model): name_category = models.CharField(max_length=50, null=False) class Meta: default_related_name = 'categories' def __str__(self): return self.name_category def get_absolute_url(self): return reverse('category_menu_edit', kwargs={'pk': self.pk}) class menu(models.Model): item = models.CharField(max_length=50, null=False) description = models.CharField(max_length=300, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(category_menu, related_name='categories', null=True, on_delete=models.CASCADE) class Meta: default_related_name = 'menus' def __str__(self): return self.item def get_absolute_url(self): return reverse('menu_edit', kwargs={'pk': self.pk}) Im my views, i have the following: query = category_menu.objects.prefetch_related('categories').all().distinct datamenu = {'object_list': query} return render(request, template_name, datamenu) In my html, just the categories are listing, but the relationed items of the menu are not. … -
I am failing to update userprofile in django. What am I doing wrong?
When I create a user it should create the profile simultaneously. That is working fine but when I try to update the profile information in the template it doesn't save to database, instead the same page is being rendered. my model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default.jpg', upload_to='media/profile pics', blank=True, verbose_name="Upload Your Profile Picture") gender_choices = [ ('F', 'Female'), ('M', 'Male'), ('O', 'Other'), ] gender = models.CharField(max_length=20, default=1, blank=False, choices=gender_choices) title_choices = [ ('Ms', 'Ms.'), ('Miss', 'Miss.'), ('Mrs', 'Mrs.'), ('Mr', 'Mr.'), ('Dr', 'Dr.'), ('Sister', 'Sister.'),('Prof', 'Prof.'), ('Bish', 'Bishop'),('Rev', 'Rev.'), ('Sir', 'Sir.'), ('Father', 'Father.'), ('Lady', 'Lady.'), ('Brother', 'Brother.'), ] title = models.CharField(max_length=20, blank=False, choices=title_choices) race_choices = [ ('F', 'Black'), ('W', 'White'), ('C', 'Coloured'), ('I', 'Indian'), ('O', 'Other'), ] race = models.CharField(max_length=20, default=1, blank=False, choices=race_choices) id_number = models.CharField(max_length=20, blank=True, ) passport_number = models.CharField(max_length=20, blank=True, ) home_tel = PhoneField(max_length=15, blank=True, ) cell = PhoneField(max_length=15, blank=True, ) birth_date = models.DateField( null=True, verbose_name="Date Of Birth") nationality = models.CharField(max_length=50, blank=False) home_lang = models.ForeignKey(Languages, default=1, verbose_name= "Home Language", on_delete=models.SET_DEFAULT) other_lang = models.ManyToManyField(OtherLanguages, default=[0], verbose_name="Other Language(s)") if_others = models.CharField(max_length=50, blank=True, verbose_name='If other please specify') license_choices = [ ('N/A','N/A'), ('A1', 'A1'), ('A', 'A'), ('B(a)', 'B(a)'), ('B(b)', 'B(b)'), ('B(5)', 'B(5)'), ('B(7)', 'B(7)'), ('C1', 'C1'), ('C', 'C'), ('EB', … -
Django ordering fields are not visible in swagger rest api ui
I have a search view set as below. What I need is in swagger ui I should able to see the sort columns (upload_date, title, views) based on which I could sort the records. I believe sorting key should be part of GET url so that I can use that for website integration. I am not sure how to get this done. Please help with this. class SearchViewSet(viewsets.ViewSet): schema = CustomViewSchema() permission_classes = (HasPermPage,) def list(self, request): """ Get search infos. """ search = request.GET.get('search', '') persons = apis_models.Target.objects.filter( Q(person__name__icontains=search) | Q(person__nationality__icontains=search) | Q(person__profession__icontains=search) ).values_list('person__name', 'person__profession', 'person__id').annotate(total=Count('video_id'))[:10] videos = apis_models.Video.objects.filter( title__icontains=search ).values_list('title', 'id', 'upload_date', 'views')[:10] search_list = [] search_list.extend([{'id': u[2], 'string': u[0], 'profession': u[1], 'video_count': u[3], 'type': 'Person'} for u in persons[:5]]) search_list.extend([{'id': u[1], 'string': u[0], 'upload_date': u[2], 'views': u[3], 'type': 'Video'} for u in videos[:5]]) search_list.extend([{'id': u[2], 'string': u[0], 'profession': u[1], 'video_count': u[2], 'type': 'Person'} for u in persons[5:10]]) search_list.extend([{'id': u[1], 'string': u[0], 'upload_date': u[2], 'views': u[3], 'type': 'Video'} for u in videos[5:10]]) return Response({'results': search_list[:10]}) if len(search_list) > 0 else Response({'results': [{'string': 'No result found', 'type': None}]}) -
Annotate Total Count of Descents of Mptt Model
Question Given the models below, I want to get a queryset of all pages, annotated with the total number of comments in the thread associated to the page, including all comments in a comment thread tree associated with pages. I am using django-mptt to store comment tree. I can get this in python using comment.get_descendant_count(), but this is very ineficient when querying all pages Models class CommentThread(models.Model): ... class Page(models.Model): ... thread = models.ForeignKey("CommentThread", ...) class Comment(MPTTModel): body = models.TextField() author = models.ForeignKey("User", ...) # Validation ensures a comment has # a thread or parent comment but not both thread = models.ForeignKey("CommentThread", related_name="comments", ...) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) class MPTTMeta: level_attr = 'mptt_level' order_insertion_by=['name'] This model allows me to add multiple "root comments" to page, but also nest comments under each comment as replies, recursively. # Model Use Examples thread = CommentThread() page = Page(thread=thread) # add page level root comments comment1 = Comment(thread=thread, ...) comment2 = Comment(thread=thread, ...) comment3 = Comment(thread=thread, ...) # add Comment Replies to comment #1 comment_reply1 = Comment(parent=comment1, ...) comment_reply2 = Comment(parent=comment1, ...) comment_reply3 = Comment(parent=comment1, ...) Current approach - in python Works but very inneficient: page = Page.objects.first() total_comments … -
Skip Login Process In Functional Tests
I am using allauth and have began making some functional tests. I have tested the login function and now am wanting to test other things, but I cant find a way to begin my functional tests with a pre-authenticated user. I have tried using the following code but I cant manage to get a user logged in automatically. def create_pre_authenticated_session(self, username, email): session_key = create_pre_authenticated_session(username, email) # to set a cookie we need to first visit the domain self.browser.get(self.live_server_url + "/") self.browser.add_cookie(dict( name=settings.SESSION_COOKIE_NAME, value=session_key, path='/', )) def create_pre_authenticated_session(username, email): user = User.objects.create(username=username, email=email) session = SessionStore() session[SESSION_KEY] = user.pk session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] session.save() return session.session_key Thank you.