Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How do you control which language get stored in your models?
I am making a GraphQLAPI for a local business in my area using django_graphene. We will only be dealing with our local language and there will be no english used except for maybe email and password. When I get data from user I want to check if the language that the user typed in is in my preferred language and then store it in the database. How do I control the language being stored in the database? -
Python import all from folder
I have encountered issue while working on my Django project. I have multiple classes inside views.py. It had 1200 lines so I decided to move these views to seperated files inside new folder. Now one files, for example Customer.py has 2 classes for different operations. This is my project structure before splitting views.py: MyProject core - urls.py api - views.py manage.py Project structure after splitting views.py MyProject core - urls.py api - view - *all the files with multiple classes in each file* manage.py After splitting views.py I needed to import all classes from all files inside of the view folder inside core/urls.py. I have been trying to find out few hours now and can figure it out... My current solution is that in urls.py im doing from api.view import * while having init.py inside view folder which is doing from .oneOfManyClasses import * for all classes... I highly dont like this solution, I would love to find out some good looking simple elegant solution. Is here anyone who can help me ? Big thanks -
Django change frontend validation of number input widget
For number fields in the Django admin interface, it's only possible to input numbers and separators. How can I implement a similar frontend validation for my own custom widget? For example, I want to extend a TextInput widget so that the user can only input [A-Za-z]. The included pattern attribute only validates in the backend. -
Python - Compare two JSON with different length and without order
I want to compare two json data without order because there are same items with different orders. For example first json: [{'Id': 113, 'Label': 'Z', 'Input': 'Z', 'Updated': False}, {'Id': 124, 'Label': ' X', 'Input': ' X', 'Updated': False}, {'Id': 128, 'Label': ' C', 'Input': ' C', 'Updated': False}, {'Id': 117, 'Label': ' R', 'Input': ' R', 'Updated': False}, {'Id': 118, 'Label': ' T', 'Input': ' T', 'Updated': False}] Second Json [{'Id': 128, 'Label': ' C1', 'Input': ' C1', 'Updated': False}, {'Id': 118, 'Label': ' T1', 'Input': ' T1', 'Updated': False} {'Id': 113, 'Label': 'Z2', 'Input': 'Z2', 'Updated': False},] I want to make update different data but same ID json from the second json and delete from the first Json what second json doesnt have. So my loop is below: for form in selectedUserForm: for jsonItem in getJson: if form.id == jsonItem['Id'] and form.isUpdated == False: form.metaKey = jsonItem['Label'] form.metaVal = jsonItem['Input'] form.isUpdated = True form.save() elif jsonItem['Id'] == 0: newMeta = UserMeta(user = selectedUser, metaVal = jsonItem['Input'].title(), metaKey = jsonItem['Label'].title(), isUpdated = True) newMeta.full_clean() newMeta.save() elif form.isUpdated == False: form.isDeleted = True form.isUpdated = True form.save() However, this algorithm only make with order but my list is posted from … -
NoReverseMatch at /sessions/exercise/6/update/
I'm going crazy here. According to the Django debugger there's no reverse match for the pattern I'm requesting, but it's identical to my URL path in urls.py, and I am passing the object id as the required argument. NoReverseMatch at /sessions/exercise/4/update/ Reverse for 'exercise_update' with no arguments not found. 1 pattern(s) tried: ['sessions/exercise/(?P[0-9]+)/update/$'] Error during template rendering This is my html <button><a href="{% url 'sessions:exercise_update' exercise.id %}">Update exercise</a></button> This is my URL path path('exercise/<int:pk>/update/', MyExerciseUpdate.as_view(), name='exercise_update'), The view is just a generic update view. class MyExerciseUpdate(LoginRequiredMixin, UpdateView): model = Exercise fields = ['my_fields'] I've tried displaying the exercise.id just to see if it exists, and it does. How come there is no argument? Also, I use this path for a detail view in another page and it works just fine <a href="{% url 'sessions:exercise_detail' exercise.id %}">{{ exercise.name }}</a> Help, please. -
Django how to check if user is in path
I made an unique url and I want to check if the acutal url contains the uid so I made a if statement which is always false in my case so what can I change that it works and checks if the path contains the uid. views.py @login_required(login_url='home:login') def ChangeEmailView(request, token): packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid if request.path == str(token): if request.method == 'POST': objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) if form.is_valid(): form.save() return redirect('home:profilesettings') else: objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid else: print('site wasnt found') objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid return redirect('home:index') context = {'form': form, 'token': token} return render(request, 'home/email_settings.html', context) -
AssertionError at /api/ Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information
I am creating an API and have some problems: title = models.CharField(max_length=250,default='') description= models.CharField(max_length=1000) start_date = models.DateField(blank=True,null=True) end_date = models.DateField(blank=True,null=True) reg_start_date = models.DateField(blank=True,null=True) reg_end_date = models.DateField(blank=True,null=True) input_date = models.DateTimeField(default=timezone.now) author = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='yoga_tours') slug = models.SlugField(max_length=250, unique_for_date='input_date') status = models.IntegerField(choices=statuses,default=1) objects = models.Manager() # default manager tourobjects = TourObjects() # custom manager serializers.py class YogatourSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'title', 'description', 'start_date', 'end_date', 'reg_start_date','reg_end_date','author','status') model = Yogatour I want to have date field only, without time properties .when I post something, I am getting next error: AssertionError at /api/ Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly. how to solve this problem? -
Use different decimal separators for frontend validation in Django Admin interface
I looked through every single similar question on stackoverflow and tried nearly everything. It seems easy to do: I just want to allow , as decimal separator for a FloatField in the Django admin interface. At the moment, it depends on the localization, but I always want to allow it. It would even be ok for me, if it's just a TextInput, but I need , to work. Setting DECIMAL_SEPARATOR in settings.py does not work. My question is similar to this 6 year old, unanswered one: How to only override DECIMAL_SEPARATOR in django while keeping localization intact? I managed to use the TextInput widget for FloatFields like this: class ExampleAdminForm(forms.ModelForm): class Meta: model = Example def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key, value in self.fields.items(): if isinstance(value, FloatField): self.fields[key].widget = TextInput() The widget works, but an input like 1,23 leads to an error message Enter a number. I can't find out where the validation happens, as validate() of FloatField never gets triggered. Is there a way to, for example, override FloatField or the TextInput widget to allow for other decimal separators? Or any other way? -
Django - Transfer data from view to form
I am struggling with the update of database information with the forms, and simply passing information between views. I could really use some advice because I am fairly new to Django. The flow goes like this: 1. First form; I transfer the article price and title to the view "event" 2. The view "event" handles title and price and ask for confirmation in the html form 3. Once confirmed, it directs that information to the view "transact_test", I want this view to handle the update of the database via a new form that is build with the Article model. But it provides the error message : "didn't return an HttpResponse object. It returned None instead." -
(Django) Edit form data that is not ModelForm
Currently I'm having a Form model (unfortunately not ModelForm) with data which need to be edited/updated. After looking through many posts (most of which were related to ModelForm), I found a way to edit/update the data of Form inside Django shell with the following syntax: Drug.objects.filter(drug_id='d61').update(drug_id='d7') It worked inside the shell, yet when I did the same thing in the html form, nothing happened: data remained unchanged, no error was raised. drugs/forms.py from django import forms class DrugForm(forms.Form): drug_id = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'drug_id', 'data-val': 'true', 'data-val-required': 'Please enter drug id', })) name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'name', 'data-val': 'true', 'data-val-required': 'Please enter name', })) updated_date = forms.CharField(widget=forms.DateInput(attrs={ 'class': 'form-control', 'type': 'date', 'id': 'update_date', }), required=False) drugs/models.py from django.db import models class Drug(models.Model): drug_id = models.CharField(max_length=20, unique=True, error_messages={'unique':"This drug id has already been registered."}) name = models.CharField(max_length=50) updated_date = models.DateField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.name drugs/views.py from django.shortcuts import render, redirect from django.views.generic import ListView from django.shortcuts import get_object_or_404 from .models import ( Drug, ) def update(request, drug_id): drug = get_object_or_404(Drug, drug_id=drug_id) drug_id = drug.drug_id name = drug.name updated_date = drug.updated_date if updated_date == '': updated_date = None Drug.objects.filter(drug_id=drug_id).update(drug_id=drug_id, name=name, updated_date=updated_date) return redirect("drug-list") templates/drugs/edit_drug.html {% extends 'base/base.html' … -
How to convert function base view to Generic class based for two models
i create a register view as function based, but i want to use generic class to improve my code better. this is my models.py from django.db import models from django.contrib.auth.models import User class UserRegister(models.Model): reg_user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='user') mobile = models.CharField(max_length=255, verbose_name='mobile phone number : ', unique=True) name = models.CharField(max_length=255, verbose_name='First Name : ') family = models.CharField(max_length=255, verbose_name='Last Name : ') def __str__(self): return f"{self.mobile} as {self.name}" then my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import * class RegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'email', 'password1', 'password2'] class UserForm(forms.ModelForm): class Meta: model = UserRegister fields = '__all__' then i called them both in views.py like this from django.shortcuts import render, redirect from django.views.generic import * from .forms import * def register(request): r_form = RegisterForm() u_form = UserForm() if request.method == 'POST': r_form = RegisterForm(request.POST) u_form = UserForm(request.POST) if r_form.is_valid() and u_form.is_valid(): user = r_form.save() u_form = u_form.save(commit=False) u_form.user = user u_form.save() return redirect('main') else: r_form = RegisterForm(request.POST) u_form = UserForm(request.POST) context = { 'r_form': r_form, 'u_form': u_form } return render(request, 'template.html', context) an example of generic class based that i know is only store to 1 models like class CreateUserView(CreateView): … -
DateTimeField: how to retrieve date in my local time
settings.py TIME_ZONE = 'Asia/Kolkata' models.py order_booking_time = models.DateTimeField() while creating: "order_booking_time":"2021-10-09 06:00" What it stores in database: "2021-10-08T18:53:17.097257+05:30" So i did this in serializer.py while viewing in data def get_order_booking_time(self,obj): date = obj.order_booking_time.strftime("%Y-%m-%d %H:%M:%S") return str(date) Output: "2021-10-09 00:30:00" which is not equal to what i stored in data i.e."2021-10-09 06:00" What in the way we retrieve OR store data in this "%Y-%m-%d %H:%M:%S" format with my local time -
NoReverseMatch at /news/
I have looked through a lot of questions but I still can't find an answer. NoReverseMatch at /news/ Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/news/ Django Version: 3.2.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. Exception Location: C:\Users\retar\anaconda3\envs\pc\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\retar\anaconda3\envs\pc\python.exe Python Version: 3.9.6 Python Path: ['C:\Users\retar\Desktop\polygon\fotonika', 'C:\Users\retar\anaconda3\envs\pc\python39.zip', 'C:\Users\retar\anaconda3\envs\pc\DLLs', 'C:\Users\retar\anaconda3\envs\pc\lib', 'C:\Users\retar\anaconda3\envs\pc', 'C:\Users\retar\anaconda3\envs\pc\lib\site-packages'] Server time: Fri, 08 Oct 2021 13:15:03 +0000 models.py class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) is_published = models.BooleanField(default=True) category = models.ForeignKey('Category',on_delete=models.PROTECT, null=True,) def get_absolute_url(self): return reverse('post_detail', kwargs={"pk": self.pk}) def __str__(self): return self.title news.urls from django.urls import path from . import views app_name = "news" urlpatterns = [ path('',views.PostListView.as_view(),name='all_news'), path('<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path,include from fapp import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), path('news/',include('news.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) all_news.html {% extends 'base.html' %} {% block content %}<h1> NEWS PAGE</h1> {% for post in posts %} <a href="{{ post.get_absolute_url }}">{{post.title}}</a> {% endfor … -
The same name for different models in different Django applications
I have application 1 and application 2 in a Django project. I need each application to have its own table named Task and File. And the File table in each app refers ForeignKey to the Task table in its own app. It looks like this: app1.models class Task(BasicTask): task_id = models.IntegerField(primary_key=True) class File(BasicFile): file_id = models.AutoField(primary_key=True) task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='Task_one') app2.models class Task(BasicTask): task_id = models.IntegerField(primary_key=True) class File(BasicFile): file_id = models.AutoField(primary_key=True) task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='Task_two') main.models class BasicTask(models.Model): name = models.TextField() priority = models.IntegerField() status = models.IntegerField(default=0) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, null=True, related_name='+') def __str__(self): return f"{self.id}. {self.name}" class BasicFile(models.Model): unique_id = models.TextField() status = models.IntegerField(default=0) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, null=True, related_name='+') content = models.TextField() def __str__(self): return f"{self.id}. {self.unique_id}" The problem is that I get the following errors when I make migrations: ERRORS: app2.Task.basictask_ptr: (fields.E304) Reverse accessor for 'app2.Task.basictask_ptr' clashes with reverse accessor for 'app1.Task.basictask_ptr'. HINT: Add or change a related_name argument to the definition for 'app2.Task.basictask_ptr' or 'app1.Task.basictask_ptr'. app2.Task.basictask_ptr: (fields.E305) Reverse query name for 'app2.Task.basictask_ptr' clashes with reverse query name for 'app1.Task.basictask_ptr'. HINT: Add or change a related_name argument to the definition for 'app2.Task.basictask_ptr' or 'app1.Task.basictask_ptr'. app1.Task.basictask_ptr: (fields.E304) Reverse accessor for 'app1.Task.basictask_ptr' clashes with … -
How to create a dynamic filter sidebar with Django and React?
We have to develop a simple homepage showing multiple electronic products and want to add a side bar filter that shows fields dynamicaly with the total of products based on previous filtered queryset. For example: Brand ----- Acer [11] LG [9] Lenovo [12] RAM --- 8Gb [6] 16Gb [16] Let's imagine LG does not have any laptop with 8Gb RAM, so if the user filters by 8Gb, the result will be: Brand ----- Acer [4] Lenovo [2] RAM --- [x] 8Gb [6] Which is the best way to handle this using Django and React?