Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: UserCreationForm: add_error to both passwords when pass validation fails
curretly in UserCreationForm (django.contrib.auth.forms) Django has def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) i want both the password fields to be shown error, when password validation fails how can i do this i tried def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) self.add_error('password1', error) But this does not work -
Django: Add another foreign key object to existing object
Probably a dumb question-- I have a model A object that has a ForeignKey to model B. When I create an A object, I include the foreign key. How can I add another B reference to my model A. Sample code: a = A.objects.create(b=b) b2 = b2.objects.create() # How can I add b2 to a? -
Using uuid.uuid4() as default value
I want to make model like import uuid class UserData(models.Model): id_key = # give uuid.uuid4() as default value pub_date = models.DateTimeField('date published',default=timezone.now) When UserData is made in script, id_key value should be made automatically. ud = UserData() ud.save() I guess I should make a function as default value though, I am not clear yet. how can I make this?? -
Django Testing - How can I patch multiple external API calls in a single function?
I have a function in a class that makes two separate, distinct GET requests to an external API. I'm not sure how I could go about patching each individual external call. Say my function is this (which lives under MyClass in myclass.py: def combined_requests(): a = requests.get("/a") b = requests.get("/b") return a.data + b.data Normally, if it was a single call I could do: def test_case(self): with mock.patch('myclass.requests') as mock_requests: mock_requests.get.return_value = 1 MyClass.single_request() But since I have two request calls, I'm not sure how I could patch each one within that combined function. Is this even possible to do? Thanks! -
how to get information for specific user in Django ( i wanted to get Appointment history for specific user who is now logged in )
#for for adding appointment def book_appointment(request): if request.method=="POST": specialization=request.POST['specialization'] doctor_name=request.POST['doctor'] time=request.POST['time'] app=Appointment(specialization=specialization, doctor_name=doctor_name, time=time) app.save() messages.success(request, "Successfully Appointment booked tap on view appointment for status") return redirect('home') #view appointment history def appointmentInfo(request): appts= Appointment.objects.all() return render(request,'home/view_appointment.html',{'appoints':appts}) #login def handeLogin(request): if request.method=="POST": # Get the post parameters loginusername=request.POST['loginusername'] loginpassword=request.POST['loginpassword'] user=authenticate(username= loginusername, password= loginpassword) if user is not None: login(request, user) messages.success(request, "Successfully Logged In") return redirect("home") else: messages.error(request, "Invalid credentials! Please try again") return redirect("home") return HttpResponse("404- Not found") return HttpResponse("login") -
Django not using DEFAULT_FROM_EMAIL
I'm trying to send emails with Django using SendGrid, that uses a Gmail account. I'm deploying the website on heroku. My settings.py file is as follows: SENDGRID_API_KEY = 'api key here' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = 'myapp.api.test@gmail.com' However the DEFAULT_FROM_EMAIL variable doesn't seem to work. When trying to send an email, I get the error The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements However I already checked and my Sender Identity was validated with Single Sender Verification . I know DEFAULT_FROM_EMAIL isn't activated, as in the error log on line /app/.heroku/python/lib/python3.7/site-packages/django/core/mail/__init__.py when the error occurs I know the variable from_email is apikey, when it should be myapp.api.test@gmail.com. What is wrong? -
Custom User Model versus Django User Model
I am making a web application using Django as my backend, and I was wondering what the best practice is when dealing with models representing user account information (username, password, email, etc.). I am aware of an existing User model, as well as the practice of creating a custom user model by subclassing AbstractUser. However, I am confused as to how this is any different than subclassing models.Model and creating my own user model from scratch. Does anyone have advice as to what is best practice in this situation? -
Using "When" in a Django annotation, with a many-to-many relationship, returns more rows than it should
I have three models defined like this: class Equipment(models.Model): hostname = models.CharField(max_length=128) class Interface(models.Model): internal_ip = models.GenericIPAddressField() index = models.IntegerField() equipment = models.ForeignKey("Equipament", on_delete=models.CASCADE) class Event(models.Model): equipment = models.ForeignKey("Equipment", on_delete=models.CASCADE) index = models.IntegerField(null=True) datetime = models.DateTimeField(auto_now=True) When an Event is created, it may have an index, but it also may not. This index refer to the index of the Interface. events = Event.objects.all() events = events.annotate(interface_ip=Case( When(Q(index__isnull=False) & Q(equipment__interface__index=F('index')), then=F('equipment__interface__internal_ip')), output_field=models.GenericIPAddressField() )) When I apply this annotation, the events get multiplied by the interfaces the equipment has. This makes sense, because it's evaluating which interfaces, in the given equipment, match the index specified by F('index'). How can I simply exclude the ones that don't match? From my point of view, Q(equipment__interface__index=F('index')) should compare if the interface__index equals the index, and jump if it doesn't (on the other hand, I know it makes sense, since it has a default value of None, when it doesn't match). I wish I'd have control over how the Events get inserted on the table, but unfortunately I don't, since it's an external system making direct inserts on the MySQL database, and they simply get the index and throw it in the "index" field. -
Reverse for 'edit' not found. 'edit' is not a valid view function or pattern name
Internal Server Error: /wiki/Python Traceback (most recent call last): File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Bappy\desktop\web50\projects\2020\x\wiki\encyclopedia\views.py", line 21, in entry return render(request, "encyclopedia/entry.html", { File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'edit' not found. 'edit' is not … -
Django, custom managers, base_manager_name and the failure to save model
I'll simplify my problem: In my project I have a Person model and that person has an age. I changed the default manager applied to Person using base_manager_name to my version of objects. Person` has this: objects = MySpecialAgeFilterManager() objects_all = models.Manager() So, when I ask for Person.objects.all() I will get only people between the ages of 20 and 30. Don't ask me why-- it's just for the sake of this question.. I have a certain Person instance with the age of 10. That person will not show up on Person.objects.all() -- however it will be included in Person.objects_all.all() My problem is this. p = Person.objects_all.filter(age=10).first() # works, I get my person. p.age = 20 # trying to bring him into the light.... p.save() # CRASH!!! The crash claims the pk for p creates a duplicate violation on the database. It's as if it's trying to save it with the objects scope in mind, and not the objects_all scope I retrieved that person with. In the objects context it doesn't exist so it tries to save... but the database has that PK already in use. The database doesn't care about Model Manager scopes.... How do I resolve this? -
Class "Room" has no "objects" members
I'm doing a web app with Django, but I keep getting this error all the time. This is the code from my models.pty, where I create the class Room. from django.db import models import string import random def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): code = models.CharField(max_length=8, default="", unique=True) host = models.CharField(max_length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) And here is where I import the room to views.py, I'm also getting the same error here. from django.shortcuts import render from rest_framework import generics from .serializer import RoomSerializer from .models import Room class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer What's wrong with my code? -
Trouble viewing cart items from admin page on django site
Here is my views.py from django.shortcuts import render from .models import Cart def cart(request): Cart = Cart.objects.get(id=1) context = { 'items': Product.objects.all(), 'object': obj, 'id': obj.id, 'name': obj.name, 'cover': obj.image, 'author': obj.author, } return render(request,'bookstore/cart.html', context) ``` Here is my models.py from django.db import models from apps.bookstore.models import Product class Cart(models.Model): products = models.ManyToManyField(Product,blank=True) total = models.DecimalField(max_digits=65, decimal_places=2,default=0.00) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return "Cart id: %s" %(self.id) ``` Here is my cart.html {% extends 'bookstore/main.html' %} {% load crispy_forms_tags %} from .models import Product from cart.models import Cart {% block content %} <h1>Shopping Cart</h1> <table> {% for item in items %} <tr> {{ item.name }} <td>{{ item.author }}</td> </tr> {% endfor %} {% endblock content %} It seems like something is wrong with my models.py portion. In my admin page I can add the items I have from the bookstore to the cart however when I go to look at them on the website nothing is displayed. -
Complex Django CheckContraint won't migrate
I'm having issues running a Django (2.2) migration that contains a somewhat complex CheckConstraint, running over python 3.6.9. The underlying database is PostGIS 9.5. The Model: class Subscription(BaseModel): class Meta: constraints = [ models.CheckConstraint(name='%(app_label)s_%(class)s_valid_product', check=( (models.Q(variant_id__exact=None) & models.Q(product_id__exact=None)) | (~models.Q(variant_id__exact=None) & ~models.Q(product_id__exact=None)) )) ] ... product_id = models.IntegerField() variant_id = models.IntegerField() The migration: ... migrations.AddConstraint( model_name='subscription', constraint=models.CheckConstraint( name='%(app_label)s_%(class)s_valid_product', check=models.Q( models.Q( models.Q(variant_id__exact=None), models.Q(product_id__exact=None) ), models.Q( models.Q(_negated=True, variant_id__exact=None), models.Q(_negated=True, product_id__exact=None) ), _connector='OR' ) ), ), ... And the big bad trace: File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 827, in database_forwards schema_editor.add_constraint(model, self.constraint) File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 345, in add_constraint self.execute(sql) File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 137, in … -
Django de-structuring of URLs
I am learning the Django Web Framework but just could not work my head around this logic. Let's say we have a Django App that has a very big urls.py where all the patterns are stored here. How would one go about splitting this into a urls folder, wherein it contains multiple 'urls.py' files? And not only that, to have a nested directory within the urls folder as well. Example project structure of what I am thinking of: >main_base >__init__.py >asgi.py >settings.py >wsgi.py >urls.py >secondary_app >admin.py >apps.py >models.py >__init__.py >views >home.py >idea.py >project.py >business_partners >customers.py >vendors.py >urls >__init__.py >home.py >idea.py >project.py >business_partners >__init__.py >customers.py >vendors.py in main_base/urls, I would have the following: from django.urls import path, include urlpatterns = [ path('', include('secondary_app.urls')), ] in secondary_app/urls/init.py, I would expect to do the following: from django.urls import path, include urlpatterns = [ path('', include('secondary_app.urls.home')), path('', include('secondary_app.urls.idea')), path('', include('secondary_app.urls.project')), path('', include('secondary_app.urls.business_partners')), ] And lastly in secondary_app/urls/business_partners/init.py, I would do the following: from django.urls import path, include urlpatterns = [ path('', include('secondary_app.urls.business_partners.customers')), path('', include('secondary_app.urls.business_partners.vendors')), ] I have tested it and it works all the way up till the secondary_app/urls directory level. But once I go one more level down, it throws a reverse match … -
Is there a way to enable verbose logging in Django Channels?
I have Django Rest Framework and Channels installed on a Heroku server. I am having issues with socket signals my API is sending to my sockets actually getting received by the consumer. I know this because the print()s in my consumer don't print. This is an intermittent issue - sometimes I refresh and it works fine for some users. Is there a way to enable some sort of verbose logging so I can see every call that Channels is receiving, and where it is sending it to? -
can't get the profile object firstname
I'm trying to get the profile firstname but it gives me this error File "/home/marwan/Desktop/Gowd/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:53742] INFO 2021-03-12 01:43:30,570 runserver 119412 140507688003328 WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:53742] I think that this error has something to do with trying to get the user profile in line 56 "profile": self.scope["user"].profile.firstname, if I remove it will work fine this is my consumers.py file from channels.generic.websocket import AsyncJsonWebsocketConsumer import json from django.contrib.auth import get_user_model from gowd_project.users.models import User, Profile User = get_user_model() # Example taken from: # https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/consumers.py class PublicChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ print("PublicChatConsumer: connect: " + str(self.scope["user"])) # let everyone connect. But limit read/write to authenticated users await self.accept() # Add them to the group so they get room messages await self.channel_layer.group_add( "public_chatroom_1", self.channel_name, ) async def disconnect(self, code): """ Called when the WebSocket closes for any reason. """ # leave the room print("PublicChatConsumer: disconnect") pass async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass … -
Passing Django ContentFile to an ImageField doesn't create an image file on the disk on Docker
The code below works on local when I don't use Docker containers. But when I try to run the same code/project in Docker, while everything else is working great, the part of the code below doesn't work as expected and doesn't save the ContentFile as image file to the disk. The ImageField returns the path of the image but actually it doesn't exist. from django.core.files.base import ContentFile ... photo_as_bytearray = photo_file.get_as_bytearray() # returns bytearray cf = ContentFile(photo_as_bytearray) obj.photo.save('mynewfile.jpg', cf) # <<< doesn't create the file only on Docker Not sure if there's something I need to change for Docker. -
django.db.utils.OperationalError: ('HYT00', '[HYT00]
I am trying to run a virtual Python Django environment and have run this command. python manage.py runserver Now, I receive the following error(s). Could someone point me in the right direction? I know this has somethingt to do with ODBC/the backend but am not sure exactly what is going on. Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line … -
Replacing CharField with a ForeignKey based on the CharField
While refactoring an app, I've started removing a config file and replacing it with a new model, Foo in this example. Because of this, another model, Bar in this example, needs to change from having a CharField that was for the config file, to a ForeignKey that is for the new model. Say I have class Foo(models.Model): name = models.CharField(primary_key=True, max_length=100) class Bar(models.Model): name_of_foo = models.CharField(max_length=100) and I want to change name_of_foo to instead be a ForeignKey... class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, default=???) I would like the default to be based on what name_of_foo was. If name_of_foo was "abc", I would like it to do something akin to default=Foo.objects.get("abc"). Is there a way to fill in the ??? such that this works nicely? If not, what steps can I take to arrive here, so that the existing data is converted? -
Crispy forms not working on django login form created with "django.contrib.auth.urls"
Good Day, i am trying to use crispy forms on a login form created with the django authentication system(using 'django.contrib.auth.urls' to be specific) but crispy forms didn't work on it. urls.py from django.conf.urls import include, url from users.views import dashboard urlpatterns = [ url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^dashboard', dashboard, name='dashboard') ] This autamotically passed the context to the login template i made.(i didn't even need a view) login.html <form method="POST"> {% csrf_token %} <fieldset class=''> <legend class='border-bottom mb-4 text-center'>Log In</legend> {{ form|crispy }} </fieldset> <div class=""> <button class="btn btn-outline-info btn-primary" type='submit'>Login</button> <small class = "text-muted ml-2" > <a href="">Forgot Password?</a> </small> </div> </form> But when i tried using crispy forms on the context variable 'form', it didn't work on it. But it worked on the other elements inside the form(like the link that says "Forgot Password?" and the login button). So i guess the way the form variable is passed to the template doesn't allow crispy forms work on it. Please is there a way(maybe with a view or something) to access the variable and make it like a regular form context variable that crispy can work on. Thank You -
How do I get the value of the object being created in Django CreateView for further logic?
So I have a CreateView which is using a model form 'A' and I also have a different model which I want to edit when this model inside model form 'A' gets submitted. How do I access the object when it's not created? Is there any better approach? Here is the form_valid function() def form_valid(self, form): member = self.object form.instance.registration_upto = form.cleaned_data['registration_date'] + delta.relativedelta( months=int(form.cleaned_data['subscription_period'])) if form.cleaned_data['fee_status'] == 'paid': payments = Payments( user=member, payment_date=form.cleaned_data['registration_date'], payment_period=form.cleaned_data['subscription_period'], payment_amount=form.cleaned_data['amount']) payments.save() return super().form_valid(form) Self.object is None as the object is not yet created. I want to access that object as it's the user in my payments model. I have to stick to class-based views only. Is there a way I can do this? I'm a little new to Django and looking at the docs didn't help much. Thanks for any advice -
How to update the las row of the table with Django OMR queryset?
I´m trying to make an update with the django OMR but I don´t know the id. Only I konw that I want to update the last record. The other columns are not useful because the data is similar except for the date column(could be an aoption but the django OMR don´t recognized my query) My actual query: Tracking = TrackEExercises.filter( exe_date = (fecha + delta).replace(microsecond=0) ).update(data_tracking = dataT) -
Django backend, reactjs frontend - How do I pass context variable from views.py to app.js?
I'm creating an application that webscrapes data. I've created all my logic in the Django backend and it works perfectly fine. I put the variables needed into a dictionary to be rendered out. views.py return render(request, 'index.html', context_dict) It properly renders out to my index.html, I am able to see the variable. However I need these context_dict variables to render out to my app.js file, so I can use it with react on the frontend. Please let me know how this is possible. Thanks in advance! app.js function App() { return ( <div className="App"> <div className="center-column"> <div className="item-row"> <div class="centered"> <span> - - - - NEED TO CALL MY CONTEXT_DICT HERE! - - - - </span> </div> </div> </div> </div> ); } export default App; Local Server - 127.0.0.0.1:8000 -
Djnago live viewers counter in rtmp
I have a few livestreaming pages on my site. And i want to count users who are watching my stream at this moment. Like on twitch. How to implement it? -
Handling pages in a vue + django webpack application
I added Vue to my Django project, but since i didn't want to decouple frontend from backend, i decided to load webpack directly from Django. My setup seems to work with django webpack loader, but i'm having some doubts on how i structured the project. Here is my folder: my_site - django settings my_app - views, urls, models, templates vue_frontend - webpack and vue stuff My doubt is: should routing be handled by Django or should it be handled by Vue in a SPA? Here is what i have now: django_template2.html {% extends 'header.html' %} {% load render_bundle from webpack_loader %} {% block content %} <body> <div id="app"> <firstVueComponent /> </div> </body> {% render_bundle 'chunk-vendors' %} {% render_bundle 'main' %} {% endblock %} django_template2.html {% extends 'header.html' %} {% load render_bundle from webpack_loader %} {% block content %} <body> <div id="app"> <secondVueComponent /> </div> </body> {% render_bundle 'chunk-vendors' %} {% render_bundle 'main' %} {% endblock %} So Django handles the urls here: from django.urls import path, include from . import views urlpatterns = [ path('first_page/', views.first_page, name='first'), path('second_page/', views.second_page, name='second'), ] So here i'm not using Vue to handle routes, but i load individual Vue components of the same app …