Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i build a web application with django? [closed]
Okay so i am meant to build an online consultation app for my project in school and ive done some small apps over time with Django but i dont know the first thing on how to create a full stack web application. I dont really have that much time to the deadline so i just want to ask. If i were to start learning now to start creating a full stack app, which way do you think i should go about learning it. option1 (learn how to combine javascript and bootstrap with django without the use of rest framework), option2(django and rest framework with javascript and bootstrap), option 3(learning django and React without the use of rest_ framework) and option 4(learning django, react and rest_framework). I really just want to know which way would be faster and easier to learn and create my app with. Keep in mind that django is the only constant option because that is the only language i am familiar with. if there are any other easier and better ways or languages to learn other than django then pls suggest. Thank you. -
Django admin site: Unable to lookup 'child model' on 'parent model or 'parent modelAdmin'
This one's really difficult to write as a question since I'm not exactly sure how to ask this in the first place. But I'll try. Basically, I'm experiencing an AttributeError when I'm visiting the parent model in my django admin site. My current django database has 2 tables (except the prebuilt tables): a parent table / model for activity, and a child table / model for instruction. This is the structure of my models: class activity(models.Model): title = models.CharField(max_length=30,default=None) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User,on_delete=models.CASCADE,default=None) def __str__(self): return self.__class__.__name__ class instruction(models.Model): detail = models.CharField(max_length=50,default=None) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User,on_delete=models.CASCADE,default=None) activity = models.ForeignKey(activity,on_delete=models.CASCADE,default=None) def __str__(self): return self.__class__.__name__ So, if I add a new activity in the django admin site, say: Push-ups, then, I should be able to select this newly added parent record in the instruction form. However, when I try to add a new instruction record and select a saved activity record, the activity dropdown shows the name of the model only(in this case, activity). It doesn't show Push-ups. What I did next was to add some modelAdmins for the activity and instruction. Here's the code: class activityAdmin(admin.ModelAdmin): list_display = [field.name for field … -
TypeError: expected str, bytes or os.PathLike object, not FieldFile while show pdf from DB
VIEW: def get_book(request, book_id): book = Book.objects.filter(book_id=16).first() return FileResponse(open(book.pdf, 'rb'), content_type='application/pdf') HTML: <embed src="{% url 'user-get-book' 16 %}" type="application/pdf" height="700px" width="500"> URL: path('get_book/<int:book_id>', views.get_book, name='user-get-book') Data is stored in the DB but not able to show on HTML. The error I get is this. TypeError at /get_book/16 expected str, bytes or os.PathLike object, not FieldFile Request Method: GET Request URL: http://127.0.0.1:8001/get_book/16 Django Version: 3.2.5 Exception Type: TypeError Exception Value: expected str, bytes or os. Help is much appreciated. -
Please My Logout redirects properly but does not truly logout from Django admin
I am building a simple notebook application and I want to include authentication. I have successfully added login, logout and registration. However, when I click on logout from the restricted app, it does successfully redirects but the restricted page can still be access through it's url. If I logout through the django admin only then will the restricted page not be access through the url until I log out. ** Normally, I expected that when I clicked on the logout link in note.html it will log me out also from the django admin panel. ** Why is this behaviour? url.py from django.urls import path from . import views from django.contrib.auth import views as auth_views from .forms import UserLogin app_name = 'accounts' urlpatterns = [ path('login/', views.loginUser, name = 'login'), path('logout/', views.logoutUser, name = 'logout'), path('register/', views.account_register, name = 'register'), path('profile/', views.profile, name ='profile'), ] views.py # from ..notebooks.models import Notes from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .forms import RegisterForm from django.contrib import messages # Create your views here. @login_required def profile(request): return render(request,'accounts/profile.html', {'section' : 'profile'}) def loginUser(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, … -
How to filter multiple fields using Django-filter?
I want to retrieve data filtered by user and category. I'm using Django Rest Framework. models.py class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) user = models.ForeignKey('User', models.DO_NOTHING, default=None) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) score = models.SmallIntegerField(null=True) def __str__(self): return str(self.practice_id) class User(models.Model): user_id = models.BigAutoField(primary_key=True) fullname = models.CharField(max_length=50) def __str__(self): return self.fullname class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) category = models.CharField(max_length=30) def __str__(self): return f"{ self.category }" serializers.py class PracticeSerializer(serializers.ModelSerializer): subcategory = SubcategorySerializer() class Meta: model = Practice fields = ('practice_id', 'user', 'subcategory', 'score', ) views.py @api_view(['GET']) def practiceFilter_User(request): if request.method == 'GET': exercises = Practice.objects.all() user = request.GET.get('user', None) if user is not None: practice_filtered = exercises.filter(user__user_id__icontains=user) exercises_serializer = PracticeSerializer(practice_filtered, many=True) return JsonResponse(exercises_serializer.data, safe=False) urls.py urlpatterns = [ url(r'^api/practice-filter-user$', views.practiceFilter_User), ] In my database I have 3 practice data as below : [ { practice_id: 1, user: 1, subcategory: { subcategory_id: 1, category: "Math", }, score: 7, }, { practice_id: 2, user: 1, subcategory: { subcategory_id: 1, category: "Math", }, score: 8, }, { practice_id: 3, user: 1, subcategory: { subcategory_id: 2, category: "History", }, score: 9, } ] If the above code is executed to get practice data by user id = 1, the result is as below : api/practice-filter-user?user=1 [ … -
Related Field got invalid lookup: level - while getting less than
I am building a easy Q&A site, And I am trying to get all the posts which have zero votes. So I tried using lt (less than). But After using lt it is not showing posts which have zero votes. It is showing nothing. Than, i tried to put 1 with lte (less than or equal to) instead of 0 lt but than it showing posts which have 1 votes , but it should show posts which have 1 or less votesbut it is not even including the posts which have0` votes. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) votes = models.ManyToManyField(User, on_delete=models.CASCADE, related_name='votes') views.py def questions(request): posts = Question.objects.filter(votes__lt=0) context = {'posts':posts} What have i tried :- I tried by filtering lte=1 , I mean it will show posts which have 1 or less than 1 votes like :- posts = Question.objects.filter(votes__lte=1) But it is not showing which have 0 votes. Than i tried level posts = Question.objects.filter(votes__level__lt=0) But it is keep showing Related Field got invalid lookup: level I will really appreciate you Help. -
Django-Celery database update
I have a celery task for updating a part of my database. The problem is that if I delay the task (hand it to celery), it gets processed, but does not update the db. When I call the task manually (e.g. refresh_printfuldb() rather than refresh_printfuldb.delay()), it works fine and I see the changes when I query the db. The celery worker log looks like this: [2021-09-05 16:48:48,541: INFO/MainProcess] Task t_well.tasks.refresh_printfuldb[55eb39eb-f1e4-4b7d-b509-a87affe0535b] received [2021-09-05 16:48:49,069: INFO/SpawnPoolWorker-32] child process 47336 calling self.run() [2021-09-05 16:48:49,081: INFO/SpawnPoolWorker-33] child process 42852 calling self.run() The file tree: -mysite/ celery.py settings.py ... -app/ models.py tasks.py printfulapi.py ... celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', "mysite.settings") app = Celery('mysite') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings.py: ... CELERY_BROKER_URL = 'redis://192.168.1.188:6379' CELERY_RESULT_BACKEND = 'django-db' ... models.py: As I've said, if I query the db after manually calling refresh_printfuldb(), I see the changes, so I suppose the problem is not with the models. tasks.py: from celery import shared_task from . import printfulapi ... @shared_task def refresh_printfuldb(): printfulapi.refresh_orders(orders_in_api_page) #other calls to the printfulapi module ... ... printfulapi.py: from .models import Product, Variant, SyncProduct, SyncVariant, Order def refresh_orders(orders_in_api: List[Dict]) -> None: for order_in_api in orders_in_api: order_id = order_in_api["id"] order = get_object_with_id(Order, order_id) order.status = order_in_api["status"] … -
why the Customer data is not show in template profile.html in django
models.py ( considering all required data ) Customer is not Django Default User how to display in template the customer class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.TextField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField(max_length=100 ,default='') password = models.CharField(max_length=500) views.py ( considering all required done ) def profile(request): data= Customer.objects.all() return render(request,'profile.html' ,{'data':data}) profile.html ( considering making urls) and all doing requirement {% if data %} <h2>{{ data.email }}</h2> {% endif %} -
DC motor connected to motor shield and raspberry pi didn't move when controlled through web server
I am very new to this stuff so bear with me :). So I had to continue my senior's project which is to control a raspberry pi car from a website running on local server. I recently received the assembled components and all, and as I turn on the raspberry pi I managed to connect to his web server by entering the raspi IP address and the 8000 port (e.g: http://XXX.XXX.XXX.XXX:8000). However, the move forward button on the page that supposed to move the tire doesn't work as it supposed to. the web interface and the post request sent from the forward button The project works fine before it arrive to me and move as it supposed to. Here some things I've discovered while troubleshooting: The project auto detect the changes of IP address which means connected to another different wifi would not be the problem. I believe there's also no problem with the connection of the page and the project since I already try edit something in the project file in the raspberry pi and it appears on the web page on my computer. Connection between the motor shield and the raspberry pi is not a probem since I've … -
how to display os.environ.get value in ubuntu using python/django
i have the following OS" (env) ubuntu@ip-xxxxxx:~/test/test_app$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 20.04.3 LTS Release: 20.04 Codename: focal now to set the env variable i have accessed nano ~/.profile and edited the file with: export TEST="johndoe" then exited nano and did chmod a+x ~/.profile and ~/.profile to apply the changes now in django views.py when i try to access the variable: views.py ... import os @api_view(["GET"]) def index(request): if request.method == "GET": env_var = os.environ.get("TEST") context = {"response": "Welcome: {}".format(env_var)} return Response(context) result { "response": "Welcome: None" } PS: I dont' intend to use any os variable in the views.py, i was just testing it there so i can use it in the settings.py Is there any reason why the value None is returned (why it's not picking up the actual value)? Thank you in advance -
how to fit image inside a div?
I am building an instagram clone & currently working in posts so my question is that, i have created a card and inside of that i have created a div containing posts(images) but the problem is that, when i upload images with multiple size it straches my card & it doesn't get fit inside of that div. Also my right div changes according images... This is small image This is big image Code: <div class="mx-auto w-75"> <div class="card my-3"> <div class="card-body p-0"> <div class="row"> <div class="col-sm-8 ms-2 mb-0 ps-1 pe-0"> <div id="carouselExampleFade" class="carousel m-0 slide carousel-fade" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static 'images/post-1.jpg' %}" style="height:auto;" class="d-block w-100 img-fluid" alt=""> </div> <div class="carousel-item"> <img src="{% static 'images/profile-1.jpg' %}" style="height:auto;" class="d-block w-100 img-fluid" alt=""> </div> <div class="carousel-item"> <img src="{% static 'images/profile-2.jpg' %}" style="height:auto;" class="d-block w-100 img-fluid" alt=""> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> <div class="col-sm-3 p-0"> <div class="card pt-0" style="width:325px; height:72px; padding:16px; margin-top:-1px;"> <div class="card-body"> </div> </div> </div> </div> </div> </div> </div> -
How can I handle selenium and geckodriver install error?
I ran the following code by installing selenium and django module. from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title For the selenium module, I need geckodriver for firefox browser. So, I installed geckodriver by different ways - 1. npm, 2. brew, 3. direct install (download from here and move it to /usr/local/bin or /usr/bin. All the ways did not work for the above test code. I got the following error message: Traceback (most recent call last): File "functional_tests.py", line 3, in <module> browser.get('http://localhost:8000') File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20localhost%3A8000. Please let me know what the problem is.. -
Django doesn't raise ValidationError on ModelChoiceField (widget RadioSelect) if user didn't select any choice
I have a form that contains a ModelChoiceField poller_category class PollersForm(forms.Form): # Poller Category poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={ 'class': 'poller-category-radio', }), queryset=Categories.objects.all().order_by('poller_category'), label='Select a Category') which is rendered as follows: <!-- Poller Categories --> <div class="fieldWrapper"> <div class="label">{{ form.poller_category.label_tag }}</div> <div class="category-ctn"> {% for category in form.poller_category %} <div class="category-wrapper">{{ category }}</div> {% endfor %} </div> </div> Now if the user doesn't select any category and tries to submit the form, nothing just happens. That actually means that the form is valid, doesn't it? If so, why doesn't it trigger the redirect? Also If I select a choice and submit, redirect is called, but the category isn't populated in the DB. # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # process the remaining data in form.cleaned_data as required poller_text = form.cleaned_data['poller_text'] poller_category = form.cleaned_data['poller_category'] poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_text=poller_text, poller_choice_one=poller_choice_one, poller_choice_two=poller_choice_two, poller_category=poller_category, created_by=created_by) p.save() # redirect to a new URL: return redirect(poller_success) # if a GET (or any other method) we'll create a blank form else: form = … -
Total Price Django
How can i get "total" from these models down below? I tried doing something in views but I get attribute error that QuerySet' object has no attribute 'total'. views.py def cart(request): cart = Cart.objects.filter(order_user=request.user) order_items = OrderItem.objects.filter(cart__in=cart) total = 0 for i in order_items: total = i.quantity * i.item.price + cart.total cart.update(total=total) models.py class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) ordered = models.BooleanField(default=False) total = models.IntegerField(default=0, help_text="100 = 1EUR") order_items = models.ManyToManyField(Item, related_name='carts', through=OrderItem ) -
Resend OTP ajax function not working in a django project
I have made an ajax function that resends otp when the 'resend Otp' lick is clicked. This is django project. The follwing are the codes that I wrote. html <a class="resend-otp" href="#" onclick="ReSendOTP('{{user.username}}', 'resendOTPmess')" ><i id="resendOTPmess">Resend</i>OTP?</a> js file function ReSendOTP(username, mess_id){ mess = document.getElementById(mess_id); mess.innerText = "Sending..."; $.ajax({ type: 'GET', url: '/user/resendOTP', data: {usr:username}, success: function(data){ mess.innerText = data; } }) } views.py def resend_otp(request): if request.method == 'GET': get_user = request.GET['usr'] if User.objects.filter(username = get_user).exists() and not User.objects.filter(username = get_user).is_active: user = User.objects.get(username=get_user) user_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = user_otp) mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!" send_mail( "Welcome to Solve Litigation - Verify your Email", #subject mess, #message settings.EMAIL_HOST_USER, # sender [user.email], #reciever fail_silently= False ) return HttpResponse("Resend") return HttpResponse("Can't Send OTP") urls.py from .views import resend_otp path('resendOTP', resend_otp) So I am requesting a resend otp for the "username: rick.bhardwaj27@gmail.com" but I am getting the follwing error in the console jquery-3.6.0.min.js:2 GET http://127.0.0.1:8000/user/resendOTP?usr=rick.bhardwaj27%40gmail.com 404 (Not Found) What should I do to rectify it, please suggest. -
How to minimize side bar when enter a spesific page?
I have a sidebar. When user enter the index page, I want to minimize the side bar. There is a button for that in sidebar: <a class="mobile-menu" id="mobile-collapse" href="javascript:"><span></span></a> How can I trigger this link when enter the home (index) page? sidebar.html <nav class="pcoded-navbar"> <div class="navbar-wrapper"> <div class="navbar-brand header-logo"> <a href="/" class="b-brand"> <div class="b-bg"> <i class="feather icon-trending-up"></i> </div> <span class="b-title">HawkDragon</span> </a> <a class="mobile-menu" id="mobile-collapse" href="javascript:"><span></span></a> </div> <ul class="nav pcoded-inner-navbar"> <li class="nav-item pcoded-menu-caption"> <label>Menü</label> </li> <li data-username="dashboard Default Ecommerce CRM Analytics Crypto Project" class="nav-item {% if 'index' in segment %} active {% endif %}"> <a href="/" class="nav-link "><span class="pcoded-micon"><i class="feather icon-home"></i></span><span class="pcoded-mtext">Anasayfa</span></a> </li> <li data-username="dashboard Default Ecommerce CRM Analytics Crypto Project" class="nav-item {% if 'index' in segment %} active {% endif %}"> <a href="/" class="nav-link "><span class="pcoded-micon"><i class="feather icon-home"></i></span><span class="pcoded-mtext">Setup Wizard</span></a> </li> </ul> </div> </div> </nav> -
less than or equal to 0 - is not showing posts which have 0 votes
I am building a simple question and answer site. And I am trying to access the answers which votes are less than or equal to 0. I have three answers which have no votes But it is not showing in the queryset I should show me three posts which have zero votes , But it is showing 0. models.py class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) body = models.CharField(max_length=3000) likes = models.ManyToManyField(User, related_name='likes', blank=True) views.py def answers(request): answers = Answer.objects.filter(likes__lte=0).count() context = {'answers':answers} return render(request, 'answers.html', context} When i remove .count() than it shows <QuerySet []>. I have tried many times but it is still showing 0 posts which have 0 votes. And when i set it to lte=1 than it shows posts which have 1 likes but it doesn't show less than 0. Any help would be much Appreciated. Thank You. -
Accessing Django username in PayPal transaction
I would appreciate any insight as to whether it is possible to access the username of whoever is logged into my Django app from a PayPal smart button. I currently have a "description" string within the createOrder function, which I would like to include the username. TIA for any help. -
Django throws No unique constraints when I add a uuid field to unique_together along with django's ID
I am just creating a model, not even adding a field to an existing model It looks like this class Product(TenantModel): firm = models.ForeignKey("TenantsUI.Firm",on_delete=models.CASCADE, default=get_current_tenant) tenant_id = 'firm_id' tracker = FieldTracker() name = models.CharField(max_length=250, null=True) packing = models.CharField(max_length=250, null=True) product_uref = models.UUIDField(default=uuid.uuid4, null=False, blank=False) class Meta: verbose_name = "Products" unique_together = [['firm','id','product_uref']] When I run migration, it says File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "FirmData_product" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\Documents\Django Projects\proj\root\manage.py", line 22, in <module> main() File "C:\Users\user\Documents\Django Projects\proj\root\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\user\Documents\Django Projects\proj\env\lib\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 "C:\Users\user\Documents\Django Projects\proj\env\lib\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 "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\db\migrations\executor.py", … -
filter model with foreignKey
I have these 2 models: class Canva(models.Model): name = models.CharField(null=True, blank=True, max_length=255) site = models.CharField(null=True, blank=True, max_length=255)s created = models.DateTimeField(null=True, blank=True, default=timezone.now) class Bilan(models.Model): agregat = models.CharField(null=True, blank=True, max_length=255) SCF = models.CharField(null=True, blank=True, max_length=255) canva = models.ForeignKey('Canva', null=True, blank=True, on_delete=models.CASCADE, related_name='bilan_canva') How can I filter the Bilan class by the "created" attribut in the Canva class? -
Django Authentication Via Http With Websockets
I'm doing this - Load single page application - an apollo client is initialised with a websocket and http link. This happens when the user is logged out, let's say. The user then logs in without a page reload. The graphql response now contains the session cookie. Problem - whilst subsequent http requests include the session cookie the websocket connection does not. How do people solve this problem? I'm guessing on the client I could either make all communication with the server via websockets, or, create a new apollo client upon successful sign in and use this for subscriptions. Is it possible though to somehow pass the session cookie to the websocket already established on the client? I'm using django channels. I know it has a login function but this is logging in the user who has made a request via websockets I believe. This is for a chat app. But websockets are obviously common within most web apps. For example a notification system. Of course with most web apps you'd use http and websocket. So I'm wondering how people go about this. -
How to Create user objects with CreateAPIView in django
i need create class with CreateAPIView for create new object class Register(CreateAPIView): permission_classes=(AllowAny) serializer_class = UserSerializer def perform_create (self,serializer): obj = serializer.save(user=self.request.user) return Response({ "id": obj.id, "username": obj.username, }, status=status.HTTP_201_CREATED, content_type='application/json') but this code dosent work and And shows the following error : TypeError: init() takes 1 positional argument but 2 were given What should I do? -
How to look up a field value using foreignkey in Django
I have the following models: class Camera(models.Model): url = models.CharField(max_length=300, unique=True) camera_number = models.IntegerField(null=False, blank=False, validators=[ MaxValueValidator(1000), MinValueValidator(1)]) camera_name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField(max_length=100, null=True, blank=False, unique=True) class BaseImage(models.Model): url = models.ForeignKey(Camera, on_delete=models.CASCADE) base_image_filename = "base_images/" + str(Camera.slug) + "/%H" image = models.ImageField(max_length=300, upload_to=base_image_filename) What I am trying to do is to create the filename in BaseImage that contains the data in the slug variable of the corresponding Camera record. A camera can have many BaseImages but each BaseImage can only match to one Camera. What I get in the name is something like "base_images/<django.db.models.query_utils.DeferredAttribute object at 0x7f6006bd9b70>/20/camera_1.jpg". What do I need to change to get the slug field value as part of the filename ? -
Getting data from parent to child - FE or BE, how?
I'm learning Django and React. I'm trying to get some data from Order to TranspOrder. Order -< TranspOrders In the model Order (orders/model.py), I have a field total_allowed_amount and a function get_total_remaining_amount(self), which calculates total_allowed_amount - total_consumed_amount and returns the result. In OrderDetailSerializer I have a field total_remaining_amount (source= "get_total_remaining_amount" - I assume this means it gets the dafa from that function). So, in the frontend I have OrderDetails.js (Order) React component which displays the two fields total_allowed_amount and total_remaining_amount. Now I need to display these two fields also on TranspOrderDetails.js (TranspOrder), but can't figure out a way to do it. Not even sure if it is correct to do it via back- or frontend. This is very annoying, as it seems to be a very basic thing. I've tried writing functions in the model TranspOrder (transporder/models.py) to bring these into this model from Orders, so I can then access them from the FE (I think that creating same fields for them in this model is not a good idea): def get_order_total_allowed_amount(self): if not self.order.total_allowed_amount: return None return self.order.total_allowed_amount def get_order_total_remaining_amount(self): if not Order.total_allowed_amount: return None return self.get_total_remaining_amount(Order) I've also tried to import these from OrderDetails.js into TranspOrderDetails.js, as such: … -
Django Rest Framework - response.set_cookie() not setting cookie in browser but working in postman and in browsable api
I am struggling with setting jwt token in httponly cookie. I tried many solution but not working. I am working with localhost "127.0.0.1" but when I try to login the cookies sent by server not display in my frontend working at "127.0.0.1:5501" but if I try with Browsable api working at "127.0.0.1:8000" it works fine and I can check my cookies easily. I noticed a weird thing too. If I login via my frontend "127.0.0.1:5501", cookies not set but if I try with browsable api working at "127.0.0.1:8000" and then switch to my "127.0.0.1:5501" tab I can see that cookies their too. This a very Weird thing and I don't know the reason behind this. Please help me to resolve this issue. Views.py class LoginView(APIView): def post(self,request,format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) csrf.get_token(request) response.data = {"Success" : "Login successfully","data":data} return response else: return Response({"No active" : "This account is not active!!"},status=status.HTTP_404_NOT_FOUND) else: return Response({"Invalid" : "Invalid username …