Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field is only visible when on "Writing" mode
I have the following field in my Django Admin app: class ContractForm(forms.ModelForm): ativo = forms.CharField( initial="this is a test" ) The field value is visible when the logged user has all permissions (can add, change and view) on Admin's default auth console: But when a user has only view permissions, the value is not shown: Any thoughts? -
Creating an objects to database: FOREIGN KEY constraint failed
When I try create an objects to my database it give me this error FOREIGN KEY constraint failed Which I dont understand why. Anyone have an idea? models.py from django.contrib.auth.models import User from django.db import models class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) accountid = models.CharField(max_length=100) mt5password = models.CharField(max_length=100, default="default") mt5server = models.CharField(max_length=100, default="default") telegramchannel = models.CharField(max_length=100, default="default") riskpertrade = models.FloatField(max_length=100, default="1.0") balance = models.FloatField(default=2000) winrate = models.CharField(max_length=100) riskreward = models.CharField(max_length=100) result = models.CharField(max_length=100, default="Not Passed") def __str__(self): return self.accountid class AccountHistory(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) tradeid = models.CharField(max_length=100) opendate = models.CharField(max_length=100) type = models.CharField(max_length=100) volume = models.CharField(max_length=100) symbol = models.CharField(max_length=100) openprice = models.CharField(max_length=100) closedate = models.CharField(max_length=100) closeprice = models.CharField(max_length=100) profit = models.FloatField() def __str__(self): return self.tradeid Here is my function to create the database objects views.py def testfunc(): AccountHistory.objects.create(tradeid=30688, account_id=98765, opendate="8 mars", type="buy", volume=1.25, symbol="EURUSD", openprice=1.234, closedate="9 mars", closeprice=1.250, profit=9349.23) -
Why my navbar not displaying properly? displaying like text
My Navbar is coming like this: Image of my navbar Why not like this : Image of desired navbar PLEAES ASSIST! (I AM NEW PROGRMMER CURRENTLY LEARNIG WEB DEV.) -
How to best handle the access with Django to a database that has some DateTime fields stored in local timezone while others are stored in UTC?
What would be the best approach to handle the following case with Django? Django needs access to a database (in MariaDB) in which datetime values are stored in UTC timezone, except for one table that has all values for all of its datetime columns stored in local timezone (obviously different that UTC). This particular table is being populated by a different system, not Django, and for some reasons we cannot have the option to convert the timestamps in that table to UTC or change that system to start storing the values in UTC. I am asking your opinion for an approach to the above case that would be as seamless as it can be, preferably without doing conversions here and there in various parts of the codebase while accessing and filtering on the datetime fields of this "problematic" table / model. I think an approach at the model layer, which will let Django ORM work as if the values for that table were stored in UTC timezone, would be preferable. Perhaps a solution based on a custom model field that does the conversions from and back to the database "transparently". Am I thinking right? Or perhaps there is a better … -
android and "server" outh keys gcloud
I have android and ios OAuth2.0 Credentials for authenticating with outh2.0, I do get my access and refreshtokens. I store the refreshToken . Then in a django server I try to get a new access_token with above refresh token by posting to https://accounts.google.com/o/oauth2/token using new Auth2.0 Credentials for a web app. params = { "grant_type": "refresh_token", "refresh_token": user_refresh_token, "token_uri": authorization_url, "access_type": "offline", "client_id": client_id, "redirect_uri": "https://www.googleapis.com/oauth2/v4/token", "client_secret": client_secret, } errorThe credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret The access token is then used to get creds and access user calendar. creds = google.oauth2.credentials.Credentials(access_token) service = build('calendar', 'v3', credentials=creds) Note the keys are for the same project. Is there a way to use a service account to get a refresh token ? Can I use different oAuth credentials for the same project? Can I "merge"/"mix" the clients? What can I do to get a refresh token with the web App Credentials? -
Find MS SQL Server column information for Django models
I have done this before but can't remember how, so forgive me if this has already been answered. I want to create a model in Django from an MS SQL Server table. How would I find the relevant information for the columns? I used the command line to retrieve this information. An example of what I am looking for: region = models.CharField(db_column='Region', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. -
Django data entry with relationships, what is the standard or most effecient way?
With a model without a relationship the, the most efficient way for data entry would be to use a django.forms.ModelForm. Take the following example: class Customer(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) def __str__(self): return f"{self.first_name} {self.last_name}" class CustomerModelForm(forms.ModelForm): class Meta: fields = ("first_name", "last_name") model = Customer form = CustomerModelForm(data={"first_name": "Jon", "last_name": "Doe"}) if form.is_valid(): form.save() But when you add in relationships, what is the most efficient or best standard to follow, let's update the model to: class Customer(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) address = models.ForeignKey( "Address", on_delete=models.PROTECT ) def __str__(self): return f"{self.first_name} {self.last_name}" class Address(models.Model): street = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=2) zip_code = models.CharField(max_length=5) def __str__(self): return f"{self.street}, {self.city}, {self.state} {self.zip_code}" One solution might be: class CustomerModelForm(forms.ModelForm): class Meta: fields = ("first_name", "last_name", "address") model = Customer class AddressModelForm(forms.ModelForm): class Meta: fields = ( "street", "city", "state", "zip_code" ) model = Address class Customer(forms.Form): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) street = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=2) zip_code = models.CharField(max_length=5) def save(self): address_form = AddressModelForm( data={ "street": "123 Sycamore St", "city": "Eagles Harbor", "state": "AD", "zip_code": "12345" } ) if address_form.is_valid(): address = address_form.save() customer_form = CustomerModelForm( data={"first_name": "Jon", "last_name": "Doe"} … -
on_save() is not triggered when model is created
I got the two following models: class Stuff(models.Model): ... def custom_function(self): ... class MyModel(models.Model): name = models.CharField(max_length=200) many_stuff = models.ManyToManyField(Stuff, related_name="many_stuff+") many_other_stuff = models.ManyToManyField(Stuff, related_name="many_other_stuff+") def __init__(self, *args, **kwargs): super(MyModel, self).__init__(*args, **kwargs) for stuff in self.many_stuff.all(): many_stuff.custom_function() def on_save(self, *args, **kwargs): for stuff in self.many_stuff.all(): many_stuff.custom_function() super(MyModel, self).save(*args, **kwargs) When I create a new instance of MyModel through the Django Admin, I want to execute for each Stuff object, a function. It works on_save but I cannot make it work on __init__ for some reason. If I create the new instance, the functions don't get executed. If I save the newly created instance, the functions do get executed. To be more specific, when I use this __init__ method, the model breaks on instance creation with the error: MyModel needs to have a value for field "id" before this many-to-many relationship can be used. I also attempted doing the same thing with the post_save signal, instead of using __init__ and on_save but I had the same problem. On object creation, the function custom_function did not get executed, but it did when I saved the object after it has been created by clicking on the save button. Any ideas? -
Django logs user in by default
I have a Django account, where there is only one user for the entire app. I also have not setup admin for this app. The problem is, when I first start my docker container for the Django app and type in my domain, I am already logged in. Even if I open this in a private window or another browser (Firefox; I normally use Chrome), the issue still remains. This is the script to create the user: from django.contrib.auth.models import User import os # Create user and save to the database if User.objects.exists(): print("user already exists") else: username = os.environ.get("USER_USERNAME") email = os.environ.get("USER_EMAIL") password = os.environ.get("USER_PASSWORD") if not username or not email or not password: print("user information not supplied. please check your .env that USER_USERNAME, USER_EMAIL, USER_PASSWORD are all set.") User.objects.create_user(username, email, password) print("created user") This is called from docker-compose.yml like this: services: web: build: . command: > bash -c "mkdir -p static && python manage.py collectstatic --no-input && python manage.py migrate && python manage.py shell < init/create_user.py && $$RUN_SERVER_COMMAND" Why does this happen? Is there a setting to turn off "logged in by default"? -
Django MultiSelect Dropdown Checkbox to update Models
How can I create a multiselect dropdown checkbox (checked=True, unchecked=False) to update my models? Below is my current code: ###### models.py ####### class TestProfile(models.Model): revenue = models.BooleanField(default=False) costOfRevenue = models.BooleanField(default=False) ###### forms.py ####### class CreateTestProfile(forms.ModelForm): class Meta: model = TestProfile fields = '__all__' ###### views.py ###### def test(request): profile_form = CreateTestProfile() if request.method == 'POST': profile_form = CreateTestProfile(request.POST) if profile_form.is_valid(): profile_form.save() return redirect('/dashboard') else: profile_form = CreateTestProfile() return redirect('/dashboard') dict = {'profile_form': profile_form} return render(request, 'demo/test.html', dict) ###### test.html template ######## <div class="w-1/2"> <form method="POST"> {% csrf_token %} {{profile_form|crispy}} <input type="submit" value="Submit"> </form> </div> If the dropdown is checked for revenue, then I would like to update the TestProfile model's revenue value to be True. Any help would be much appreciated! -
Password field is visible and not encrypted in Django admin site
So to use email as username I override the build-in User model like this (inspired by Django source code) models.py class User(AbstractUser): username = None email = models.EmailField(unique=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email admin.py @admin.register(User) class UserAdmin(admin.ModelAdmin): fieldsets = ( (None, {"fields": ("email", "password")}), (("Personal info"), {"fields": ("first_name", "last_name")}), ( ("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("email", "password1", "password2"), }, ), ) list_display = ("email", "is_active", "is_staff", "is_superuser") list_filter = ("is_active", "is_staff", "is_superuser") search_fields = ("email",) ordering = ("email",) filter_horizontal = ("groups", "user_permissions",) But this is how it looks like when I go to Admin site to change a user: Password is visible and not hashed and no link to change password form. Comparing to what it looks like on a default Django project: Password is not visible and there's a link to change password form So clearly I'm missing something but I can't figure out what it is. -
Django endpoint with slug and id
How to create endpoint that will return data using two different fields? Model: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) post_title = models.CharField(max_length = 125) text = models.TextField() slug = models.SlugField(max_length=100, unique=True, blank=True) Serializer: class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = [ 'id', 'post_title', 'text', 'slug', ] lookup_field = 'slug' View: class PostViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer ordering = ['id'] lookup_field = 'slug' Urls: router = routers.DefaultRouter() router.register(r'post', PostViewSet) urlpatterns = [ path(r'', include(router.urls)), ] Now my endpoints works only for slugs my question is what should I modify to use endpoints like: localhost:9000/post/f18e8017-ebbc-432d-b1c6-1ff23737a744 and localhost:9000/post/post-title -
taggit.managers.TaggableManager how to use it with Django FilterSet Class and filter with __in all (every) items
unlike default __in filter, which return any records which matches at least one item in the list, I want to return all records who matches all items in the list using Django FilterSet Class and Django-taggit TaggableManager field -
How do I make two choice fields that will be saved as one value in the database in django?
I have created a Task model: class Task(models.Model): name = models.CharField(max_length=200, null=True) author = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) eta = models.CharField(max_length=20, null=True, blank=True) I want the eta to be saved as a CharField that will be inputed by the user via two fields: one field for the measurement, for example: months, days, minutes etc. and one field for the amount, for example: 1, 4, 10 etc... at the end I would like to have the eta field be '1 hour', '30 minutes', '2 weeks' etc... I want the user to input the fields and then have the backend save them in to the right format. can anyone help with how to do this? or maybe if someone has an idea on how to do this in a better way. I want to make an application that will detect when the ETA already passed and alert the user of that. -
How to store UInt8Array in django model
As the title said, How to store UInt8Array in django model? Hope you can help me out, thanks a lot. -
filter by category the subcategories belonging to the same category of different products in the django admin area
I want when am adding the products in the django admin, when I enter the category of the product to list only the subcategories belonging only to the category. Here is my models class Category(models.Model): category_name = models.CharField(max_length=50) slug = models.SlugField(max_length=100, unique=True) category_image = models.ImageField(upload_to = 'photos/categories', blank = True) created_at = models.DateTimeField(auto_now_add=True) class Sub_Category(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category_name = models.CharField(max_length=50) slug = models.SlugField(max_length=100, unique=True) In my admin area I want the subcategory to be filtered from the category when adding different products.... Like showing say Furniture(category) to show chairs, beds (subcategories) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE) product_name = models.CharField(max_length = 200, unique=True) slug = models.SlugField(max_length=200, blank=True) description = models.TextField(max_length = 1000) price = models.IntegerField() discount_price = models.IntegerField(blank=True) on_offer = models.BooleanField(default=False) -
Simplejwt don't appear on importation options
I had installed djangorestframework-simplejwt with pip, so had i configure settings.py file for to use it, but, when i try to import the package, it doesn't has showing in importable package list. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), The importations list: Can anyone help me? -
ECDSA algorithm in netsuite
How can i use ECDSA encryption algorithm with a private key to generate a digital signature in suitescript. Does netsuite support it and if not can i use it as an external library? Thanks in advance -
ModuleNotFoundError even if module (app name) is installed
I want to start a project but when trying to makemigrations, I got ModuleNotFoundError even if my apps is "installed" in settings I have 2 apps: authentication and blog In authentication, I have override User model with AbstractUser and that all Python 3.8.3 / Django 3.2.3 I've try to re-install librairies in my virtual env but doesn't works I have checked for typ errors but there are no errors whats is wrong? -
What type of database field for a multiple choice Search filter with DRF?
What type of Database field is the most efficent one for a drf based search filter? I'm trying to build a search feature where i can search by a specific set of features. You could compare it to an hotel search were you filter by Amenities that you want. Are many to many fields the best choice for this? -
How to render images in Django
I am using the latest version of Django and I am having problems rendering my images. My img tag doesn't work so I googled it and the problem seems to be the static files. So I followed some tutorials online but none of them worked for me. It will be awesome if you could provide me with some guidance, thanks. Path of my static folder Do I need to move my static folder else where, do I need to add some line of code? Path of my index.html Below is my html code... {% extends 'landing/base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html> <head> <style> html,body{overflow-y: scroll; } h3 { font-weight: lighter; } .btn-space { margin-right: 5px; margin-left: 5px; } h1{ font-size: 75px; font-weight: bold; background: -webkit-linear-gradient(#00ffd0, #c493ff); -webkit-background-clip: text; -webkit-text-fill-color: transparent; padding-top:13%; justify-content: center; font-family: 'Lato', sans-serif; } p{ background: -webkit-linear-gradient(#ffffff, #4287f5); -webkit-background-clip: text; -webkit-text-fill-color: transparent; padding:15px; display: flex; justify-content: center; font-family: 'Lato', sans-serif; } .c{ font-size: 15px; background: -webkit-linear-gradient(#ffffff, #3c3b3d); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } body { background-color: black /*background-image: url('a/circle.svg'); background-size: cover;*/ } .d { font-size: 25px; background: -webkit-linear-gradient(#ffffff, #c493ff); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .e { padding-left: 20%; padding-right: 20%; text-align: … -
Django Crispy forms Validators
I have Django and I use crispy forms to enter data about a user. Problem is, some new users have 'diacritic' symbols in their name. Then I get the following error: Enter a valid “slug” consisting of letters, numbers, underscores or hyphens. For example: 'Coric' is ok, but 'Čorić' gets the error. I can manualy write it into the database, so I think that the problem is with crispy forms. How can I include 'š/č/ć/ž' simbols in the input form? -
Django Queryset filter
My django table contains a field that contains comma-separated strings. class RawData(TimeStampModelMixin): id = models.UUIDField(primary_key=True) media = models.TextField() media column will hold values like 'Multimedia, TV', 'Multimedia, TV Station'. I need to filter Rawdata table rows such that media column contains 'TV' or 'Multimedia'. __icontains doesn't provide the accurate result. If I do Rawdata.objects.filter(media__contains='TV') then it will return both 'Multimedia, TV', 'Multimedia, TV Station' rows. But I need only the 'Multimedia, TV' row. Is there any way to achieve this via queryset API? -
Celery has DNS resolution problems?
I used Celery for email registration asynchronously, but when I trigger this asynchronous request, the following error will appear Traceback (most recent call last): File "d:\python3\lib\site-packages\dns\resolver.py", line 982, in nameservers raise NotImplementedError NotImplementedError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\python3\lib\site-packages\celery\app\trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "d:\python3\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "E:\Exploit_blog\blog_index_html\tasks.py", line 9, in send_email send_mail( File "d:\python3\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "d:\python3\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "d:\python3\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "d:\python3\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "d:\python3\lib\smtplib.py", line 1034, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout, File "d:\python3\lib\smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "d:\python3\lib\smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "d:\python3\lib\smtplib.py", line 1040, in _get_socket new_socket = super()._get_socket(host, port, timeout) File "d:\python3\lib\smtplib.py", line 310, in _get_socket return socket.create_connection((host, port), timeout, File "d:\python3\lib\site-packages\eventlet\green\socket.py", line 44, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 543, in getaddrinfo qname, addrs = _getaddrinfo_lookup(host, family, flags) File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 505, in _getaddrinfo_lookup answer = resolve(host, qfamily, … -
Django get last value for each forgin key values
In models.py class loan(models.Model): completed=models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True,null=True) application_id=models.CharField(max_length=100,unique=True) class topay(models.Model): loanapplication=models.ForeignKey(loan,on_delete=models.CASCADE,null=True) paymentdate=models.DateField(null=True, blank=True) How to get last paymentdate for every loan application In views.py topay.objects.filter().values().annotate(last=Max('paymentdate'))