Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Explicitly defining fields on ModelSerializer overrides Model's parameters like verbose_name and validators
Imagine having a simple model like the one bellow: from utils.validators import name_validator class Customer(models.Model): name = models.CharField(verbose_name="Customer Name", validators=[name_validator]) email = models.EmailField(verbose_name="Customer Email") def __str__(self): return self.name Now if I explicitly define a filed on my serializer, both validators and verbose_name are lost. I can use label= and validatos= when defining the field on my serializer but I don't want to repeat myself. What if I have multiple serializer pointing to the same Model? class CustomerSerilizer(serializers.ModelSerializer): custom_field_name = serializers.CharField(source="username") class Meta: model = Customer fields = "__all__" Is there anyway to prevent this from happening? -
Wagtail - Override internal links in richtexteditor
Since I use wagtail headlessly the internal links get messed up due to them using the site-url listed in settings. Instead, I want to be able to override that same URL and point them to my frontend. This post talks a little bit about it in 2018, but I'm hoping this has changed? Wagtail: Is it possible to disable prepending internal link's with the site domain? For external links you'd do something like this to override it: class NewWindowExternalLinkHandler(LinkHandler): # This specifies to do this override for external links only. identifier = 'external' @classmethod def expand_db_attributes(cls, attrs): href = attrs["href"] print(attrs) # Let's add the target attr, and also rel="noopener" + noreferrer fallback. # See https://github.com/whatwg/html/issues/4078. return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href) Is it possible to do the same for internal links? E.g now since I use a multi-site setup my link looks something like: https://localhost.my-backend-api-domain.com/page/pagename I want it to look like this: https://my-frontend-domain.com/page/pagename -
Post only unique key value pairs to redis instance
I am POSTing a list of key values pairs to a redis_instance. I would like to first check if any of the keys/values I am posting to redis already exist to avoid having duplicate key value pairs or instances where a pre-existing key has a different value or a pre-existing value has a different key so for example avoiding scenarios like this: Fred: Luke Luke: Jim Jim: Jane and instead only allow these pairs to be written to my redis_instance: Fred: Luke Jim: Jane This is what I have: @api_view(['GET', 'POST']) def manage_items(request, *args, **kwargs): if request.method == 'GET': items = {} count = 0 for key in redis_instance.keys("*"): items[key.decode("utf-8")] = redis_instance.get(key) count += 1 response = { 'count': count, 'msg': f"Found {count} items.", 'items': items } return Response(response, status=200) elif request.method == 'POST': item = json.loads(request.body) keys = list(item.keys()) values = list(item.values()) for i in range(0, len(keys)): redis_instance.set(keys[i], values[i]) response = { 'msg': f"{keys} successfully set to {values}" } return Response(response, 201) not quite sure how to carry this out -
raise TypeError("%s() got an unexpected keyword argument '%s
I am trying to create super user in django==4.0.1 when add my information i get this error raise TypeError("%s() got an unexpected keyword argument '%s I trying this and get the same error File "C:\Users\ZAKARIA\Desktop\task\Users\models.py", line 39, in create_superuser user =self.create_user( File "C:\Users\ZAKARIA\Desktop\task\Users\models.py", line 24, in create_user user =self.model( File "C:\Users\ZAKARIA\Desktop\task\env\lib\site-packages\django\db\models\base.py", line 507, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: NewUser() got an unexpected keyword argument 'is_staff' can any one help my to solve this problem my model : from statistics import mode from time import timezone import django from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser ,BaseUserManager,PermissionsMixin class CustomAccountsManager(BaseUserManager): use_in_migrations: True def create_user(self ,email,username, first_name,last_name,password=None,**extra_fields): if not last_name: raise ValueError(_('User must a last name')) elif not first_name: raise ValueError(_('User must have a firstName')) elif not username: raise ValueError(_('User must have a username')) elif not email : raise ValueError(_('User must provide an email address')) user =self.model(email= self.normalize_email(email), username=username,first_name=first_name,last_name =last_name,**extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, email ,username,first_name,last_name,password=None, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser' , True) extra_fields.setdefault('is_admin',True) user =self.create_user(email= self.normalize_email(email), username=username,first_name=first_name,last_name =last_name,password=password,**extra_fields) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is staff=True') if extra_fields.get('is_superuser') is not … -
Django whats the best model for this table
I am lookin for the best way to match the first column with the 2nd & 3rd columns? Foerign key and ManyToManyField didnt work. -
Django - Displaying content based on permissions in a class based view
I want to display an edit link on certain content if the user has permission to edit the content. I've done some research and it appears that the best way to do this is via the view. I saw some vague suggestion to use permissions to add the link via context. As a beginner, I am not sure how to go about this. Any suggestions? The view: class CompanyProjectsDetailView(UpdateView): queryset = Project.objects.get_with_counted_notes_documents_todos() template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm The model: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) -
How remove password from response in django
Code: SERILIZERS class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("email", "user_name", "password") def create(self, validated_data): return User.objects.create_user(**validated_data) VIEWS @api_view(["POST"]) @permission_classes([AllowAny]) def CreateUserView(request): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) MODELS class CustomAccountManager(BaseUserManager): def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_("You must provide an email address")) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user After i post user i got response data with password. { "email": "mawqgvxdfdat1@mat.com", "user_name": "sdwxcvgfsdefsdf", "password": "pbkdf2_sha256$320000$g74DLAMRDypcK6LuGriBio$ } How can i remove that password from returned data? -
Django queryset to CSV, string field with quotes
I have a feature where i translate a queryset to a CSV, and i have two string fields coming from a JSON, "media" and "brand", but when i export it to CSV i got the media result with quotes and the brand field without quotes. I want to remove that quotes without having to parse the CSV because of performance. This is the process i do: from django.db import connection from django.db.models.functions import Cast # Get queryset fields = { "Media:: Cast("event__media_name", output_field=CharField()), "Brand": Cast("event__brand_name", output_field=CharField()), } queryset = ( base_queryset.order_by("id") .annotate(**fields) .values(*fields.keys()) ) # Create CSV file filename = "filename.csv" path = f"reports/{filename}" folder = tempfile.mkdtemp() temp_path = os.path.join(folder, filename) # Copy values into CSV sql, params = queryset.query.sql_with_params() sql = f"COPY ({sql}) TO STDOUT WITH (FORMAT CSV, HEADER, DELIMITER ',')" with connection.cursor() as cur: sql = cur.mogrify(sql, params) cur.copy_expert(sql, file) -
Foreign Key Constraint is failed is showing while getting auth token using Token authentication provided by django rest framework
I have created a custom model using ABSTRACTBASE USER in django. Now i am trying to generate auth token and it is showing Foreign key constraint fail error. I a able to login and register the user to the custom model. My AUTH_USER_MODEL is set to the custom model i have created -
ModelForm customisation with image upload in django
i am new to django and in my project i have a form that lets the user update his/hers profile picture. The problem is that the way i wrote the code for that form the output in the browser is like this: But the thing is i don't want the first line (Profile pic:...) to show up. Is there any way i can do that?? The code: views.py def profile_view(request, profile_id): askedprofile = Profile.objects.get(pk=profile_id) profiles = Profile.objects.all() form = ProfileForm(request.POST, request.FILES, instance=askedprofile) if request.method == "POST": if form.is_valid(): image_path = askedprofile.profile_pic.path if os.path.exists(image_path): os.remove(image_path) form.save() return redirect('myprofile', profile_id=profile_id) context = { 'askedprofile': askedprofile, 'profiles': profiles, 'form': form, } return render(request, 'my_profile.html', context) models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) username = models.CharField(max_length=200, null=True) password = models.CharField(max_length=50, null=True) profile_pic = models.ImageField(null=True, blank=True, upload_to='images/') forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['profile_pic'] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name="home"), path('forum/', views.forum_view, name="forum"), path('forum_detail/<topic_id>', views.forum_detail_view, name="forumdetail"), path('login/', views.login_view, name="login"), path('signup/', views.signup_view, name="signup"), path('logout/', views.logout_view, name="logout"), path('forum-create/', views.forum_create, name="forumcreate"), path('answer-create/<topic_id>', views.answer_create, name="answercreate"), path('topic-delete/<topic_id>', views.delete_topic, name="deletetopic"), path('answer-delete/<answer_id>', views.delete_answer, name="deleteanswer"), path('my-profile/<profile_id>', views.profile_view, name="myprofile"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my_profile.html {% for profile in profiles %} {% if profile.user == request.user %} … -
Django how to pass arguments to a view with {% url %}
I have this url path: urlpatterns = [ path('f/<str:a>/<str:b>', views.f, name='f') And the view: def f(request, a, b): # some code The f view takes 2 paramters. Now if I have the code below in a template: <a href="{% url 'f' %}">click me</a> How can I pass values for parameters a and b? -
Django/PostgreSQL not displaying search result
I am unable to retrieve any search results when searching for items. I am using Postgresql and Django. Below is my code. I am not sure if I am not doing the search query right or I just cannot display the results. I have the search bar in "inventory_management.html". I am trying to get it to where the user searches for an item, and then a list of the displayed items are shown. Any help would be greatly appreciated! models.py class Inventory(models.Model): product = models.CharField(max_length=50) description = models.CharField(max_length=250) paid = models.DecimalField(null=True, max_digits=5, decimal_places=2) bin = models.CharField(max_length=4) listdate = models.DateField(null=True, blank=True) listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) solddate = models.DateField(null=True, blank=True) soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) shipdate = models.DateField(null=True, blank=True) shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.product + "\n" + self.description + "\n" + self.paid + self.bin + "\n" + self.listdate + "\n" + self.listprice + "\n" + self.solddate + "\n" + self.soldprice + "\n" + self.shipdate + "\n" + self.shipcost views.py @login_required(login_url="/login") def search(request): q = request.GET.get('q') if q: vector = SearchVector('product', 'description') query = SearchQuery(q) searchinv = Inventory.objects.annotate(search=vector).filter(search=query) else: searchinv = None return render(request, 'portal/search.html', {"searchinv": searchinv}) inventory_management.html (where … -
How to properly migrate a monolith architecture app to a microservice app in Django
Today I come with this question probably to someone who has large experience in this. Basically what the title indicates. We have that app and we have to migrate it to microservices. We didn't find any solid approach (or we felt it like that) about this. What we ended up doing is creating 1 project per microservice (a single functionality related to a module app, in general) but then we had some problems because we already had a database to work with since this is already a functioning app. We had problems communicating with the existing models, so basically what we did was to point in every settings.py of the projects to the existing DB, and with python3 manage.py inspectdb, we grabbed the existing models. This approach ended up working, but we feel that is not the best approach. We had a lot of problems with circular imports and more. Is out there good practices about microservices with Django, and how to properly do it, like in most of the cases that we want to create something with the framework? If someone knows or has something we would really appreciate it! -
SortableHiddenMixin AttributeError: module 'nested_admin' has no attribute 'SortableHiddenMixin'
Estoy buscando usar la opcion de arrastrar y soltar para ordenar elmentos de una lista en django. admin usando nested_admin 3.2.4. vi este issue en github LINK PERO NO FUNCIONA. return ModuleType.__getattribute__(self, name) AttributeError: module 'nested_admin' has no attribute 'SortableHiddenMixin' class ReportSectionFieldInline(nested_admin.SortableHiddenMixin, nested_admin.NestedTabularInline): model = ReportSectionField extra = 0 classes = ['collapse'] class ReportSectionInline(nested_admin.NestedTabularInline): model = ReportSection inlines = [ReportSectionFieldInline] extra = 0 classes = ['secciones-informe'] class Media: css = { "all": ("admin/css/reportsection.css",) } class ReportAdmin(nested_admin.NestedModelAdmin): list_display = ('id', 'description', 'type_report', 'modulo', 'active',) search_fields = ('description', 'type_report',) list_filter = ('type_report', 'active',) inlines = [ReportSectionInline] -
Field 'LOCATION' expected a number but got <LOCATION: LOCATION object (71)>
I have foreign key LOCATION in LOCATION table to get the Location value in another table, i got the error json_object is my input, item is another table Code=item["LOCATION"]=LOCATION.objects.get(LOCATION = json_object["LOCATION"]) error=Field 'LOCATION' expected a number but got <LOCATION: LOCATION object (71)>. -
Getting (NoReverseMatch at / Reverse for 'chatpage' with no arguments not found. 1 pattern(s) tried: ['ChatView/(?P<uname>[^/]+)\\Z'] after login
I know this question had been asked for more than five times but I had tried many solutions as a noob and still weren't able to find out the solution. I had been following the django-channels documentation and instead of room-name I want to display username in the URL but when I try as per instructions this error occurred. This is the image of error. Image of error when I run it on Mozilla firefox and this is what it is saying in terminal Image of error in terminal and this is the line of chatpage urls.py line which is I am trying to display with username path('ChatView/<str:uname>', login_required(views.ChatView.as_view()), name="chatpage"), and this is the line of views.py for chatpage. class ChatView(View): def get(request, username): uname = User.objects.get(username=username) return render(request, 'chatbot/chatPage.html', { 'uname': uname }, context_instance=RequestContext(request)) and this is the Html code that I use for username input: <input class="w-full text-lg py-2 border-b border-gray-300 focus:outline-none focus:border-indigo-500" type="text" placeholder="Enter Your Username" id="username" name="username" value="{{data.username}}" Required> These are the four links of pastebin for whole code: views.py urls.py chatpage.html signin.html -
Complicated Neted Admin Inline
I have a complicated model, where playlists can be created on two levels: UserGroup and User. Further, these playlists are targeted to a specific weekday. So Users/UserGroups can have separate playlists for each day of the week. To manage the user playlists in the admin, I'm looking to add the User and UserGroup an inline of all weekdays, and under each weekday the inline of all songs (for that weekday). Hopefully the image below will clear this up a bit. To add to the confusion, the songs per a specific weekday should include both User songs and also UserGroup songs. My models: UserGroup name = models.CharField(max_length=255) User name = models.CharField(max_length=255) UserGroupSong file = models.FileField() weekday = models.ForeignKey(Weekday, on_delete=models.PROTECT) user_group = models.ForeignKey(UserGroup, on_delete=models.PROTECT) UserSong file = models.FileField() weekday = models.ForeignKey(Weekday, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) inherit = models.BooleanField(verbose_name='Include songs from user-group for this weekday?') class Weekday(models.Model): day = models.CharField(max_length=255) # Pre-populated with values: Sun, Mon, Tue, Wed, Thu, Fri, Sat Any help will be greatly appreciated. -
How to insert value in a forign key from the csv file
I want to insert the Matches and Delivery table from matches.csv and delivery.csv in the Django database. models.py looks like this: from django.db import models # Create your models here. class Matches(models.Model): id=models.IntegerField(primary_key=True) season = models.IntegerField() city = models.CharField(max_length=200) date = models.DateField(null=True) team1 = models.CharField(max_length=200) team2 = models.CharField(max_length=200) toss_winner = models.CharField(max_length=200,null=True) toss_decision = models.CharField(max_length=200,null=True) result = models.CharField(max_length=200,null=True) dl_applied = models.CharField(max_length=200,null=True) winner = models.CharField(max_length=200,null=True) win_by_runs = models.IntegerField(null=True) win_by_wickets = models.IntegerField(null=True) player_of_match = models.CharField(max_length=200,null=True) venue = models.CharField(max_length=200,null=True) umpire1 = models.CharField(max_length=200,null=True) umpire2 = models.CharField(max_length=200,null=True) umpire3 = models.CharField(max_length=200,null=True) class Deliveries(models.Model): match_id= models.ForeignKey(Matches,on_delete=models.CASCADE) inning = models.IntegerField() batting_team = models.CharField(max_length=100) bowling_team = models.CharField(max_length=100) over = models.IntegerField() ball = models.IntegerField() batsman = models.CharField(max_length=100) non_striker = models.CharField(max_length=100) bowler = models.CharField(max_length=100) is_super_over = models.IntegerField() wide_runs = models.IntegerField() bye_runs = models.IntegerField() legbye_runs = models.IntegerField() noball_runs = models.IntegerField() penalty_runs = models.IntegerField() batsman_runs = models.IntegerField() extra_runs = models.IntegerField() total_runs = models.IntegerField() player_dismissed = models.CharField(max_length=100) dismissal_kind = models.CharField(max_length=100) fielder =models.CharField(max_length=100) I am updating this table using management/commands/updateModels.py and my updateModles.py looks like this:django from django.core.management.base import BaseCommand import csv from match.models import Matches, Deliveries class Command(BaseCommand): help = 'import booms' def add_arguments(self, parser): pass def handle(self, *args, **options): # database connections here with open('matches.csv') as f: match_obj = csv.DictReader(f) for match in match_obj: … -
How to read from Form Data on Django view?
I need to read data from "Form-Data" on Django 3.2, how to do it on a view? Thank you -
Forbidden (CSRF token missing or incorrect.): /api/token/refresh/
When using the @csrf_protect decorator in the view, I encountered the error "Forbidden (CSRF token missing or incorrect): /api/token/refresh/" views.py @api_view(['POST']) @renderer_classes([CustomizeJSONRenderer]) @csrf_protect def refresh_token_view(request): refresh_token = request.COOKIES.get('refreshtoken') # check valid refresh token if refresh_token is None: raise exceptions.AuthenticationFailed('Authentication credentials were not provided, please login.') try: payload = jwt.decode(refresh_token, settings.REFRESH_TOKEN_SECRET, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('expired refresh token, please login again.') user = User.objects.filter(id=payload.get('user_id')).first() # check valid user if user is None: raise exceptions.AuthenticationFailed('user not found.') if not user.is_active: raise exceptions.AuthenticationFailed('user is inactive.') access_token = generate_access_token(user) # create new access token return Response({'access_token': access_token}) -
Please help me, I am unable to update my note taking app api using CRUD
This is the tools.py from .models import Note from .serializers import NoteSerializer from rest_framework.response import Response from django.shortcuts import get_object_or_404 def getNoteslist(request): notes=Note.objects.all().order_by('-updated') serializer=NoteSerializer(notes, many=True) return Response(serializer.data) def NoteDetail(request, pk): notedetail=get_object_or_404(Note,id=pk) serializer=NoteSerializer(notedetail, many=False) return Response(serializer.data) def createNote(request): data=request.data note=Note.objects.create( title=data['title'], body=data['body'] ) serializer=NoteSerializer(note, many=False) return Response(serializer.data) def updateNote(request, pk): note=Note.objects.get(id=pk) serializer=NoteSerializer(instance=note, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) def delete(request, pk): note=get_object_or_404(Note,id=pk) note.delete() return Response('Note is deleted!') This is the views.py from .models import Note from .tools import getNoteslist,NoteDetail,updateNote,createNote,delete from rest_framework.decorators import api_view @api_view(['GET']) def getNotes(request): return getNoteslist(request) @api_view(['POST']) def createNotes(request): return createNote(request) @api_view(['GET']) def getNote(request,pk): return NoteDetail(request, pk) @api_view(['POST']) def updateNote(request, pk): return updateNote(request, pk) @api_view(['DELETE']) def delNote(request, pk): return delete(request, pk) This is the urls.py from django.urls import path from . import views from rest_framework.documentation import include_docs_urls from rest_framework_swagger.views import get_swagger_view schema_view=get_swagger_view(title='NOTE TAKING APi') API_TITLE='NOTE TAKING APi' API_DESCRIPTION='A note taking API for creating and editing notes.' urlpatterns=[ path('',views.getNotes,name='Notes'), path('create/',views.createNotes,name='Notes'), path('<int:pk>/',views.getNote,name='note'), path('update/<int:pk>/',views.updateNote,name='note'), path('delete/<int:pk>/',views.delNote,name='note'), path('docs/',include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)), path('swagger-docs/',schema_view) ] here is the error: **Internal Server Error: /Note/update/4/ Traceback (most recent call last): File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Django: overwriting the method model of the abstract model, from inside the inherited models
I have a problem with re-assigning some var in my model, I have a model like this: class ExpireTime(models.Model): """Expire time fields and methods in abstract mode""" def expire_time(): return create_expire_time(seconds=10) expire = models.DateTimeField(default=expire_time) def is_expired(self) -> bool: return self.expire < timezone.now() class Meta: abstract = True but in the different models that used this abstract model, I need the use different expiration times in the exprie_time: def expire_time(): return create_expire_time(seconds=10) so I am trying to overwrite this method in the model that was inherited from ExpireTime but it has no effect. so how can I solve this situation? Should I not use the abstract model in this situation? -
How to update a users account balance on purchase in a Django View?
For a side project I'm working on creating a simulated cryptocurrency exchange application. For the first part of this I'm just creating a simple page where the users can buy and sell BTC for USD and it will update their respective balances for each one. I have created a form for the 'Trade' and there's two model tables - 'Trade' and 'Portfolio. How do I set this up so when a 'Trade' takes place, it updates the amount of tokens (when buying) or the amount of USD (when selling) in the 'Portfolio', and if it doesn't exist it creates a new entry? models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Trade(models.Model): token_name = models.CharField(max_length=100) token_symbol = models.CharField(max_length=10) date = models.DateTimeField(default=timezone.now) account = models.ForeignKey(User, on_delete=models.CASCADE, related_name='trader') amount = models.FloatField() price = models.FloatField() type = models.CharField(max_length=15, choices=( ("Market Buy", "Market Buy"), ("Market Sell", "Market Sell"))) def id(self): return id(self.id) class Portfolio(models.Model): token_name = models.CharField(max_length=100, unique=True, default="United States Dollar") token_symbol = models.CharField(max_length=10, default="USD") account = models.ForeignKey(User, on_delete=models.CASCADE, related_name='portfolio') amount_holding = models.FloatField(default="100000") def id(self): return id(self.id) Views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Trade from .models import Portfolio from django.contrib import messages from … -
ValueError: Cannot assign "1": "User.jsgGroupName" must be a "JsgGroup" instance
I am getting ValueError: Cannot assign "1": "User.jsgGroupName" must be a "JsgGroup" instance. this error when using a foreign key in a custom user model. I guess there is some problem with the Foreign Key. There is no proper solution for django rest framework based app and I am using drf. models.py from django.db import models from django.contrib.auth.models import User, AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.translation import gettext_lazy as _ from django.utils import timezone class Region(models.Model): RegionName = models.CharField(max_length=20) numGroups = models.IntegerField(default=0) def __str__(self): return self.RegionName class Group(models.Model): GroupName = models.CharField(max_length=20) id = models.IntegerField(primary_key=True, editable=True) Region = models.ForeignKey( Region, on_delete=models.CASCADE, related_name="groups", null=True, blank=True) def __str__(self): return self.GroupName class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True, editable=False) username = models.CharField( max_length=20, null=True, blank=True, unique=True) email = models.EmailField(_('email address'), unique=True) GroupName = models.ForeignKey( Group, on_delete=models.CASCADE, related_name="groupUser", null=True, blank=True) RegionName = models.ForeignKey( Region, on_delete=models.CASCADE, related_name="regionUser", null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField( auto_now_add=True, null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'GroupName','RegionName', ] def __str__(self): return self.username -
Is there something wrong with the installation?
After running the Django server, I created a file 'exo2' importing "ex01" and "exo1". When dragging and dropping the "ex01" into the .config on the left explorer, the message in the image below never pops up: poto>>"Python extensions want to make refactoring changes with this file move." I wantenter image description here this message to appear. Is there something wrong with the installation?