Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django adding colon to the path out of nowhere
I have a pretty simple Django project based on the one from the tutorial that I am slowly morphing into my own app. It was working fine locally. I tried to deploy it to Heroku, so I made a few changes, but it was still working fine locally (I am still working on getting it to work on Heroku). But then I ran it once more and out of nowhere I am getting this error: Invalid argument: 'C:\\Users\\cusack\\PycharmProjects\\pythonProject\\website\\:\\index.html' So it is adding :\\ or \\: to the path for some reason. I have looked at settings.py, views.py, urls.py, and I can't find anywhere where I have told it to do this. My urls.py file looks (partially) like this: urlpatterns = [ path('', views.index, name='index'), path('images/random.png',views.my_image,name='randomImage'), path('admin/', admin.site.urls) ] The main page and admin both give this error, but 'images/random.png' works just fine. For the admin page, it is adding the extra :\\ before admin\\index.html. My views.py for this index is trivial: def index(request): return render(request, 'index.html') It happened when I was playing around with DEBUG and ALLOWED_HISTS, although changing them back to True and [] didn't seem to help. Any idea where this could be coming from? -
Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax
I've been working on a Django project, I'm using Pycharm community edition 2021 and Django version as 4.0.3, the problem is that , whenever I reload my site there would be no pictures shown which I want to display from another website. Error would be like "Indicate whether to send a cookie in a cross-site request by specifying its Same Site attribute", I have tried much more method to resolve this adding removing cookies but unable to solve it, as I dnt know whether these same site cookies would be in IDE , Django or chrome? {% extends 'base.html'%} {% block body %} <div class="container my-4 mx-4 py-8 px-8" > <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://api.unsplash.com/search/photos?&client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100 " alt="..."> </div> <div class="carousel-item"> <img src="https://api.unsplash.com/search/photos?client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="https://api.unsplash.com/search/photos?client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs- target="#carouselExampleControls" 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="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> {% endblock body %} -
how to place the images in the select of my template to make the language change?
it is very very basic but my inexperience does not make me see the error. Well, the flags don't appear, but it is the folder and also the path, because I have other images that have the same path, only instead of flags it says brands <select class="selectpicker" data-width="fit"> <option><img src="{%static 'assets/images/flags/spain.jpg' %}" alt="">English</option> <option><img src="{%static 'assets/images/flags/us.jpg' %}" alt="">Español</option> </select> -
Python Django "surrogates not allowed" error on model.save() call when text includes emoji character
We are currently in the process of building a system that stores text in a PostgreSQL DB via Django. The data gets then extracted via PGSync to ElasticSearch. At the moment we have encountered the following issue in a testcase Error Message: UnicodeEncodeError: 'utf-8' codec can't encode characters in position 159-160: surrogates not allowed We identified the character that causes that issue. It is an emoji. The text itself is a mixture of Greek Characters, "English Characters" and as it seems emojis. The greek is not shown as greek, but instead in the \u form. Relevant Text that causes the issue: \u03bc\u03b5 Some English Text \ud83d\ude9b\n#SomeHashTag \ud83d\ude9b\ translates to this emoji:🚛 As it says here: https://python-list.python.narkive.com/aKjK4Jje/encoding-of-surrogate-code-points-to-utf-8 The definition of UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF, which are reserved for use with the UTF-16 encoding form (as surrogate pairs) and do not directly represent characters. PostgreSQL has the following encodings: Default:UTF8 Collate:en_US.utf8 Ctype:en_US.utf8 Is this an utf8 issue? or specific to emoji? Is this a django or postgresql issue? -
django ModuleNotFoundError: No module named 'debug-toolbar'
I just tried to install the django-debug-toolbar. I believe I followed all the steps as indicated in the docs. I am using docker, so I included the following in my settings: if os.environ.get('DEBUG'): import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] After installing, I ran docker-compose build then docker-compose up -d. docker-compose logs and docker-compose exec web python manage.py collectstatic show the error ModuleNotFoundError: No module named 'debug-toolbar' The only thing I think I did differently from the docs is that I use pipenv. I exited docker-compose and then installed via pipenv install django-debug-toolbar. Debug toolbar is in my pipfile. FWIW I'm never sure if I'm supposed to exit docker-compose before install a module via pipenv (or if it matters). -
(django rest) JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError
In my django rest framework project when post data it works but when i have added validators it gives me error. here's serializers.py(with validator code) def starts_with_r(value): if value['0'].lower() != 'r': raise serializers.ValidationError('Name Should start with R') return value class StudentSerializer(serializers.Serializer): name=serializers.CharField(max_length=100, validators=[starts_with_r]) roll =serializers.IntegerField() city=serializers.CharField(max_length=100) views.py( this part to handle post request if request.method == 'POST': json_data=request.body stream=io.BytesIO(json_data) pythondata=JSONParser().parse(stream) serializer=StudentSerializer(data=pythondata) if serializer.is_valid(): serializer.save() res={'msg':'Data Created'} json_data=JSONRenderer().render(res) return HttpResponse(json_data,content_type='application/json') json_data=JSONRenderer().render(serializer.errors) and myapp.py from where i am trying to post data import requests import json URL="http://localhost:8000/studentapi/" def post_data(): data={ 'name':'rayan', 'roll':170, 'city':'Cumilla' } json_data=json.dumps(data) r= requests.post(url=URL, data=json_data) data=r.json() print(data) when i try to post data without the validators it works but when with validators it gives this error File "C:\Users\ITS\Desktop\django-rest\myapp.py", line 45, in <module> post_data() File "C:\Users\ITS\Desktop\django-rest\myapp.py", line 25, in post_data data=r.json() raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
How to load entities with manytomany relationships in django
class Category(models.Model): name= models.CharField(max_length=50) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name class SubCategory(models.Model): name= models.CharField(max_length=50) categories = models.ManyToManyField(Category) def __str__(self): return self.name @staticmethod def get_all_subcategories(): return SubCategory.objects.all() class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) category= models.ManyToManyField(SubCategory) def __str__(self): return self.name @staticmethod def get_products_by_id(ids): return Products.objects.filter (id__in=ids) @staticmethod def get_all_products(): return Products.objects.all() def productdetail(request,id): product1 = Products.objects.get(id = id) subcategoryname = product1.category.name categories = Category.get_all_categories() How to load a product, subcategory and category heirarchy in the view function -
Trouble with routing in django - page not found
I am not able to perform routing. error at /home: enter image description here urls.py: enter image description here views.py: enter image description here -
how to select an item multiple time in django m2m field in form
I am a beginner and learning django, here i want to let the user to select items multiple times in a m2m field, for example here i have a icecream model with flavor class linked to it in a m2m rel, when the form is displayed in the template i want user to select 1 option many times. my models: class IceCream(models.Model): hold_choice = ( ('Cone', 'Cone'), ('Cup','Cup'), ) type_name = models.ForeignKey('IceCreamType', on_delete=models.CASCADE, null=True, blank=True) flavor = models.ManyToManyField(Flavor, verbose_name='total scopes') toppings = models.ManyToManyField(Topping) holder = models.CharField(max_length=4, choices=hold_choice, default='Cone') number_of_icecreams = models.PositiveIntegerField(default=1) def __str__(self): return str(self.type_name) @property def total_scope(self): return self.flavor_set.all().count() the flavor model has some options: class Flavor(models.Model): CHOCOLATE = 'Chocolate' VANILLA = 'Vanilla' STRAWBERRY = 'Strawberry' WALLNUT = 'Wallnut' KULFA = 'Kulfa' TUTYFRUITY = 'Tuttyfruity' choices = ( (CHOCOLATE, 'chocolate scope'), (VANILLA, 'vanilla scope'), (STRAWBERRY, 'strawberry scope'), (WALLNUT, 'wallnut scope'), (KULFA, 'kulfa scope'), (TUTYFRUITY, 'tutyfruity scope'), ) flavor = models.CharField(max_length=20, choices=choices, null=True) def __str__(self): return self.flavor now if i display the form for it, how could it be possible for user to select 1 item(or scopes) many times, and also the method i've created in IceCream model doesnt work and gives the error IceCream has no attribute flavor_set. the … -
Axios call inside an axios response
I'm having issue when I try to do an axios call whithin the scope of the response const url = 'http://localhost:8000/session/'; axios.get(url).then(response => { console.log(response) const sessionEnCours = response.data.results.filter(session => session.fin_session == null).map(session => { axios.get(session.client).then(client => { session.client = `${client.prenom} ${client.nom}` }) return session }) sessionEnCours.map(session => console.log(session)) setSession(sessionEnCours) }) }, []); I have a Django API, so I have hyperlink models and get url as a foreign key. Whenever I'm trying to replace this url with the customer name with my little trick, it is not modified. Thank you for your help -
How to implement a better use of Django ORM?
I need to get a queryset where there are certain 2 users. My model: class ChatRoom(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="room_user1") user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="room_user2") My qs: def by_users(self, user1, user2): return self.get_queryset().filter( (Q(user1=user1) | Q(user2=user1)) & (Q(user1=user2) | Q(user2=user2) ) Right now the query looks like this, is there any way to optimize it, make it optimal? -
Flask + sqlalchemy get class object from database
I'm builing Flask application using SqlAlchemy and i'd like to retrive hashed_password using db_session.query. here's my user model: import sqlalchemy from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from .db_session import SqlAlchemyBase class User(SqlAlchemyBase, UserMixin): __tablename__ = 'users' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True) name = sqlalchemy.Column(sqlalchemy.String, nullable=True) surname = sqlalchemy.Column(sqlalchemy.String, nullable=True) age = sqlalchemy.Column(sqlalchemy.Integer, nullable=True) position = sqlalchemy.Column(sqlalchemy.String, nullable=True) speciality = sqlalchemy.Column(sqlalchemy.String, nullable=True) address = sqlalchemy.Column(sqlalchemy.String, nullable=True) email = sqlalchemy.Column(sqlalchemy.String, index=True, nullable=True) def set_password(self, password): self.hashed_password = generate_password_hash(password) def check_password(self, password): self.hashed_password = None return check_password_hash(self.hashed_password, password) you can see that here is no password coloumn but I add user.hashed_password in set_password func here is register app.route: @app.route('/register', methods=['GET', 'POST']) def reqister(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return flask.render_template('register.html', title='Регистрация', form=form, message="Пароли не совпадают") db_sess = db_session.create_session() if db_sess.query(User).filter(User.email == form.email.data).first(): return flask.render_template('register.html', title='Регистрация', form=form, message="Такой пользователь уже есть") user = User( name=form.name.data, email=form.email.data, surname=form.surname.data, age=form.age.data, position=form.position.data, speciality=form.speciality.data, address=form.address.data ) user.set_password(form.password.data) db_sess.add(user) db_sess.commit() return flask.redirect('/login') return flask.render_template('register.html', title='Регистрация', form=form) I call user.set_password at the bottom of the func and try to check password here: @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): db_sess = db_session.create_session() user = db_sess.query(User).filter(User.email == form.email.data).first() if user and … -
Using Javascript validation checks in a Django Project
I have to make a registration page in a project that uses Django as the backend framework.. In the registration page, I have to input the names, email, password and mobile... During registration, I need to validate email if its a valid format, check if the mobile number is of 10 digits and check if the password is a strong one.. I want to do it using javascript... I have written the code for the form and also the javascript function... But while running on the server I am unable to get the desired validation checks and alerts... Please help what should i do? signup.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> {% load static %} <link rel="stylesheet" href="{% static 'signup1.css'%}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Register</title> <!--Javascript form validator--> <link rel="stylesheet" href="{% static './register.js' %}"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="card"> <div class="text-center"> <h1>Signup</h1> <h6>Register yourself</h6> </div> <form style="text-align: top;" name="myForm" method="POST" action="" onsubmit="validate()" > {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label"><b>First Name</b></label> <input type="text" name="first_name"placeholder="First Name" class="form-control" id="name" required aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label"><b>Last Name</b></label> <input type="text" name="last_name"placeholder="Last Name" class="form-control" id="name" required aria-describedby="emailHelp"> </div> … -
Formset with request.post not initializing correctly
I am having an issue using formsets and request.POST. Whenever I initialize the formset without request.POST it works as intended, but will not send the data through as the form is never valid. If I include request.POST (as I have done on all my other forms in the view) the formset doesn't seem to initialize correctly. No data gets through, I can't see any form fields, and I get a html warning saying: (Hidden field TOTAL_FORMS) This field is required. (Hidden field INITIAL_FORMS) This field is required. Here is a very simplified version of what I am doing in my project. This is bare minimum and the project itself is much more involved. But this should be the heart of the problem I am having. The intent of this very basic form is that my formset would have 3 forms, each one initialized with a letter, 'a', then 'b', then 'c'. views.py def MyView(request): my_formset = formset_factory(my_form) my_list = ['a', 'b', 'c'] if request.method == 'POST': my_formset = formset(request.POST, initial=[{'field1':x} for x in my_list]) #If I remove 'request.POST' then the form initializes correctly, but will never pass .is_valid() if my_formset.is_valid(): print('valid') else: print('invalid') else: my_formset = formset(initial=[{'field1':x} for x in … -
python manage.py runserver in cmd
(hafi) C:\Users\User\Desktop\hafi>python manage.py runserver C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\Users\User\Desktop\hafi\manage.py': [Errno 2] No such file or directory -
Does python web frameworks like Flask/Django have a build process?
I have recently started learning CI/CD concepts. In the tutorials, they used a react website to show the build stage. I was wondering do we have a build phase for applications developed using frameworks like Django/flask? For these applications, we generally run a single command to start the application directly from source code like: python manage.py runserver python app.py Also, in general, is to possible (and okay?) for a web application not to have a build phase? Any knowledge here would be helpful. Thanks in advance! -
Django test fails to run migrations
I'm trying to run a test script, following this django doc (which is the version being used here). It quickly fails with a long stack. I've selected what's the possible culprit. File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 185, in migrate add_sistema_entidade_e_orgao_composicao(apps, sistema) File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 16, in add_sistema_entidade_e_orgao_composicao user = get_user(apps) File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 7, in get_user return User.objects.filter( File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/query.py", line 318, in __getitem__ return qs._result_cache[0] IndexError: list index out of range As a workaround, I modified django's query.py if qs._result_cache: return qs._result_cache[0] else: return "" Which worked, until the next error: File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/home/user11/app-master/app/core/migrations/0016_auto_20201120_0934.py", line 106, in migrate sistema = Sistema.objects.get(nom_alias=sistema) File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/query.py", line 439, in get raise self.model.DoesNotExist( __fake__.DoesNotExist: Sistema matching query does not exist. Now I'm stuck. The test_database gets created with all the tables up to these migrations' errors, with the vast majority lacking any data. Among those that are empty is the table that this last error seems to refer to. Note that I'm not the developer, I had no hand in creating the DB being used nor any of the migrations. … -
In Django, how do I add a join table relation to an existing model?
I'm using Python 3.9 and Django 3.2. I have these models. The second is a join table for the first class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') class CoopAddressTags(models.Model): # Retain referencing coop & address, but set "is_public" relation to NULL coop = models.ForeignKey(Coop, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) is_public = models.BooleanField(default=True, null=False) I would like to actually reference the join table in my first model, so I added address_tags = models.ManyToManyField('CoopAddressTags') like so class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) address_tags = models.ManyToManyField('CoopAddressTags') addresses = models.ManyToManyField(Address, through='CoopAddressTags') but I'm getting this error when I run a script to generate migraitons $ python manage.py makemigrations directory SystemCheckError: System check identified some issues: ERRORS: directory.Coop.address_tags: (fields.E303) Reverse query name for 'directory.Coop.address_tags' clashes with field name 'directory.CoopAddressTags.coop'. HINT: Rename field 'directory.CoopAddressTags.coop', or add/change a related_name argument to the definition for field 'directory.Coop.address_tags'. I'm not clear what this means or how to resolve it. The goal is that when I have a "Coop" object, I can reference its addresses and whether or not those addresses are public. -
DRF request after authentication lost data
Hi i have problem about authentication in drf. Generally when I set default permission class to IsAuthenticated,request is getting authenticated but my data from post request get lost. I changed SessionAuthentication to delete function enforce_csrf #custom_auth from rest_framework.authentication import SessionAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return #settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'config.custom_auth.CsrfExemptSessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } #views.py @api_view(["GET", "POST"]) def give_user_teams(request): print(request.user) print(request.auth) print(request.data) current_user = User.objects.get(pk=int(request.data['user_id'])) selected_teams = current_user.teams.all() serializer = TeamSerializer(selected_teams, many=True) return Response(data=serializer.data) If i set default permission to AllowAny, after request in postman these 3 prints from the view, look like this: #with allow any: AnonymousUser None {'headers': {'Authorization': 'Token 4a1e2a6a0ee4e004f3f867910dacbc35c85bd494'}, 'user_id': 25} #with is authenticated: testuser 4a1e2a6a0ee4e004f3f867910dacbc35c85bd494 {} Is there something I'm missing? -
Get files from Aw3 and append them in a .zip in Django
I would like to download some files from Aw3 in a .zip, with all these files. I am using django==2.2.1 with boto3 library, last version. I am trying to get the files one by one, convert them with json.dump and insert them in a .zip file with generate_zip function. Not resolve nothing, I mean, it not resolve any error and it not response the .zip or something in console that I would see. Probably the .zip was not created, but I do not know because, like I told before, it not response nothing. My code is: for id_file in files: BUCKET_NAME="xxxx" BUCKET_FILE_NAME='folder/'+id_file+'/'+category+"/"+name_file s3 = boto3.client('s3',aws_access_key_id=settings.AWS_ACCESS_KEY_ID,aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,region_name='eu-west-2') s3_response_object=s3.get_object(Bucket=BUCKET_NAME,Key=BUCKET_FILE_NAME) s3_response_object['Body'] = s3_response_object['Body'].read().decode("ISO-8859-1") s3_response_object['Key'] = settings.AWS_ACCESS_KEY_ID+'/'+settings.AWS_SECRET_ACCESS_KEY location = s3.get_bucket_location(Bucket=BUCKET_NAME)['LocationConstraint'] url = "https://s3-%s.amazonaws.com/%s/%s" % (location, BUCKET_NAME, BUCKET_FILE_NAME) s3_response_object['URL'] = url file_data = json.dumps(s3_response_object, default = myconverter) resultFiles.append(file_data) full_zip_in_memory = generate_zip(resultFiles) response = HttpResponse(full_zip_in_memory, content_type='application/x-zip') response['Content-Disposition'] = 'attachment; filename="files.zip"' return response La función generate_zip def generate_zip(files): mem_zip = BytesIO() with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf: for f in files: zf.writestr(f[0], f[1]) return mem_zip.getvalue() -
Cannot add extra styles to django-ckeditor
django-ekeditor packages comes with highlight.js library for code snippets and that library comes with some pre-installed styles. As I prefer seti-ui style, I download it from highlightjs.org. Inside the downloaded package is seti-ui.min.css file and I copy it to \venv\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins\codesnippet\lib\highlight\styles where all other styles are and then set this in my settings.py: 'codeSnippet_theme': 'seti-ui' # based on the name of css file And it doesn't work. The editor shows the code snippet but without any style. I've tried several other pre-installed themes like monokai and foundation and they work fine. Then I noticed that seti-ui.min.css is inside a subfolder base16 in the package I downloaded from highlightjs.org, so I tried \venv\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins\codesnippet\lib\highlight\styles\base16 too but didn't work either. So what is the correct method to add it? -
Django/Python - update html after update with radiobutton
I have a Django app with an email box. Users can send the email by hand or let it be done automatically. To change the setting: either manual or automatic, I have creates a view to change the settings. To show the user what the current setting is, I prechecked the radio button. It looks like this: My problem is, that when the button "Update" is clicked, it does change the settings, but not the frontend for the user. So the user does not see that it is changed. So the page should be refreshed or something with the new settings, but I don't know how.. This is the code that I have now: .html <div class="form-group"> <label class="form-label">Send Emails:</label> <p></p> <input type="radio" name="update_type" value="manual" {% if view.manualSetting %}checked {%endif%}> Manual {% if view.manualSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <input type="radio" name="update_type" value="auto" {% if view.autoSetting %}checked {%endif%}> Automated {% if view.autoSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <button type="submit" class="btn btn-primary">Update</button> </div> views.py class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(id=1) autoSetting = int(model.auto == … -
Separate array to small array by count [duplicate]
I have array like this [1,4,2,3,4,14,2,5,1,2,3,14,1,3] Now I want to separate this to small 3 arrays( last might be 1 or 2 array) [[1,4,2],[3,4,14],[2,5,1],[2,3,14],[1,3]] I think I can do this such as ,but obviously it's not clear and clean. Is there any more easy way to do this? total = [] item = [] for cnt,a in enumerate(original_arr): item.append(a) if len(item) == 3: total.append(item) item = [] total.append(item) -
Bad Request error when trying to refresh Django login access token
Trying to refresh the access token I receive from Django every few seconds, however I am getting the error message Request Method: POST Status Code: 400 Bad Request I am sending my refresh token to this endpoint: "http://127.0.0.1:8000/api/token/refresh/" This is my urls.py: from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), ] This is how I am sending my refresh token: let updateToken = async ()=> { try { let response = await axios.post('http://127.0.0.1:8000/api/token/refresh/',JSON.stringify(authTokens.refresh)) //update state with token setAuthTokens(authTokens => ({ ...response.data })) //update user state const decoded = jwt_decode(response.data.access) setUser(user => ({ ...decoded })) //store tokens in localStorage //we stringify because we can only store strings in localStorage localStorage.setItem('authTokens',JSON.stringify(response.data)) } catch(err) { //if fail, something is wrong with refresh token console.log(err.response) } } This is the error I am getting: config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: refresh: ['This field is required.'] [[Prototype]]: Object headers: content-length: "39" content-type: "application/json" [[Prototype]]: Object request: XMLHttpRequest onabort: ƒ handleAbort() onerror: ƒ handleError() onload: null onloadend: ƒ onloadend() onloadstart: null … -
( django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.accounts'. Check that 'mysite.apps.accounts.apps.AccountsConfig.name' is correct
This is how it is structured The code inside apps.py of accounts folder file is from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = "apps.accounts" The code inside Settings is INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite.apps.accounts', ] I tried changing 'mysite.apps.accounts', to 'mysite.apps.AccountsConfig', and changing name = "apps.accounts" to name = "accounts" I am new to Django and was following How to make a website with Python and Django - MODELS AND MIGRATIONS (E04) tutorial. Around 16:17 is where my error comes up when I enter python manage.py makemigrate to the vscode terminal The error is ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.accounts'. Check that 'mysite.apps.accounts.apps.AccountsConfig.name' is correct. Someone please help me.