Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check fields/fieldsets/exclude attributes of class CustomUserAdmin error in admin
I am getting this error even though I have already removed and migrated again. Initially, I added as extra boolean field is_vehicle_owner after Abstracting a Usermodel and then it was removed later. But i get this error. Any help will be appreciated. FieldError at /admin/accounts/customuser/1/change/ Unknown field(s) (is_vehicle_owner) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://127.0.0.1:8000/admin/accounts/customuser/1/change/ Django Version: 3.1.4 Exception Type: FieldError Exception Value: Unknown field(s) (is_vehicle_owner) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Exception Location: C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py, line 711, in get_form Python Executable: C:\Users\DELL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['E:\Django\projects\carpool', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Thu, 18 Mar 2021 18:28:58 +0000 Traceback Switch to copy-and-paste view C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py, line 709, in get_form return modelform_factory(self.model, **defaults) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py, line 555, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py, line 268, in new raise FieldError(message) … ▶ Local vars During handling of the above exception (Unknown field(s) (is_vehicle_owner) specified for CustomUser), another exception occurred: C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py, line 614, in wrapper return … -
Adapter to handle requests for APIs that exists on another server
So this is the scenario: I have a server(say SERVER A), that has the following rest APIs /questionnaire/{questionnaire_id} /questionnaire/ /questionnaire/question/{question_id} questionnaire/question/ Now I have a second server(say SERVER B), that has some other APIs. Now SERVER B has a frontend(say FRONTEND B), that access both backend SERVER A and SERVER B Requirements: I do not want to directly access SERVER A from FRONTEND B, instead, I want to access backend SERVER B that will authenticate the request coming from FRONTEND B and in turn, hit backend SERVER A to get the response. Now I do not want to write a duplicate APIs on SERVER B to hit the the corresponding APIs on SERVER A. What I want is an adapter that handles all API request whose URL starts with "/questionnaire/" and authenticate the user or request and then hit the SERVER A, receive the data and return it to FRONTEND B. So is there any tool inbuilt in Django for this or if there is any workaround to make it possible? Thanks in advance. -
Django: Trouble filtering my Artist model to show objects from the request user
So I have a model in a different app that records a user's 5 favorite artists. The model is uses the user as a foreign key through my own custom userprofile model. So I want to display the list of favourite artists linked to the request profile when I log in and I want to display it. But im having trouble filtering it because I keep getting an error saying the request user needs to be a userprofile instance. Heres my music model from django.db import models from accounts.models import UserProfile # Create your models here. class Artist(models.Model): artist_name = models.CharField(default='', max_length=200) artist_name2 = models.CharField(default='', max_length=200) artist_name3 = models.CharField(default='', max_length=200) artist_name4 = models.CharField(default='', max_length=200) artist_name5 = models.CharField(default='', max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) as_pro = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='artist') def __str__(self): return f"{self.as_pro}-{'Artist List'}" and heres my profile view in the accounts app def profile(request): userprofile = UserProfile.objects.get(user=request.user) obj = Artist.objects.filter(as_pro=request.user) context = { 'userprofile': UserProfile, 'obj' : obj, } return render(request, 'accounts/profile.html', context) heres also my profile template where I want to display it but like I said I'm finding it hard to crack why I cant display a simple list. </div> <p>{{ obj.artist_name }}</p> <p>{{ obj.artist_name2 }}</p> <p>{{ … -
Javascript file calls another jsfile from the wrong directory
I am currently using OTree, which is a Python framework that allows to run experiment online, using Django for the web-side if I am not mistaken. Basically, it is really easy to implement things in it, except if one wants to modify a bit the HTML page, for instance, by incorporating live objects (such as video games, etc...) on the HTML page. That is my case. I am trying to implement a UNO game in my experiment. Since I virtually know next to nothing to Javascript, I am using a UNO game built in Construct 3 for all the coding. If I understood it right, to call script in Django, one needs to write as follows: <script src="{% static 'my_app/script.js' %}" alt="My script">. So this is what I did. My code for the HTML page can be found below: {% extends "global/Page.html" %} {% load otree %} {% block content %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> <meta name="generator" content="Construct 3"> <meta name="description" content="UNO"> <link rel="manifest" href="{{ static "HTML_Uno/appmanifest.json" }}"> <link rel="apple-touch-icon" href="{{ static "HTML_Uno/icons/icon-128.png" }}"> <link rel="apple-touch-icon" href="{{ static "HTML_Uno/icons/icon-256.png" }}"> <link rel="apple-touch-icon" href="{{ static "HTML_Uno/icons/icon-512.png" }}"> <link rel="icon" type="image/png" href="{{ static "HTML_Uno/icons/icon-512.png" }}"> <link rel="stylesheet" … -
Django Reverse for 'edit' with no arguments not found
I'm new to Django. I just laid out a new project to teach myself how routing works. I have a template that works like a 'detail view' to show information about an item in my database, and that template includes a button that should allow you to 'edit' this item. Clicking the button gives me: NoReverseMatch at /4/edit Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$'] Here is the template. I am trying to call the dashboard app's 'edit' view and pass the current article's ID in as an argument. {% extends 'dashboard/components/layout.html' %} {% block content %} <div id='detail-container'> <div class='detail-sidebar'> <a href='{% url 'dashboard:edit' id=article.id %}'>Edit</a> </div> <div class='article detail-article'> <h1 class='article-title'>{{ article.article_title }}</h1> <p class='article-body'>{{ article.article_body }}</p> </div> </div> {% endblock %} Here is my urls.py file. To my understanding this should match the pattern named 'edit' from django.urls import path from . import views app_name = 'dashboard' urlpatterns = [ path('', views.index, name='index'), path('new/', views.NewPost, name='new'), path('<id>/', views.ArticleDetailView, name='article'), path('<id>/edit', views.EditArticleView, name='edit'), ] And finally, here is the view that the edit path should call. I'm aware that the logic is probably not right when it comes to rendering a form with … -
Is it possible to use multiple slash Django URL as one variable in Django?
I'm new to Django. I'm using Django for 5months. I'm now creating a project. In that project, I've links like this: https://localhost:8000/example.com/example/path/ In the URL the example.com/example/path/ can be dynamically long as like this example.com or example.com/asset/css/style.css or domain.com/core/content/auth/assets/js/vendor/jquery.js I've used <str:domainurl> But is not working. As it has multiple forward slashes. And the forward slashes URL length generated while web scrapping. So is there is a way to use the full URL as one variable? -
Query all connected ancestors or children in a self relation table
Suppose I have a table 'prlines' with a self relation on adjacent records: id | prev_id ------------ 1 | NULL 2 | NULL 3 | 1 4 | 2 5 | 3 6 | 5 I want to get all connected IDs (previous/next) of a certain record. For example: SELECT `prev_id` FROM `prlines` ... WHERE id = 5; Should produce this output: prev_id ------- 3 1 6 What I am doing currently is making a nasty while loop in Django that generates multiple queries to follow the relationship for each record. Any ideas to achieve this in a single mysql query? -
Modal not showing long messages, problem with javascript function arguments
I am facing a problem when I try to show message content in modal. I am trying to build a view which has a list of messages (table), and by clicking a message title, the user would be able to see the message content in modal view. It works for short messages, but for some reason nothing happens with longer messages. I think the issue is with my function 'displayMessage' to which I pass two elements: message title and message content. Here is the snippet from the table view: <table id="msg-table" class="table table-striped"> <thead> <tr> <th id="message-date" scope="col">Date</th> <th id="message-content" scope="col">Message</th> </tr> </thead> <tbody> {% for message in messages %} <tr> <td>{{ message.date }}</td> <td onclick="displayMessage('{{message.content,}}', '{{ message.title }}')"> {{ message.title }} </tr> <div id="myModal" class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="message-title"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p id="message-content"></p> </div> </div> </div> </div> {% endfor %} </tbody> </table> And this is the function for displaying the Modal: function displayMessage(message, title) { var modal = document.getElementById("myModal"); var close = document.getElementsByClassName("close")[0]; // Change the modal text and display document.getElementById("message-title").innerHTML = title; document.getElementById("message-content").innerHTML = message; modal.style.display = "block"; close.onclick = function … -
dictionary update sequence element #0 has length 0; 2 is required
I was working on my project and everthing worked fine. I tried to open the server in another browser and this error appeared. I stopped the project and start it agian and it stop working on my main browser aswell. I dont have any idea what this cause it. Internal Server Error: /account/login/ Traceback (most recent call last): File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "A:\repos\topanime\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "A:\repos\topanime\venv\lib\site-packages\django\template\base.py", line 168, in render with context.bind_template(self): File "C:\Python\Python391\lib\contextlib.py", line 117, in __enter__ return next(self.gen) File "A:\repos\topanime\venv\lib\site-packages\django\template\context.py", line 244, in bind_template updates.update(processor(self.request)) ValueError: dictionary update sequence element #0 has length 0; 2 is required [18/Mar/2021 18:52:01] "GET /account/login/ HTTP/1.1" 500 86400 If there is any other information that you need tell me. -
User Frontend Selection That Loads Images From Database With Django
I have a drop down bar with a multi selection tool. A user picks from titles of graphs stored in a model for the graphs they want to display. How can I use those selections to display these graphs? I am using Ajax to send the data to the backend. From that data I created a new context_dict full of the model objects we want displayed. I want to either display in the same template or link to another template that can use this context dict. I do not know the best way to do this. Here is some of my code below. Models: from django.db import models class ChartPrac(models.Model): title = models.CharField(max_length=256) chart = models.ImageField() def __str__(self): return self.title Views: def querier(request): if request.method == 'POST': options_arr = request.POST.get('optionsArr') options = options_arr.split(':') options = options[1:] print(options) context_arr = [] context_graphs = {} i = 0 for elements in options: charts_to_display = ChartPrac.objects.get(title=elements) context_arr.append(charts_to_display) i += 1 context_graphs['titles'] = context_arr return HttpResponse(options_arr) else: graph_titles = ChartPrac.objects.all() context_dict = {'titles': graph_titles} print(context_dict) print(type(context_dict['titles'])) return render(request, 'graph_querier/base.html', context=context_dict) Urls: from django.urls import path from graph_querier import views app_name = 'graph_querier' urlpatterns = [ path('', views.index, name='index'), path('querier/', views.querier, name='querier'), # path('graph/', views.graph, … -
Django REST API auth token ERR_CONNECTION_REFUSE
I have my django project with angular front-end running on a server, when I try to visit my website with the server it's working fine, but trying to connect remotely to the website using my computer I cant authenticate. Note that i can visit public pages fine but when I'm trying to loggin i got ERR_CONNECTION_REFUSE . PS : I'm running django with cmd : python manage.py runserver 0.0.0.0:8000/ and using my computer I can connect to the django backend office all working fine but connecting from my website ( front end ) I got the error . In my settings.py : ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True -
Get reoccurring date from rrule Django / Python
I make two requests, one to get a collection of events that have valid dates, and then an additional function to find dates within the returned valid events: def valid_data(matches, start_date, end_date): for prices in matches: if prices.rule: until = ( prices.rule.until if prices.rule.until and prices.rule.until <= end_date else end_date) dtstart = ( prices.start_date if prices.start_date >= start_date else start_date) prices_dates = price_rrule( frequency=prices.rule.frequency, interval=prices.rule.interval, byweekday=tuple(prices.rule.byweekday) or None, bymonthday=tuple(prices.rule.bymonthday) or None, until=until, dtstart=dtstart) if start_date in price_dates: return prices The response I get back in other areas of my code is fine, it'll return the event (prices) within the start - end dates, those that are occurrences inside these dates, don't come back with an actual date - how could I modify the above so I can attach dates to reoccurrence and maybe return this as a list as I only get the one item back. -
I want to make a progress bar ,but don't use celery lib. so I writ the code, it works, but have some problem
I use a variable like a global variable. I think it a bad idea when multiple users run at the same time, the progress bar is messy. who can help me improve this code, please? num_progress = 0 # This is bad idea def show_progress_page(request): # return JsonResponse(num_progress, safe=False) return render(request, 'progress.html') def process_data(request): global num_progress for i in range(12345666): # ... Some thing in progress num_progress = int(i * 100 / 12345666) # print 'num_progress=' + str(num_progress) res = num_progress # print 'i='+str(i) # print 'res----='+str(res) return JsonResponse(res, safe=False) def show_progress(request): print('show_progress----------' + str(num_progress)) return JsonResponse(num_progress, safe=False) -
How can i show friends of users in ManyToManyField
I am building a BlogApp and I am trying to access only friends in ManyToManyField. BUT it is not working for me. What i am trying to do I am trying to show only list of friends in ManyToManyField. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField("Profile",blank=True) class Video(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) add_users = models.ManyToManyField(Profile,related_name='taguser') What have i tried I also did ManyToManyField('friends)` but it didn't worked for me. I don't know what to do. Any help would be Appreiated. Thank You in Advance -
django filter two ManyToManyField equal
class VideoUserModel(models.Model): user = models.ManyToManyField(get_user_model()) viewlist = models.ManyToManyField(get_user_model(), related_name='view_list', blank=True, null=True) I want to get the queryset of user list equal viewlist. How to do this? VideoUserModel.objects.all().filter(user=**viewlist**) -
How to use selected value by a user?
I want to allow user to pick a dog food brand from a database. When he selects it, I want to use his submitted value and return him how many calories it has. I am stuck and don't know what to do next. models.py class DogFoodDry(models.Model): brand = models.CharField(max_length=25) name = models.CharField(max_length=100) calories_per_kg = models.IntegerField(null=False) forms.py class DogFoodDryForm(forms.Form): brand = forms.CharField(max_length=25) name = forms.CharField(max_length=100) calories_per_kg = forms.IntegerField() views.py def get(self, request, id): form = DogFoodDryForm() dog = Dog.objects.get(id=id) foods = DogFoodDry.objects.all() context = {'dog':dog, 'foods':foods} return render(request, 'dog_info.html', context) dog_info.html <form method="GET"> <select> <option value="">--------</option> {%for food in foods %} <option value="">{{food.brand}} | {{food.name}}</option> {%endfor%} </select> <input type="submit" value="Select"> </form> -
Q model and or query giving incorrect result
I want perform below SQL query using Q models SELECT * FROM motor_vehicle_collision.collision_data_collisiondetails where (numberOfCyclistInjured > 0 or numberOfCyclistKilled > 0) and (longitude != '' and latitude != ''); for that I have written below query query = Q(numberOfCyclistInjured__gt=0) query.add(Q(numberOfCyclistKilled__gt=0), Q.OR) query.add(~Q(latitude=''), Q.AND) query.add(~Q(longitude=''), Q.AND) but still I am getting data having latitude/longitude empty, how should I rectify it? -
ValueError for default value of integerfield in django production
In the production(server) on the command migrate I am getting an error ValueError: Field 'price' expected a number but got ''. But the problem is that the default value of that integer field is not "" its 0 a number. class Product(models.Model): ZKSOKS = [ ('zks', 'Зкс'), ('oks', 'Окс'), ] title = models.CharField(max_length=250, unique=True) price = models.IntegerField(default=0) sort = models.CharField(max_length=250, null=True, blank=True) uraj = models.CharField(max_length=250, null=True, blank=True) age = models.IntegerField(null=True, blank=True) zks = models.CharField(max_length=20, choices=ZKSOKS, null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='product_img') slug = models.SlugField(unique=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = defaultfilters.slugify(unidecode(self.title)) super().save(*args, **kwargs) -
Django REST Framework always return Bad Request but it does log me into the Django admin
I'm using Django 2.1.5 and djangorestframework 3.9.2. The app is deployed using docker. The application works in local but not in production, I have set up ALLOWED_HOSTS = ['*'] and DEBUG = False. So, every request to log in using REST Framework API returns 400 BAD REQUEST (credentials are OK), but if I go to the Django admin, it shows that I successfully logged in (this differs from the API response). And as I said before in local environment the app behaves as expected. Note: I didn't create the initial app, nor I created the docker config files. But I have checked and it seems to be something going on with Django. -
Django query to keep perticular item at first and then apply order_by to rest of the items
Let say we have an Article model. class Article(models.Model): id = int name = char i want to get all the articles but the article with name = "stackoverflow" should be the first item in queryset and apply order_by to rest of the items. eg .order_by("name"). what i've achieved so far is queryset = Article.objects.all().order_by("name") stackoverflow = queryset.get(name="stackoverflow") query = queryset.exclude(name="stackoverflow") articles = [] articles.extend(stackoverflow) articles.extend(query) But this hits the database atleast 5 times. Can we do this in a better way? -
create an appointment app with registered and non registered user in Django
I want to create an appointment app with Django with the following condition: if the user is a patient it will show him a template like this if the user is a doctor or reception it will give him a choice the first the patient is register and show him a template like this : the patient is not registered, it will show him a template like this : this is my fomrs.py class AppointementForm(ModelForm): class meta: model = Appointement_P fields = ('doctor', 'date', 'start_time', 'end_time') class AppointementForm_2(ModelForm): class meta: model = Appointement_P fields = ('patient', 'doctor', 'date', 'start_time', 'end_time') class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) class ProfileUpdateForm(forms.ModelForm): gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False, widget=forms.RadioSelect) class Meta: model = Profile fields = ('date_of_birth', 'gender', 'phone_number', 'blood_group', 'address', 'photo') and models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) phone_number = PhoneNumberField(blank=True) blood_group = models.CharField(choices=BLOOD_GROUPS, max_length=3, … -
How can I constrain a ManyToMany to only associate objects with the same parent universe in a declarative way?
I have two django models that I need to link together many-to-many, but I only want to allow linking between two models if they are "compatible", having the same value for their parent universe. As a toy code example: from django.db import models class Universe(models.Model): pass class Foo(models.Model): universe = models.ForeignKey(Universe, on_delete=models.CASCADE) bars = models.ManyToManyField('Bar', related_name='foos', through='FooBarLinkage') class Bar(models.Model): universe = models.ForeignKey(Universe, on_delete=models.CASCADE) foos = models.ManyToManyField('Foo', related_name='bars', through='FooBarLinkage') class FooBarLinkage(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) bar = models.ForeignKey(Bar, on_delete=models.CASCADE) (Note that I'm not trying to use the universes as some kind of security boundary; this is just an attempt to capture and validate an additional detail about the problem domain I'm using these objects to describe.) I know how I'd add this constraint non-portably using SQL, and I could add python validation code that checks this on save, but that requires re-expressing this constraint several times and writing code to handle implementation differences between different databases. How can I instead express this constraint declaratively with the Django ORM? Note that in addition to having the database constraint and python validation automatically generated, an ideal solution would also allow me to implement browser-side javascript admin panel widgets for the foo and bar … -
How to store VideoIntelligence Speech Transcription data in MySQL for best text searching strategy
The following Django/Python implementation provides the results from VideoIntelligence for speech transcription data for a video stored in Google Cloud Storage : video_client = videointelligence.VideoIntelligenceServiceClient() features = [enums.Feature.SPEECH_TRANSCRIPTION] config = videointelligence.types.SpeechTranscriptionConfig( language_code = "en-GB", enable_automatic_punctuation=True, ) context = videointelligence.types.VideoContext( segments=None, speech_transcription_config=config, ) operation = video_client.annotate_video(gs_video_path, features=features, context) Below is the sample output from that operation : [alternatives { transcript: "Word1 Word2 Word3 Word4 Word5 Word6 Word7 Word8 Word9 Word10" confidence: 0.9206268787384033 words { start_time { } end_time { seconds: 2 } word: "Word1" } words { start_time { seconds: 2 } end_time { seconds: 2 nanos: 200000000 } word: "Word2" } words { start_time { seconds: 2 nanos: 200000000 } end_time { seconds: 2 nanos: 300000000 } word: "word3" } And so on .... How should I store them on my PostGreSQL database for best access strategy to answer search operations such as : Find Word1 Find Word2 Word3 Find Word3 Word4 Word5 Find Word7 Word8 Word9 Word10 Find Word8 Word10 Which will correspondingly return the timestamp of Word1, Word2, Word3 & Word7, None. Should I store all transcript as a single entity and timestamps for words seperately ? Should I store all words separately and in the case of … -
creating user-profile using DRF
i want to creating an api for user registration & user-profile using drf, i'm using my custom user model and also created profile model but i'm getting a TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f8d6a2a7220> error below is my code snippet #profile-model class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) school_name = models.CharField(max_length=255) address = models.TextField() badge = models.ImageField(upload_to='assets/badge', blank=True, null=True) school_type = models.CharField(max_length=50, choices=Type) gender = models.CharField(max_length=20, choices=Gender) level = models.CharField(max_length=40, choices=Level) state = models.CharField(max_length=100) date_established = models.DateTimeField(blank=True, null=True) curriculum = models.CharField(max_length= 255) ###profile-serializer class schoolProfileSerializer(serializers.ModelSerializer): parser_classes = (MultiPartParser, FormParser, ) id = serializers.IntegerField(source='pk', read_only=True) email = serializers.CharField(source='user.email', read_only=True) username = serializers.CharField(source='user.username', read_only=True) user = serializers.CharField(source='user.username', read_only=True) badge = Base64Imagefield(max_length=None, use_url=True) date_established = serializers.DateField(format=None,input_formats=None) class Meta: model = Profile fields = ( 'email', 'id', 'username', 'school_name', 'address', 'badge', 'gender', 'level', 'website', 'clubs', 'school_phone_number', 'school_type' ) def create(self, validated_data, instance=None): if 'user' in validated_data: user = validated_data.pop('user') else: user = CustomUser.objects.create(**validated_data) profile = Profile.objects.update_or_create(user=user, **validated_data) return profile ##profile-apiView class CreateProfileView(generics.CreateAPIView): parser_classes = (MultiPartParser,) serializer_class = schoolProfileSerializer queryset = Profile.objects.all() permission_classes = [permissions.AllowAny] def perform_create(self, serializer): serializer.save(user=self.request.user) ###user-registration apiView class RegistrationAPIView(APIView): permission_classes = [AllowAny] serializer_class = RegistrationSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response( … -
why im getting thsi adsense warning
whenever I'm inspecting my Django websites this warning shows up why I'm getting this warning on my website? what does it mean? show_ads_impl_fy2019.js:343 Non-ASCII characters in origin. (anonymous) @ show_ads_impl_fy2019.js:343