Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django update using logged in username as pk
So I made table and post method menus with logged user information. I want to update information using username. If there's no username exit on table as logged in user, it posts data but if username already exits, I want it to overwrite data. So far, it doesn't overwrite but just post. What can I do to fix this? model.py class OrderItem(models.Model): username = models.CharField('Username', max_length=20, null=True, blank=True) first_name = models.CharField('First Name', max_length=30, null=True, blank=True) last_name = models.CharField('Last Name', max_length=30, null=True, blank=True) vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True) note = models.CharField('note', max_length=255, null=True, blank=True) view.py def UpdateOrderView(request, pk): username = user.is_authenticated order = OrderItem.objects.get(username=username) form1 = OrderForm() context = {'form1': form1 } if request.method == 'POST': form1 = OrderForm(request.POST, instance=order) print(request.POST) if form1.is_valid(): form1.save() return redirect('order-update', pk=pk) return render(request, '/order_info.html', context) urls.py urlpatterns = [ path("order_info", views.OrderView, name="order-page"), path("<int:pk>", views.UpdateOrderView, name="order-update"), ] -
Deploy Django app on Apache server on CentOS 7
I am following this article to deploy a Django app on Apache in CentOS 7. I have some differences compared to that article: 1 - I used port 443 for https (my machine already has port 443 open with my_app_dns) 2 - My virtual host config file /etc/httpd/conf.d/django.conf is as following: <VirtualHost *:80> ServerAdmin xxx@xxx.com ServerName my_app_dns DocumentRoot /home/centos/path_to_my_app Alias /static /home/centos/path_to_my_app/static <Directory /home/centos/path_to_my_app/static> Require all granted </Directory> #ErrorLog /logs/apis_error.log #CustomLog /logs/apis_access.log combined WSGIPassAuthorization On WSGIDaemonProcess my_app python-path=/home/centos/path_to_my_app:/home/centos/.local/share/virtualenvs/my_app-8BiokhAz/lib/python3.9/site-packages WSGIProcessGroup my_app WSGIScriptAlias / /home/centos/path_to_my_app/wsgi.py <Directory /home/centos/path_to_my_app> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> 3 - My app uses Postgres database instead of SQlite3. The DocumentRoot is set to /var/www in /etc/httpd/conf/httpd.conf. I have also set up self-signed SSL certificate with the file etc/httpd/conf.d/ssl.conf). Below is some of the content of the ssl.conf file: Listen 443 https ... <VirtualHost _default_:443> DocumentRoot "/var/www" ServerName my_app_dns:443 ... SSLEngine on SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt ... </VirtualHost> With the above setup, when I go to https://my_app_dns", I see the sample Apache Test page. If I change <VirtualHost *:80> to <VirtualHost *:443> in the file /etc/httpd/conf.d/django.conf, going to https://my_app_dns yields this error: my_app_dns sends an invalid response ERR_SSL_PROTOCOL_ERROR What am I missing in this setup sequence in order … -
Forward Telegram Channel Messages to Twitter via Bot (with delay)
Hope you are having a good time. I am looking to develop a basic telegram bot that will redirect all the messages from a private telegram channel to a twitter account with a delay of 3 hours, that is, if a message is posted in a telegram channel at 09:00 AM it should be forwarded to twitter at 12:00 AM. Can it be possible, if yes, how? -
AWS SES sending emails with disabled links
I configured the SES service with SMTP in a Django project. It sends emails, but sometimes (Not always), the emails arrives with all the links disabled. I verified the domain and the DKIM -
Django 3 by example bookmarklet_launcher.js
Following is a piece of code in the Django 3 by example book we can use it to in bookmark in a browser and upon clicking the bookmark, the code in it will be executed. Can anyone please help me understand this code? (function(){ if (window.myBookmarklet !== undefined){ myBookmarklet(); } else { document.body.appendChild(document.createElement('script')).src='https://127.0.0.1:8000/static/js/bookmarklet.js?r='+Math.floor(Math.random()*99999999999999999999); } })(); Why we need to put function inside parenthesis? (function.....)() How browser executes the code. We put javascript tag in start of code. JavaScript:(function.....)() what is this function myBookmarklet() and when if statement will be actually executed? How will window object will have myBookmarklet property? Any relevant resources will be appreaciated. Thanks a lot -
ValueError at /accounts/register. The User could not be created because the data didn't validate. (django model form)
I don't understand why this error would occur. So, here's my very simple user model: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): pass My Model Form: class RegistrationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Cofirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email') def clean_password(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: return False return True def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user And my view where i am calling the form.save() method: class Register(View): template = 'application/register.html' success_url = 'application:index' def get(self, request): ctx = { 'form': RegistrationForm(), } return render(request, self.template, ctx) def post(self, request): form = RegistrationForm(request.POST) instance = form.save(commit=False) if not form.is_valid(): ctx = { 'form': RegistrationForm(), } return render(request, self.template, ctx) instance.save() login(request, instance) return redirect(self.success_url) Can someone please help me understand what i have done wrong here?? Thank you -
Django-3.2 empty path anchoring in template
I have two urls.py file. The first one on root I have included the second. #urls.py (project urls file) path('', include('home.urls')), #urls.py (home app urls file) path('', views.Home.as_view(), name='index'), In my browser address bar '127.0.0.1:8000' works just fine. I am getting stuck when I want to anchor the url in template. <a href="{% url 'index' %}"></a> -
How to render errors provided from django API for each field individually in React JS
I have a register form and I want to display for each field the validation error that comes from api like in the next photo. I know how to create this on front end but I don't know how to find for each field from my form is the error message in api. I want to know how I cand show that red message coresponding to each field, based on the answer from api. {email} <label className="label-register">First Name</label> <input value={firstName} onChange={updateFirstName} id="first-name" required="true" className="form-input" type="text" /> <label className="label-register">Create a password</label> <input value={password} onChange={updatePassword} className="form-input" required="true" type="password"/> <label className="label-register">Repeat your password</label> <input value={password2} onChange={updatePassword2} className="form-input" required="true" type="password" /> <div className="term-and-cond"> <p><input type="checkbox" required="true"/>I have read and agree to the Terms and Conditions, the Privacy Policy.</p> </div> <button type="submit" className="check-email-btn register-btn">Create account!</button> </form> The response from the API is next: { "email": [ "E-mail already exist" ], "password": [ "Password must contain one number." ], "password2": [ "Password didn't match" ] } -
Use Custom Renderer Response In Django Test Client
I use a custom renderer to render responses from my views, and they work well when I send requests using Postman. When I try to write tests, the responses I get from the Test Client is different. Printing both responses gives these results: Postman Response: b'{"success":true,"message":"User retrieved successfully.","data":{"id":5,"email":"user0@email.com","username":"user0"}}' Test Client Response: {'id': 5, 'email': 'user0@email.com', 'username': 'user0'} How do I make the Test Client response the same as the response I get from Postman? -
Python: Reverse every 2 items on a list
I am working on a Django platform where i am supposed to submit a list of polygon coordinates from google maps to search through a dataset. So far, i have managed to collect the coordinates from the frontend but they are mixed up i.e the longitudes start then latitude follows and ideally ,the longitudes are supposed to start then the latitudes to follow Here is a working sample of the list i have: coordinates = [65.56147597726766, -104.83033675930798, 64.44751706485646, -93.93189925930798, 58.232434372977615, -98.85377425930798] The desired format should be: coordinates = [-104.83033675930798,65.56147597726766, -93.93189925930798,64.44751706485646, -98.85377425930798,58.232434372977615] Any help will be highly appreciated. -
Django unittest self.assertTemplateUsed, how to check the occurrence of multiple templates
self.assertTemplateUsed(response,('goods/item_list.html', 'base.html', 'inc/_nav.html') ,) error AssertionError: False is not true : Template '('goods/item_list.html', 'base.html', 'inc/_nav.html')' was not a template used to render the response. Actual template(s) used: goods/items_list.html, base.html, inc/_nav.html how to check for multiple templates in response -
Django: How to open a small window on button click without changing url
I am using Django and I want to open a small forms window when I click on button 'Nouvelle Chirurgie' in template without changing the url and I don't know if I have to do it with js or no and how to do it, and after that how to save it in views. Actually, I'm this button take me to another page: <a href="{% url 'register_visit' patients.id %}" class="btn btn-primary">Nouvelle Chirurgie</a> So, what should I do? -
Django v3 path variable in url issue
I've been scratching my head on this one a lot. I feel like the answer is right in front of me but I can't see it. I'm using django 3 and I have an url that is returning an error. My Urls is... url(r'^(?P<path>.*)$', views.GraphanaProxyView.as_view(), name='grafanadash'), My View is... class GraphanaProxyView(ProxyView): upstream = '{{ip.port}}' def get_proxy_request_headers(self, request): headers = super(GraphanaProxyView, self).get_proxy_request_headers(request) headers['X-WEBAUTH-USER'] = request.user.username return headers I am calling the url from an iframe.... <iframe src ="{% url 'grafanadash' %}" width="100%" height="1200px" frameborder="0"></iframe> But I get the following error... NoReverseMatch at /testsite/mt/mtgrafana/ Reverse for 'grafanadash' with no arguments not found. 1 pattern(s) tried: ['testsite\\/mt\\/(?P<path>.*)$'] I know that technically the "path" part doesn't point to anything, but the view is expecting a "path" variable for it to use. If I just type the address into the bar "/testsite/mt/grafanadash" it routes through the view and works. If I attempt to have it render inside a frame, or just call it through a link is when I get the error. Any help would be appreciated. -
How to make custom form readonly when accessed by user with no change perms on Django Admin
I have an issue. I have custom forms for most of my models - as I do most of my validation and data manipulation through Forms instead of Views so that the experience or behaviour when a user does their operation through my site or Django's Admin panel are the same. For models registered to the Admin site without custom forms (register model only) - they behave flawlessly according to user perms. If they have change_modelname perms, they can click the link on an object and be taken to a DetailView form where they can make changes. If they only have view_modelname perms, they'll be taken to the DetailView that are now all readonly. For models registered to the Admin site with my custom forms though - for users that only has View permissions (no Change permissions), are met with a KeyError when clicking on an object, instead of being able to see the DetailView in readonly mode. I've looked around on how to solve this, including trying to find out from the source code on how Django does this with the forms they generate from our models by default, but can't seem to find anything useful to me. What … -
Automatically link form and user using OneToOneField
I have create a model form using also OneToOneField field to link it to my user, my problem is that I have to go to the admin section to manually select the user to make it works. Is it possible to have the user linked to the form submitted automatically? Also this may be stupid but when I use user.userinformation.gender to get the info about gender I get back "m", is there a way to access the label "Male" instead? TThank for yours help! My code: models.py class UserInformation(models.Model): gender_choice = [('m', 'Male'),('f', 'Female')] user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) gender = models.CharField(max_length=120, choices=gender_choice) phone = models.CharField(max_length=10) email = models.EmailField() forms.py class UserInformationForm(forms.ModelForm): class Meta: model = UserInformation fields = ('first_name', 'last_name', 'gender', 'phone', 'email',) views.py def add_information(request): if request.method == "POST": form = UserInformationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Form submitted') else: form = UserInformationForm() return render(request, 'accounts/profile/add_information.html', {'form': form}) def show_profile(request): profile_info = UserInformation.objects.all() return render(request, 'accounts/profile/user_profile.html', {'profile_info': profile_info}) -
Handle multiple booleans in postgres?
I have a table which has more than 12 columns which just have boolean items ! How to manage this with a single column or having multiples are the effective ? And as part of requirement, this needs to be dynamic ( in the sense, the column may increase in future ) so it should act without altering the table ! Whats the best way to achive this ? Table users: education: False profession: False location: True certificates: False exams: True Like the above i have more than 12 columns, and in near future this may increase - so is there any way to handle this - for example using Json or array or bitwse etc -
Style Ckeditor image upload
I have ckeditor 4 with image upload on my website. Everything works great the only issue is that it visually looks very bad. Is it possible to style or change the UI for the image upload as I expect users will have a hard time understanding it. I just want a simple upload button nothing fancy -
Make data to display in graph in python
I'm writing an API endpoint in Django Rest framework and want to make data for showing graph I have data like this which I get from the database. data = [ { "name": "Test 3", "status": "Active", "count": 1 }, { "name": "Test 2", "status": "Failed", "count": 1 }, { "name": "Test", "status": "In Progress", "count": 85 }, { "name": "Test", "status": "Failed", "count": 40 }, { "name": "Test", "status": "Active", "count": 1 }, { "name": "Test", "status": "Success", "count": 218 }, { "name": "Test 2", "status": "Active", "count": 1 } ] and I want to make final graph data from above like this in order to show it in the graph. [ "labels": ['Test', 'Test 2', 'Test 3'], "data": [ { name: 'Active', data: [1, 1, 1] }, { name: 'Failed', data: [40, 1, 0] }, { name: 'Success', data: [218, 0, 0] }, { name: 'In Progress', data: [85, 0, 0] } ] ] I'm trying to make data in that way but I'm unable to make the correct format of data can anyone please help is there any built-in functions that I can use to make the data correct. response = [ { 'labels': [], 'data':[], } … -
nlp model and django tokenizer not linked
After creating the NLP model in colab, I downloaded it as an h5 file. I pasted the file to django. Only h5 files. But after passing through tokenizer.text_to_sequences, all values become null. What's the problem? The code implemented in django is def result(request): full = request.GET['fulltext'] full = okt.morphs(full, stem=True) full = [word for word in full if not word in stopwords] encoded = tokenizer.texts_to_sequences([full]) # error !!!! pad_new = pad_sequences(encoded, maxlen=80) score = float(model.predict(pad_new)) return render(request, 'testapp/result.html', {'score': score}) Encoded = tokenizer.texts_to_sequences ([full]) - It works well except for this part. Tokenizer. I think the data is empty here. The code is https://wikidocs.net/44249. This site. Do you happen to know the solution? -
I am trying to install react-native but keep getting errors
I want to start developing native apps with react-native and i am also using VScode as my code editor, i keep running in to error when trying to start my project using this command "expo init First project", so how do you think i can overcome this error -
how to add missing CORS header ‘Access-Control-Allow-Origin’?
I want to get a base64 encoded image from another domain. I have enabled CORS on the backend but I am getting an error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://codedecoder.pythonanywhere.com/media/embed/2021/10/07/temp.jpg. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <img id="datadiv"></img> var src = 'https://codedecoder.pythonanywhere.com/media/embed/2021/10/07/temp.jpg' $.ajax({ type: "GET", url: `https://codedecoder.pythonanywhere.com${src}`, crossDomain: true, success: function(dayta) { console.log(dayta); $('#datadiv')[0].src = dayta; }, }) -
Is it possible to recreate a table field that was accidentally removed from Django Model, without tearing down all migrations?
Suppose the following model: class Country(models.Model): name = models.TextField(null=True, blank=True) continent = models.TextField(null=True, blank=True) population = models.PositiveIntegerField(null=True, blank=True) And then I: Delete the field population from models.py. Create a migration: python manage.py makemigrations countries_app Execute the migration, which marks the field as removed: python3 manage.py migrate countries_app Here's the migration file 0006, which is a sequence for the last migration created (0005): class Migration(migrations.Migration): dependencies = [ ('countries_app', '0005_auto_20210723_0007'), ] operations = [ migrations.RemoveField( model_name='country', name='population', ), ] Now, I don't have the field population on my database, but I realized that it was a mistake, to remove population field from Country model. Trying to get things back to normal, I define the field once again on the model and I unapply the migration 0006, and also removed 0006 migration file, where it was defined the deletion of the field, and I also execute python manage.py migrate countries_app and it says nothing to migrate, which makes sense. $ python3 manage.py migrate countries_app Operations to perform: Apply all migrations: countries_app Running migrations: Applying countries_app.0006_remove_country_population... OK $ rm countries_app/migrations/0006_remove_country_population.py $ python manage.py migrate countries_app But when I check the database table, the field population is still not there. But I thought Django … -
Updating Django's JSONField
Let's say I have a model: class Foo(Model): bar = JSONField(...) I can easily filter by the elements of bar. For example, Foo.objects.filter(bar__has_key="some_key").count() will give me the number of Foo objects that have "some_key" as a key in their bar field. My question is about updates. I tried: Foo.objects.exclude(bar__has_key="some_key").update(bar__some_key={"x": "y"}) to set the value to some default where it isn't set, but that gives me django.core.exceptions.FieldDoesNotExist: Foo has no field named 'bar__some_key'. I can, of course, do objs = list(Foo.objects.exclude(bar__has_key="some_key")) for obj in objs: obj.bar["some_key"] = {"x": "y"} Foo.objects.bulk_update(objs, ["bar"]) but I'm interested if this can be done without looping (and generating potentially large Foo objects in memory), using only QuerySet.update. Additionally, I'd be curious how to remove "some_key" from all objects that have it. So, this: objs = list(Foo.objects.filter(bar__has_key="some_key")) for obj in objs: del obj.bar["some_key"] Foo.objects.bulk_update(objs, ["bar"]) but again using only QuerySet.update. -
One Django App/Model to Multiple databases
I'm on a Django project & for performance and RoadMaping reasons I will need to use a Multi-BDD system. However I am a little stuck let me explain myself, I created the databases, I added a Routing URL'S to specify which database to use and when to use it. I have a single 'Application in this project' and also a single & unique 'Database model', this last (model) logically must be duplicated in all my databases during my migration. THE QUESTION: Why when I migrate this model it is only migrated in a single database and not in the other while the migration table is duplicated, I cannot understand the why and how 🙂 I will appreciate your feedback. Thank you in advance ! Here is my settings.py # Including le DB_Router DATABASE_ROUTERS = ['routers.db_routers.AuthRouter', 'routers.db_routers.VIGRouter', 'routers.db_routers.VISRouter', 'routers.db_routers.DURRouter', 'routers.db_routers.IPCRouter', ] DATABASES = { 'default': {}, 'izlog': { 'ENGINE': ENGINE, 'NAME': 'izlog', 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': PORT, }, 'db_vig': { 'ENGINE': ENGINE, 'NAME': DBSNAME['db_VIG'], 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': PORT, }, 'db_vis': { 'ENGINE': ENGINE, 'NAME': DBSNAME['db_VIS'], 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': PORT, }, Here is my db_routers.py class VIGRouter: route_app_labels = {'izLogApp'} def … -
Issue with parsing date in legacy database | Django inspectdb
I have an application running in MySQL. I want to create an API, so i tried with Django Rest Framework. Created the django models by using, manage.py inspectdb > models.py Everything works fine. But I have a datefield in the existing database with value: 0000-00-00 00:00:00. While accessing this data, I got the below error, 'str' object has no attribute 'tzinfo' Is there any way to ignore this error? I tried passing null=True, blank=True in models.py. But no use.