Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
makemigrations/migrate error django.db.utils.OperationalError: no such table
I have an application that I have made using PostgreSQL as a database management system, but due to a series of things that have happened, now I want to use SQLite, but when I run makemigrations or migrate, it throws me the error django.db.utils.OperationalError : no such table: blogapp_category. With PosgreSQL it works perfectly, but I can't get it to work with SQLite ... (I have also tried to deploy the application with heroku and got the same error ...) This is the traceback: Traceback These are my models: blogapp\models.py class Category(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(to=User, on_delete=models.CASCADE) # body = models.TextField() body = RichTextField(blank=True, null=True) post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='uncategorized') # category podría ser un ManyToManyField # https://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django likes = models.ManyToManyField( to=User, related_name='blog_posts', blank=True) # null has no effect on ManyToManyField snippet = models.CharField(max_length=255) header_image = models.ImageField( blank=True, null=True, upload_to='images/') def get_likes(self): return self.likes.count() def __str__(self): return '{} - {}'.format(self.title, self.author) def get_absolute_url(self): # https://docs.djangoproject.com/en/3.1/ref/urlresolvers/#reverse return reverse('article_detail', args=[str(self.id), ]) # return reverse('home') class Meta: ordering = ['-post_date'] class Profile(models.Model): user = models.OneToOneField(to=User, null=True, on_delete=models.CASCADE) bio … -
Django - Filter by multiple values (Logical AND) on ManyToMany field
I'm trying to build job-candidate match system. I want to filter Candidates by Critical Skills needed for the Job. Every candidate has multiple skills. Every Job has multiple 'required' JobSkill which is a model that also contains importance of the skill. I want to filter my candidates and to get only candidates how have all the critical skills required for a job. A critical skill is defined as a JobSkill with importance = 3. For a given job 'job_1' I want to get the relevant candidates as follows: critical_skills = job_1.required_skills.filter(importance=3) relevant_candidates = Candidate.objects.filter('candidate how has all the critical_skills) models.py: class Skill(models.Model): title = models.CharField(max_length=100, blank=False, unique=True) class JobSkill(models.Model): skill = models.ManyToManyField(Skill) class Importance(models.IntegerChoices): HIGH = 3 MEDIUM = 2 LOW = 1 importance = models.IntegerField(choices=Importance.choices) class Job(models.Model): title = models.CharField(max_length=100, null=False) required_skills = models.ManyToManyField(JobSkill, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Candidate(models.Model): title = models.CharField(max_length=100, blank=False, null=False) full_name = models.CharField(max_length=100, blank=False, null=False) skills = models.ManyToManyField(Skill, blank=True) I would appreciate any help with this!! Thank you -
My HTML page won't print my django variable
First of all sorry for my bad english but i'm french. I am currently working on a django app and i'm trying to make my HTML page work but it won't and i dont know why. I followed the tutoriel but i edited some of the code to fit my purpose. And now my page won't print out my variable. I have python 2.7.5 and Django 1.11.29 My html page Now this is my code for the HTML : {% if True %} <p> Vrai </p> <li>{{ Thriller.title }}</li> {% else %} <p> faux </p> {% endif %} <ul> <p> Paragraphe : </p> <li>{{ Thriller.title }}</li> <li>{{ Thriller.id }}</li> </ul> My code for the Django part : This is in the models.py file : from django.db import models import datetime from django.utils.encoding import python_2_unicode_compatible from django.utils import timezone class Artist(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class Album(models.Model): reference = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) title = models.CharField(max_length=200, unique=True) picture = models.URLField() artists = models.ManyToManyField(Artist, related_name='albums', blank=True) def __str__(self): return self.title This is in the views.py file : from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from .models import Album, Artist, Contact, … -
Integrity Error: NOT NULL constraint failed - Django Rest Framework
models.py from django.db import models class client(models.Model): ROLES = ( ("Player", "player"), ("Umpire", "umpire"), ("Scorer", "scorer"), ("Organization", "organization"), ("Administrative", "administrative") ) client_id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=10) lastName = models.CharField(max_length=10, blank=True) email = models.EmailField() # * in the form.py widget=forms.PasswordInput as param passed into the model.CharField(). password = models.CharField(max_length=15) profileImage = models.ImageField( blank=True, null=True) coverImage = models.ImageField( blank=True, null=True) role = models.CharField(max_length=20, choices=ROLES) def __str__(self): return f"{self.firstName} {self.lastName}" GAMES = ( ("Basketball", "basketball"), ("Football", "football"), ("Cricket", "cricket"), ("Table-tennis", "tennis") ) class tournament(models.Model): tournament_id = models.AutoField(primary_key=True) title = models.CharField(max_length=60) organizer = models.ForeignKey( client, null=False, blank=False, on_delete=models.CASCADE) logo = models.ImageField(null=True, blank=False) game = models.CharField(max_length=20, choices=GAMES) fees = models.IntegerField() def __str__(self): return self.title class team(models.Model): name = models.CharField(max_length=30) logo = models.ImageField(default=None, blank=False, null=True) members = models.ManyToManyField(client) game = models.CharField(max_length=60, choices=GAMES, null=False, blank=False, default=None) def __str__(self): return f"{self.name} - {self.game}" views.py from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import clientSerializer, tournamentSerializer from .models import client, tournament # Client Views @api_view(['GET']) def index(request): return Response("API") @api_view(['GET']) def clientList(request): clients = client.objects.all() serializer = clientSerializer(clients, many=True) return Response(serializer.data) @api_view(['GET']) def clientDetail(request, clientId): singleClient = client.objects.get(client_id=clientId) serializer = clientSerializer(singleClient, many=False) return Response(serializer.data) @api_view(['POST']) def clientCreate(request): serializer = clientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['POST']) … -
how to save JSON data in Django using forms
when I am printing new_data I'm getting JSON data in CMD but I don't know how do I verify and save it in the database? I tried to save but I'm getting AttributeError at /attendance/ so please suggest to me how to solve it . [ { "1220":"present", "1221":""present", "1223": "present", "1223": "present" }}, models.py from django.db import models class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class Meta: ordering = ('name',) verbose_name_plural = 'Student Profile' def __str__(self): return self.name class studentAttendance(models.Model): CHOICES = ( ('present', 'present'), ('absent', 'absent'), ) name = models.ForeignKey(studentProfile, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=10, choices=CHOICES) date = models.DateField(auto_now=True) class Meta: verbose_name_plural = 'Student Attendance' def __str__(self): return self.name.name views.py def studentAttendanceView(request): student_status = studentProfile.objects.all() if request.method == "POST": my_data = ast.literal_eval(request.POST.get('passedJSON')) new_data = json.dumps([my_data]) save_data = studentAttendanceForm(new_data) if save_data.is_valid(): cd = save_data.save() cd.author = request.user cd.save() cd.refresh_from_db() name = save_data.cleaned_data.get('name') messages.success(request, f'Attendance submitted for {name} ') else: messages.error(request, 'Please check An Error occurred') else: save_data = studentAttendanceForm() return render(request, 'attendance.html', {'save_data': save_data, 'student_status': student_status}) -
Django: render template after AJAX POST request in view using context
Simple question but can't find the answer. I submit an AJAX post request from my template template1.html, my view function uses the AJAX POST data to lookup objects/context variables from the database. Then I simply want to render a different template template2.html from this view using those context variables as template tags in this next template (template2.html). I do NOT want to use the AJAX success call-back function to load the next template (because I don't want the context variables displayed in the URL in the GET request). Please help. -
Overwrite django admin delete_queryset's "short_description"
I've been overwriting django's delete_queryset in my app (mainly to provide custom bulk deletion). I can't find the way to overwrite the "short_description" of this method. For custom methods, you can easily use the short_description attribute, for instance : class MyAdminModel(admin.ModelAdmin): def dump_model(self, request, queryset): pass dump_model.short_description = "My description" But this won't work : class MyAdminModel(admin.ModelAdmin): def delete_queryset(self, request, queryset): pass delete_queryset.short_description = "My description" I've tried every method/attribute of the standard delete_queryset (within the __init__ method after a super() call that is) without finding anything useful, though I might have missed something. I've also gave it a try deleting the standard method using delattr (also in __init__), though it seems a bit clumsy. It also fails, throwing an AttributeError : class MyAdminModel(admin.ModelAdmin): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) delattr(self, "delete_queryset") -
Django Custom Model, Email Field disable for filling when Create User by Admin
I changed default User Model to my custom usermodel and use email for login. After login to admin and trying to create new user, the email field can not be filled. Like the screenshot below. I deleted db.sqlite3 while solving someother problems. But already re-build later. python manage.py createsuperuser still work. I can create superuser through terminal. Here the code | ./accounts/admin.py | from django.contrib import admin from django.contrib.auth.admin import UserAdmin # Register your models here. from .models import Account class AccountAdmin(UserAdmin): list_display = ('email', 'date_joined', 'last_login', 'is_admin') search_fields = ('email',) readonly_fields = ('email', 'date_joined', 'last_login') ordering = ('email',) # solution for E033 filter_horizontal = () list_filter = () fieldsets = ( (None, {'fields': ('email', 'password')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }), ) admin.site.register(Account, AccountAdmin) | ./accounts/backends.py | from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailAuthBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): UserModel = get_user_model() if email is None: email = kwargs.get(UserModel.USERNAME_FIELD) if email is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(email) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if … -
How should I save to the database?
I have created a Customer model in Django and am not able to save the data to the database table and when I click the signup button it just redirects me back to the home page. I have attached below the customer model and the signup function. ...please help me resolve the issue. customer.py from django.db import models class Customer(models.Model): first_name= models.CharField(max_length=50) last_name= models.CharField(max_length=50) phone=models.CharField(max_length=15) email=models.EmailField() password=models.CharField(max_length=500) def register(self): self.save() views.py def signup(request): if request.method == 'GET': return render(request, 'signup.html') else: postData=request.POST first_name=postData.get('firstname') last_name=postData.get('lastname') phone=postData.get('phone') email=postData.get('email') password=postData.get('password') print(first_name,last_name,phone,email,password) customer=Customer(first_name=first_name,last_name=last_name,phone=phone,email=email,password=password) customer.register() return HttpResponse("Signup success") signup.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="p-4 m-4"> <div class="col-lg-5 mx-auto border rounded pt-4"> <h3 class="alert alert-light border rounded" >Create An Account</h3> <form action="/" method="POST"> {% csrf_token %} <!--firstname--> <div class="form-group"> <label for="">First Name</label> <input type="text" name="firstname" id="" class="form-control form-control-sm" placeholder="Mike"> </div> <!--lastname--> <div class="form-group"> <label for="">Last Name</label> <input type="text" name="lastname" id="" class="form-control form-control-sm" placeholder="Ross"> </div> <!--phone--> <div class="form-group"> <label for="">Phone No</label> <input type="text" name="phone" id="" class="form-control form-control-sm" placeholder="9876543210"> </div> <!--email--> <div class="form-group"> <label for="">Email</label> <input type="email" name="email" id="" class="form-control form-control-sm" placeholder="abc@gmail.com"> </div> <!--password--> <div class="form-group"> <label for="">Password</label> <input type="password" name="password" id="" class="form-control form-control-sm" placeholder="********"> </div> <div class="form-group"> <input class="btn btn-sm … -
Django allall send verification code instead of verification link
I am using Django allauth for rest API. Currently, when I request password reset, then Django sends me email containing a link which you have to go to in order to verify your email. But i want so that Django send an email with a verification code which put another api endpint to verify the account? My code are below: settings.py file ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True REST_USE_JWT = True JWT_SERIALIZER = True and Installed app [ ''' 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'rest_auth', 'rest_auth.registration', ''' ] this is my current urls of built in viwes path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), path("api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"), path('rest-auth/', include('rest_auth.urls')), #for forget password api endpoint path('rest-auth/registration/', include('rest_auth.registration.urls')), # handle the error: https://github.com/iMerica/dj-rest-auth/issues/9 # https://django-allauth.readthedocs.io/en/latest/configuration.html path("account-inactive/", AccountInactiveView.as_view(), name="account_inactive"), re_path(r'^rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), Can anyone help me in this case? how can i send verification code to verify instead of verificatin link? I am using this lib : https://django-rest-auth.readthedocs.io/en/latest/ https://django-allauth.readthedocs.io/en/latest/ -
"curl: (56) Recv failure: Connection reset by peer" after "curl --unix-socket /run/gunicorn.sock localhost"
I'm trying to deploy a django app to DigitalOcean but when I try to activate gunicorn with curl --unix-socket /run/gunicorn.sock localhost it says curl: (56) Recv failure: Connection reset by peer. I'm literally following a tutorial made by digitalocean but it doesn't shows how to solve this error. What do I have to change? my /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=sammy EnviromentFile=/home/sammy/mysite/env WorkingDirectory=/home/sammy/mysite ExecStart=/home/sammy/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mysite/locallibrary.wsgi:application [Install] WantedBy=multi-user.target my /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target -
using mixin with a def
I m using this Accessmixin on generic.views: class OrganisorAndLoginRequiredMixin(AccessMixin): """Verify that the current user is authenticated and is an organisor.""" def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated or not request.user.is_organisor: return redirect("home") return super().dispatch(request, *args, **kwargs) I want to use it on a def. I tried this but I've error bellow. @OrganisorAndLoginRequiredMixin() def AgentUpdateView(request, pk): obj = Agent.objects.filter(pk=pk).first() if obj is None: return render(request, "404.html", { "Instance": pk }) else: form = AgentModelForm(instance=obj.user) Error: TypeError: 'OrganisorAndLoginRequiredMixin' object is not callable -
Django CSRF cookie not set: using Ajax Cross site
I have two parts of my code first is a frontend running on localhost:3000 via simple python HTTP server and a Django server running on localhost:8080, what's happening in here is the frontend is making a cross-site POST request to Django server but its been getting a Forbidden (CSRF cookie not set.) error. I know this problem has been asked about so many times but I don't seem to find a solution. I don't have any experience requesting a POST call in Django like this, not using DRF but endpoints of our own. The Problem Code: firstly the frontend shall make a get request for a csrf token to /api/csrf/ views.py: def get_csrf(request): # print(get_token(request)) return JsonResponse({ 'detail': 'CSRF cookie set', 'X-CSRFToken': get_token(request) }) After getting the value, the token is assigned to the cookie and a hidden element via main.js: success: function (response, status, xhr) { $('.csrftoken').attr('value', response['X-CSRFToken']); setCookie("csrftoken", response['X-CSRFToken']); } The code above works fine and we get the value, at the start, it was like this but was not working so I changed it like: xhr.getResponseHeader("X-CSRFToken") -> response['X-CSRFToken'] Now whenever the frontend makes a POST call to the back end with header:{ 'X-CSRFToken': token} running on localhost:8080 … -
How to use @font-face in django?
SO I downloaded a font and I have woff2 , woff and ttf files inside a fonts directory inside my static folder. Directory structure : project\project\static\fonts STATIC_URL = '/static/' STATICFILES_DIRS = [(os.path.join( BASE_DIR, "project", "static"))] style.css is located in static folder too @font-face { font-family: kinder_boyregular; src: url("{% static '../fonts/kinder-boy-regular-webfont.woff2' %}") format('woff2'), url("{% static '../fonts/kinder-boy-regular-webfont.woff' %}") format('woff'), url("{% static '../fonts/kinder-boy-regular.ttf' %}") format("truetype"); font-weight: normal; font-style: normal;} .header{ width: 800px; width: 300px; margin: 5px; text-align: center; border: 1px green; } .header h4{ font-family: "kinder_boyregular"; } html <div class="container"> <div class=header> <h4>Sparison</h4> </div> </div> But when I load the page, the h4 font doesn't change. What could be the issue? -
Django - add ModelTranslation to already registered model
I want to add fields in my db to translate. I want to use modeltranslation link here. I added my model to translation.py: from .models import GameTask class GameTaskTranslationOptions(TranslationOptions): fields =('name', 'description', 'button_text') translator.register(GameTask, GameTaskTranslationOptions) Now I want to add admin integration. I already added GameTask to admin: @admin.register(GameTask) class GameTaskAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'category', 'game', 'cycle_type', 'points', 'link_to_validity') search_fields = ('name', 'category') link_to_validity = link_to_validity What is the best way to create this connection? -
How do I extend a Django admin form's clean() function?
I have a Django 3.0 Model and associated Admin Add Form. I would like to validate entered data against other data being entered at the same time, the way you can for normal Forms -- making sure two password fields match, for example, or making sure the email and backup email fields are different. It seems like the best way to do this is to extend the clean() function for the Add page's Form, because that's the function you'd use for a normal Form. The documentation seems to give hints that this might be possible, but it doesn't give enough information to put it all together. Web searches for "Django extend Admin Form" return results only for extending the template. How do I extend a Django Admin Add Form's clean() function? -
Django url with parameters for http GET POST and DELETE request
I want to have url like localhost/path/?page=1&per_page=5. The page and per page are optional parameters. How should the URL look like. In views I want to use these parameter in raw PostgreSQL query. -
django - Mutual relations between models: How to create instances?
With a model like class Restaurant: default_pizza = models.OneToOneField('Pizza', on_delete=models.PROTECT) class Pizza: served_in = models.ForeignKey(Restaurant, on_delete=models.CASCADE) how can I create a new restaurant object and a corresponding default_pizza object at the same time? A restaurant can serve many pizzas, but only one will be the default pizza. -
How can convert this sql query into django queryset
This is my DjangoQuery bills = BillMaster.objects.filter(pay_type=1, customer=2).values('order_id', 'customer_id', 'invoice_no', 'grand_total').annotate(paid_amount=Coalesce(Sum('creditpaymentdetail__amount'), 0)) bills = bills.values('customer_id').annotate(gt=Coalesce(Sum('grand_total'), 0)) which is equivalent to postgreSQL query : SELECT "bill_billmaster"."customer_id", COALESCE(SUM("bill_billmaster"."grand_total"), 0) AS "gt" FROM "bill_billmaster" LEFT OUTER JOIN "credit_management_creditpaymentdetail" ON ("bill_billmaster"."id" = "credit_management_creditpaymentdetail"."bill_master_id") WHERE "bill_billmaster"."pay_type" = 1 GROUP BY "bill_billmaster"."customer_id" But I want to achieve this postgreSQL query: select customer_id, sum(gt) gt from ( SELECT "bill_billmaster"."customer_id", "bill_billmaster"."grand_total" AS "gt" FROM "bill_billmaster" LEFT OUTER JOIN "credit_management_creditpaymentdetail" ON ("bill_billmaster"."id" = "credit_management_creditpaymentdetail"."bill_master_id") WHERE "bill_billmaster"."pay_type" = 1 GROUP BY "bill_billmaster"."customer_id", grand_total ) R group by customer_id -
Using Django's autoreloader for Celery worker, autoreloading doesn't get triggered for changes in some files
I am using this strategy to make the Celery worker respond file changes and reload itself. It works well. However, for some files, like one of the tasks.py module which contains a task for the Celery worker doesn't trigger the autoreload when changed, while another tasks.py in another app triggers. Both of these modules have identical lines: app1/tasks.py: from main import celery_app @celery_app.task(bind=True) def queue_update(self, json_obj): ... app2/tasks.py: from main import celery_app @celery_app.task(bind=True) def new_job(self, job_temporary_id): ... I make a change in the first file and it triggers autoreloading, but the second one doesn't. Celery discovers these tasks modules successfully as I see in the logs: my_celery_worker | . app1.tasks.queue_update my_celery_worker | . app2.tasks.new_job -
Python unit test assertEqual throwing assertionError in one machine but not in others
I've built a test case for a GraphQL mutation where I save inputs (priceOne and priceTwo) of type graphene.Decimal() into the model MyObj fields of type models.DecimalField and I return MyObj in the response. The code below returns OK, test successful in my machine, let's call Machine A, and it also works in Machine B, but doesn't work on Machine C. Machine A: Windows 10, python 3.7 => OK Machine B: Ubuntu, python 3.8.0 => OK Machine C: Ubuntu, python 3.8.5 => F import json from mixer.backend.django import mixer from core.schema import schema from my_app.models import MyObj from my_app.tests.utils import CustomGraphQLTestCase MY_MUTATION = ''' mutation MyMutation($input: MyInput!) { myMutation(input: $input) { success myObj { id price } } } ''' class TestMyMutation(CustomGraphQLTestCase): GRAPHQL_SCHEMA = schema def setUp(self): self.my_obj = mixer.blend(MyObj) self.input_data = { 'id': self.my_obj.id, 'priceOne': '2000.00', 'priceTwo': '0.10', } def test_my_mutation_success(self): response = self.query(MY_MUTATION, input_data=self.input_data) content = json.loads(response.content) self.assertResponseNoErrors(response) self.assertTrue(content['data']['myMutation']['success']) self.assertEqual(content['data']['myMutation']['myObj']['priceOne'], 2000.00) self.assertEqual(content['data']['myMutation']['myObj']['priceTwo'], 0.10) We fixed the issue by transforming both arguments of assertEqual to Decimal and for the 0.10 we had to use quantize. self.assertEqual(Decimal(content['data']['myMutation']['myObj']['priceOne']), 2000.00) self.assertEqual(Decimal(content['data']['myMutation']['myObj']['priceTwo']).quantize(Decimal(10)**(-2)), Decimal(0.10).quantize(Decimal(10)**(-2))) Question: Why doesn't it work on Machine C? The CustomGraphQLTestCase: import json from django.core.serializers.json import DjangoJSONEncoder from graphene_django.utils import GraphQLTestCase … -
how do i edit a post which would be in a mysql table in flask?
i have created a simple blog site using flask where a user login and create a blog and can edit it or delete it. the blog post are saved in a separate db. but idk how can a user edit the blog because in the backend we will require the id for that blog which isnt stored with the posted blog. I can pass the blog id using request.args.get() but that will send data in get method and that is not secure tbh. -
How to get visitors geolocation (country and city ) using django?
i have a django project and need get visitors location using HTML5 (navigator.geolocation) , since im new with django , how to use and save navigtor.geolocaiton data in django ? anybody could help please? -
Assign value to logged in user in Django
I have a Django app where I am trying to assign a bank variable to each user, set to 100 by default. I have the following model in models.py : class Wallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bank = models.FloatField(default=100) which is then used in views.py: class BitgainzView(View): def get(self, *args, **kwargs): user = User.objects.get(username=self.request.user) context = {'bank': user.wallet.bank} return render(self.request, "index.html", context) I then print bank in my html page. Two problems with this : if user is logged in : I get the error Exception Value: User has no wallet. which I think is because the schema for Wallet was created in relation to User, but never initialised for each user. if user is not logged in : Then the context in BitgainzView() cannot be loaded, and I am also getting an error. Should I make separate views in that case ? Or should I treat different cases inside this function ? Thank you in advance. -
when date is selected from datepicker then How to display date in html table cell using jQuery
When the user selects the particular date from datepicker, I want to display date in first cell of table and by default it should show current date. How can I fetch date from the datepicker ? Here top of table I am using Datepicker jQuery. Table +-----------+---------+---------+-------+ | Date | Day | Project | Task | +-----------+---------+---------+-------+ | 3/12/2021 | Friday | | | +-----------+---------+---------+-------+