Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2 installed on M1 running MacOS Big Sur, but unable to run local server
I have the new (2021) Macbook Air running the Apple M1 chip. I have set up my django application, which uses postgresql, and I have created a virtualenv running Python 3.9.2. Have installed Python directly from the macOS 64-bit universal2 installer on python.org. After much difficulty, I was finally able to install psycopg2 using: env LDFLAGS="-L/opt/homebrew/opt/openssl@1.1/lib -L/opt/homebrew/opt/readline/lib" pip3 --no-cache install psycopg2-binary==2.8.6 I am able to SSH into my PostgreSQL DB, but when I run python manage.py runserver, I get the following error (abridged due to length). File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/contrib /auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/contrib /auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/mode ls/base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/mode ls/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/mode ls/options.py", line 208, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/__in it__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/util s.py", line 207, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/util s.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__ init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/back ends/postgresql/base.py", line 29, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/ … -
Is this a Django bug with annotation?
Redefining models.query.QuerySet. class TransactionQuerySet(models.query.QuerySet): def delete(self, *args, **kwargs): wallets = [] wallet_transactions = self.values('wallet').annotate(amount = Sum('amount')) ... ... I got: wallet_transactions = <TransactionQuerySet [{'wallet': 1, 'amount': 666}, {'wallet': 1, 'amount': 1000}, {'wallet': 1, 'amount': 500}, {'wallet': 1, 'amount': 1000}]> Why aggregation in annotation doesn't work??? If you write right there: Transaction.objects.all().values('wallet').annotate(amount = Sum('amount')) then everything is ok and I get: <TransactionQuerySet [{'wallet': 1, 'amount': 3166}]> self и Transaction.objects.all() - одно и тоже <TransactionQuerySet [<Transaction: Transaction: B3>, <Transaction: Transaction: B3>, <Transaction: Transaction: B2>, <Transaction: Transaction: B1>]> Is it a Django bug? -
Django translate data from the DB {{ profession }}
Is it possible to translate DB entries? I have a dependent dropdown story that i need to translate. But i cant translate the dropdown fields, the fields come from other models and har hard coded. I can use HTML with JQ to achive this but i want to skip the manual labor to translate everytime new profession or professioncategories are added. class Profession(models.Model): name = models.CharField(max_length=30), def __str__(self): return self.name class Professioncategory(models.Model): profession = models.ForeignKey(Profession, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Skills(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(_('Active'), default=True) profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True) professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True) posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('last updated'), auto_now=True) years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) -
Using Google OAuth with React-Django Application
I am working on a web application with ReactJs frontend and Django backend. In this app, I will need to send calender notifications to the users and overall need a user authentication feature for which I planned to use google oauth. From react, I am able to log in the user and get the access tokens but since they expire in an hour, I planned to get the authorization code and use it to get the refresh/access tokens from the backend whenever a user logs in/needs to send API request. The issue is that I am not able to find any good resource on how to get refresh tokens from the backend given I have the authorization code. Most of the HTTP based methods I have found are very outdated and I have searched some of the google documentation but have not found anything worthwhile. Since I could not find any package that would handle this, I have been trying to send POST request to the URL mentioned here (https://developers.google.com/identity/protocols/oauth2/web-server#python_1) but only get a 400 response. Below are 2 methods I have tried. to_send={'code':user_data['code'], 'client_id': cl_id , 'client_secret': cl_secret, 'redirect_uri':'http://localhost:3000/', 'grant_type':'authorization_code'} test=requests.post('https://oauth2.googleapis.com/token', data=to_send) print(test) credentials = service_account.Credentials.from_service_account_file('path/key.json') scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive.metadata.readonly']) … -
Script function not found : doGet
These are the codes i m working with script_url is the google script web app deployed sample.py import requests import datetime url = "script_url?client_name={}&client_address={}&company_name={}&company_address={}&vessel_name={}&po={}&id={}&date={}&item1={}&item2={}&item3={}&cost1={}&cost2={}&cost3={}&total={}" name_client = ["inder", "sawpnesh", "kajal"] address_client = ["addInder", "addswapnesh", "addkajal"] name_company = ["ospl", "ospl", "ospl"] address_company = ["addospl", "addospl", "addospl"] vessel_name = ["redlips", "elizabth", "jack"] po = ["EWDCC", "wefwec", "asxwq"] invoice_ids = ["1", "2", "3"] item1 = ["keyboard", "mouse", "screen"] item2 = ["mouse", "screen", "keyboard"] item3 = ["screen", "keyboard", "mouse"] cost1 = ["1000", "500", "2000"] cost2 = ["500", "2000", "1000"] cost3 = ["2000", "1000", "500"] i = 0 for invoice_id in invoice_ids: total = cost3[i] + cost2[i] + cost1[i] print("processing ", invoice_id) response = requests.get( url.format(name_client[i], address_client[i], name_company[i], address_company[i], vessel_name[i], po[i], invoice_id, datetime.date.today(), item1[i], item2[i], item3[i], cost1[i], cost2[i], cost3[i], total )) # response = requests.get( # url.format(invoice_id, cust_names[i], add_streets[i], add_citys[i], issue_dates[i], last_dates[i])) print("file generated") response = requests.get(response.content) print("file downloaded") i += 1 with open("invoice{}.pdf".format(invoice_id), "wb") as f: f.write(response.content) # i += 1 google script app code.cs function createDocument(id,client_name,client_address,company_name,company_address,vessel_name,po,date,item1,item2,item3,cost1,cost2,cost3,total) { var TEMPLATE_ID = 'template_id'; var documentId = DriveApp.getFileById(TEMPLATE_ID).makeCopy().getId(); drivedoc = DriveApp.getFileById(documentId); drivedoc.setName("Invoice " + id+"/2021"); doc = DocumentApp.openById(documentId); var body = doc.getBody(); body.replaceText('{id}', id); body.replaceText('{client_name}',client_name); body.replaceText('{client_address}',client_address); body.replaceText('{company_name}',company_name); body.replaceText('{company_address}',company_address); body.replaceText('{vessel_name}',vessel_name); body.replaceText('{po}',po); body.replaceText('{date}',date); body.replaceText('{item1}',item1); body.replaceText('{item2}',item2); body.replaceText('{item3}',item3); body.replaceText('{cost1}',cost1); body.replaceText('{cost2}',cost2); body.replaceText('{cost3}',cost3); … -
Filtering, ordering and pagination in clean architecture django rest
I recently used clean architecture for my project. The project is divided into several sections according to clean architecture, each of which performs its tasks. But what confused me is that, I do not know how can I use filter and pagination class in this architecture. -
"NodeAlreadySaved " error when using djangocms publishing page changes
Encounter an error when using djangocms publishing page changes. when I ran tail -f /var/log/apache2/error.log, it returned: treebeard.exceptions.NodeAlreadySaved: Attempted to add a tree node that is already in the database, referer: http://47.95.254.172/?edit And when I allowed the settings.py DEBUG= True and click the 'Publish page changes' button: NodeAlreadySaved at /admin/cms/page/1/en/publish/ Attempted to add a tree node that is already in the database Request Method: POST Request URL: http://47.95.254.172/admin/cms/page/1/en/publish/ Django Version: 3.1.7 Exception Type: NodeAlreadySaved Exception Value: Attempted to add a tree node that is already in the database Exception Location: /root/env1/lib/python3.8/site-packages/treebeard/mp_tree.py, line 326, in process Python Executable: /root/env1//bin/python Python Version: 3.8.5 I have run python manage.py cms fix-tree but it did not work. While python manage.py cms check returned 10 checks successful!. I deployed the djangocms project with: apache2.4.41 mod-wsgi 4.8.0 django 3.1.7 django-cms 3.8.0 The python version in venv is 3.8.5, and mod-wsgi was compiled by python3.8.5 in the venv. Thank you for the help! -
How can store Multiple checkbox value to single user
I am trying save multiple id of products from checkbox to a specific user, but i select multiple values and submit them it show the error. ' Field 'id' expected a number but got ['13', '14', '22']. ' when i select any category from drop down menu it just only show last added category, not show that category which i select view.py class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'products': products, 'selectedCategory': categoryId} return render(request, self.template_name, args) def post(self, request, vendor_id): categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.POST.getlist("ProductSelect") try: vendor = VendorCategory( vendor_id=VendorModel.objects.get(id=vendor_id), category_id=categoryobj, product_id=productobj, ) vendorCate.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory" > <option disabled="disabled" value="True" selected="{{ selectedCategory|yesno:"yes, no"|safe }}"> Select Category</option> {% for category in categories %} <option value="{{ category.id }}" selected="{% if category.id == selectedCategory %} {% endif %}"> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> <form method="post"> <input type="hidden" value={{ selectedCateogry }} name="ProductSelect"> {% csrf_token %} <label> {% for product in products%} <input type="checkbox" name="ProductSelect" value="{{ product.id }}" >{{ product.name … -
How could i get an object correctly from database in a different server in python?
I am trying to work with a machine learning and a web server with django, and both my web and machine learning server use the same dockerized postgres database. Machine learning server creates machine learning models and writes them to the database by using pickle. I have a Regressor class in machine learning server like this: class Regressor: def __init__(self): self.predictions = [] self.yTrue = [] self.predDiffs = [] self.model = object self.name = "" #some methods below and i have a class that creates an appropriate database table for orm technique class RegressorTable(DeclarativeBase): __tablename__ = "ml_models" id = Column(Integer, primary_key=True) regressorName = Column(String) regressorModel = Column(LargeBinary) and both in machine learning and django web server, i have 2 functions in order to convert models to binary and binaries to model def modelToBinary(model): return pickle.dumps(model) def binaryToModel(data): return pickle.loads(data) Here is my method in the machine learning server to save the Regressor models for the database: def saveModelsToDb(predictorArray): for predictor in predictorArray: predictorForTable = RegressorTable() predictorForTable.regressorName = predictor.name predictorForTable.regressorModel = modelToBinary(predictor) DBSession.add(predictorForTable) DBSession.commit() The predictorArray in the above code contains Regressor objects. When i try to save and load models in machine learning server, i can successfully save, load and … -
Realtime sharing of Website content to other user
I have a django web application with a map view using openlayers. I have to develop a map sharing screen in real time to other user in the application for the real time view/suggestion for the edit. How to develop the real time web content sharing system. -
Django. Model function for avatar
I wrote a function for the profile model so that if the profile does not have an avatar, there will be a default picture. But this function works only when the profile has a picture, and when it does not exist, there is the absence of any image tag . How can I write the function correctly so that it displays a picture from the media folder of the project directory? @property def avatarURL(self): try: url = self.avatar.url except: url = 'media/avatar.svg' return url ── ./media │ ├── ./media/avatars │ ├── ./media/avatar.svg │ └── ./media/images HTML <img src="profile.avatarURL" alt="Profile picture class="round"/> -
How to show Many-to-Many Field on Django Admin Panel?
I have 2 models, Product and Tag. The relation between product and tag is Many-to-Many Relationship. How to show "tags" field on django admin panel? Currently the value is None when I am using the code below models.py class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) admin.py @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['id','name','price','category','tags'] list_display_links = ['name'] def tags(self): return self.tags.name -
REST Framework — Serializing many-to-many. Create and Save
I am using django-restframework for my API. My problems: I can't validate data. Need to create "regions" and nested with courier. Regions send as a list in json. But when validating the data, I get the following errors: error_valid {'regions': [{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')] How I can created models with this json POST request? The POST json: { "data": [ { "courier_id": 10, "courier_type": "foot", "regions": [1, 12, 22] }, { "courier_id": 11, "courier_type": "bike", "regions": [22] },.. ] } My models.py: class Regions(models.Model): region_id = models.PositiveIntegerField(unique=True) def __str__(self): return self.region_id class Courier(models.Model): courier_id = models.PositiveIntegerField(unique=True, ) courier_type = models.CharField(max_length=4, choices=TypeCourier.choices, blank=False, ) regions = models.ManyToManyField("Regions", through=RegionsCouriers, through_fields=("courier", "region" ), ) Regions will need to be created together with the post request my serializers.py class RegionsSerializer(serializers.ModelSerializer): class Meta: fields = "__all__" model = Regions class CourierSerializerPost(serializers.ModelSerializer): regions = RegionsSerrializer(many=True) class Meta: model = Courier fields = "__all__" my View.py class CourierView(APIView): def post(self, request): data = request.data["data"] couriers_add = [] couriers_fail = [] for record in data: serializer = CourierSerializerPost(data=record) if serializer.is_valid(): courier_id = … -
Unable to update many to many fields in Django Rest Framework
I have a Product model which has many fields, some of them have many to many relationships with other models, for eg the Category model. I am able to update other fields but I am stuck at updating the m2m fields from the JSON payload sent from the frontend. I have the logic, but can't write the code. I have to first remove the existing categories which are associated with that product and add the new categories that are on the payload from the ids. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? best_seller = models.BooleanField(default=False) top_rated = models.BooleanField(default=False) My views: class ProductUpdateView(UpdateAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductUpdateSerializer My serializers: class ProductUpdateSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller', 'rating','availability','warranty','services',] def update(self, instance, validated_data): instance.featured = validated_data.get('featured',instance.featured) instance.top_rated = validated_data.get('top_rated', instance.top_rated) instance.brand = validated_data.get('brand', instance.brand) instance.collection = validated_data.get('collection',instance.collection) instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) #category_logic category_data = validated_data.get('category') #new_category = validated_data.pop('category') product = … -
Creating a pagination using Django
I'm working on a small project using Django Rest Framework and i'm looking for a way to create pagination using Viewset, i checked the DJR documentation but i couldn't find any answer about doing pagination with Viewsit class, this is my code : class ContactView(viewsets.ViewSet): def list(self, request): contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data) -
TypeError: __init__() got an unexpected keyword argument 'use_required_attribute' - django
django(3.1.7) python(3.9.0) I've been working on putting an input validation for my modelformset and this is what I had come up this code is working well until today I don't what happen but suddenly this error shows up and it seems it all point towards the django package in my virtual environment so if anyone have any idea to fix this thank you. Also, if anyone knows a better way to validate a modelformset your answer would be much appreciated thank you. Forms.py from django.forms import modelformset_factory, DateTimeField, BaseModelFormSet from django.contrib.admin import widgets class OrderFormSetValidation(BaseModelFormSet): def clean(self): products = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue product = form.cleaned_data.get('product') quantity = form.cleaned_data.get('quantity') theme = form.cleaned_data.get('theme') flavor = form.cleaned_data.get('flavor') text = form.cleaned_data.get('text') price = form.cleaned_data.get('price') products.append(product) if isInvalidInput(product): raise forms.ValidationError(("This field is has invalid value")) OrderFormSet = modelformset_factory( Order, form=OrderFormSetValidation, can_delete=True, fields=('product','quantity','theme','flavor','text','price'), widgets={ 'quantity': forms.NumberInput(attrs={'placeholder':'0',}), 'theme': forms.TextInput(attrs={'placeholder':'Theme','maxlength':256}), 'text': forms.TextInput(attrs={'placeholder':'Text','maxlength':256}), 'price': forms.NumberInput(attrs={'placeholder':'0.00','step':1}) } ) Error Traceback (most recent call last): File "C:\Users\John\Envs\test\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\John\Envs\test\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\John\Envs\test\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\John\Envs\test\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\John\Envs\test\lib\site-packages\django\template\backends\django.py", line … -
Django: How to use AUTH_USER_MODEL
I have seen several posts and read the documentation about how it's best practice to set AUTH_USER_MODEL in settings.py, but do not see any actual examples on how to do that. I have tried several configurations but keep getting this error: AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed It doesn't even tell me where the error is occurring. Below are the methods I have tried: METHOD 1: from django.contrib.auth import get_user_model User = get_user_model() Then I would just reference my user like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) METHOD 2: from django.contrib.auth.models import User Neither worked, and I'm not sure how I would set AUTH_USER_MODEL in settings.py if I just want to use the standard user model. I'm not customizing the User object at all. I assume something like AUTH_USER_MODEL = 'django.contrib.auth.models.User' but i'm not sure. -
Setting up virtual environment in Django
i just started learning django and i am very confused in how to set up a virtual environment. i have successfully installed python: When i run python --version i get Python 3.8.1 and when i run python3 --version i get Python 3.8.1 My first problem is when i run which -a python3 i get this /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 /usr/local/bin/python3 /usr/bin/python3 Can someone help me understand why i have 3 locations where python3 exist? My 2nd problem is i have successfully installed virtaulenv and virtualenvwrapper when i run virtualenv --version i get: virtualenv 20.4.3 from /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/virtualenv/__init__.py and when i run virtualenvwrapper --version i get: -bash: virtualenvwrapper: command not found thats why when i run mkvirtualenv test i keep getting command not found. My third problem is what is the difference between virtualenv test and mkvirtualenv test? -
OSMWidget Django form location coodinates are incorrect
I have the following form field point = gis_forms.PointField(widget=gis_forms.OSMWidget( attrs={'map_width': 800, 'map_srid': 4326, 'map_height': 500, 'default_lat': 49.246292, 'default_lon'-123.116226, 'default_zoom': 7,})) The form is rendered in django as <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Submit for Review</button> </form> But when the data comes in POST the locations are incorrect. def register_storage(request): if request.method == 'POST': form = MyGeoForm(request.POST) if form.is_valid(): data=form.cleaned_data print(data.get('point')) print(data.get('point').srid) The SRID is showing up as 3857 and weird default coordinates -13645232.541356523 6283123.725041488 I thought it was my django version, but it is updated to 3.1.3 due to some functionality with GDAL. But no luck. Very lost here. -
multiple default values specified for column "id" of table "Transaction"
I'm trying to deploy a Django app to Heroku, and the moment I start doing the migrations with these commands: heroku run python manage.py makemigrations heroku run python manage.py migrate I get the following error: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "Transaction" This is the code from my Transaction Model: class Transaction(models.Model): """Modelo de Transaccion""" id = models.CharField(max_length=8, primary_key = True) TnType = models.ForeignKey(TransactionType, on_delete=models.CASCADE, blank=True, null=True, related_name='id_tn_type') userReceiver = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user_receiver', blank=True, null=True) userTransmitter = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user_transmitter', blank=True, null=True) amount = models.IntegerField(blank=True, null=True) creationTime = models.DateTimeField(default=datetime.now) concept = models.CharField(max_length=80, blank=True, null=True) STATUS = ( ('A','Active'), ('I','Inactive'), ) status = models.CharField(max_length=1,choices=STATUS, default='A') def __str__(self): return self.id class Meta: db_table = "Transaction" class TransactionAdmin(admin.ModelAdmin): list_display = ('id', 'userReceiver', 'userTransmitter', 'amount' ) I really don't understand this error, I've been trying a lot of things with no luck. I hope someone could help. -
Linking front-end to back-end in Django using vanilla javascript
I understand that you can use the fetch API to send data from the front-end to your backend to be processed by django views. I also know that you can use jquery API to do the "fetching of data. I am wondering if there are any other common methods using only javascript to send data from the front to the back without using the fetch api or jquery ajax. -
how to add otp authentication in django login page
Firstly, the login.html should ask for 'Enter OTP' once the email(username) is entered and submitted. This username is checked with user table if the user exists. If user exists , it should send OTP to the mobile registered for this user instance. On entry of the OTP, user should get appropriate message to reset password or get the home page. I don't want to use the django-otp app. What i have done so far: In the django accounts/registration/templates/login.html {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/login.css" %}"> {{ form.media }} {% endblock %} {% block bodyclass %}{{ block.super }} login{% endblock %} {% block usertools %}{% endblock %} {% block nav-global %}{% endblock %} {% block content_title %}{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} {% if form.errors and not form.non_field_errors %} <p class="errornote"> {% if form.errors.items|length == 1 %}{% trans "Please correct the error below." %}{% else %}{% trans "Please correct the errors below." %}{% endif %} </p> {% endif %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p class="errornote"> {{ error }} </p> {% endfor %} {% endif … -
Is there anyway to clear Firebase notoficaion programitally?
I am new to Firebase, I want to control the notification from django which is going to the android devices of the customer. I want to make sure that if the email if seen from any device either from desktop or any other means, the Firebase notification should be deleted, as the email is already seen. Any help will be appriciated. -
Django - Protect media files with django-wiki
In the past I managed to protect my images in other projects in the following way: urls.py urlpatterns = [ ... path('media/<str:filename>/', views.media, name="media"), ] settings.py #MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') views.py @login_required def media(request, filename): import os from mimetypes import MimeTypes content_type, encoding = MimeTypes().guess_type( os.path.basename(filename) ) if content_type is None or len(content_type) == 0: print(f'No content-type found for file: {filename}') content_type = 'text/plain' try: url = os.path.join( settings.MEDIA_ROOT, str(filename) ) with open(url.encode('utf-8'), 'rb') as f: resp = HttpResponse(f.read(), content_type=content_type) # resp['Content-Disposition'] = f'attachment; filename="{filename}"' resp['X-Robots-Tag'] = 'noindex, nofollow' return resp except IOError as ex: data = {'ERROR': str(ex)} print(data) return JsonResponse(data) With this, if someone tries to view for example an image via the url www.example.com/media/image.png, the user cannot see anything unless they are logged in. I need to use the django-wiki system https://github.com/django-wiki/django-wiki which I have installed in my existing project through pip install wiki. Now my project works together with the wiki system. Wiki system is installed in this path: /Users/{my_username}/.virtualenvs/{my_virtualenv_name}/lib/python3.9/site-packages/wiki/ Is there any way to protect images in the same way for the wiki system? I think modifying .../site-packages/wiki/ views is not a good idea and perhaps there is a better solution to … -
django - relation already exists (special problem)
I made changes, created a new branch, committed, then migrated (after makemigrations). But in that commit, it contained changes that I pulled remotely and it looked like my own. I did not want this because I work on a team, so I made a new branch with only my changes. The problem is, our database kept the migrations, but the code didn't. So when I try to migrate, I get "migration already exists." What do I do here? Is this a case where --fake would be useful? Any help is appreciated. Thanks in advance