Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django imagefield display image and have browse button for the form
In my django app, I have been able to include image for an imagefield form, however there is no browse button to upload a new image. How do I include this browse button to upload a new image ? Currently it looks like this: https://imgur.com/a/Qu4JE And here is my form code: class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""<img src="$link" height=50 width=50 />""") logging.debug("value %s" % value.url) return mark_safe(html.substitute(link=value.url)) class EmployeeFaceImageUploadForm(forms.ModelForm): face_image = forms.ImageField(widget=PictureWidget) class Meta: model = Employee fields = ("face_image",) -
Django - How to pass value after submit when editing form?
I'm trying to pass a data to my form when it's being edited I have the following code: form = senalesEipForm(request.POST or None, instance=eip,prefix='form') new_data_2 = None form2 = reglasForm(request.POST or None, instance=regla,prefix='form3') form3 = patronInicioForm(request.POST or None,initial={'minutos':minuto_inicio,'hora':hora_inicio,'dia_mes':dia_mes_inicio,'mes':mes_inicio,'semana':semana_inicio}, prefix="form3") form4 = patronFinalForm(request.POST or None,initial={'minutos':minuto_fin,'hora':hora_fin,'dia_mes':dia_mes_fin,'mes':mes_fin,'semana':semana_fin}, prefix="form4") print form2 if form.is_valid() and form2.is_valid() and form3.is_valid() and form4.is_valid(): nuevo_minuto_inicio = form3.cleaned_data['minutos'] nuevo_hora_inicio = form3.cleaned_data['hora'] nuevo_dia_mes_inicio = form3.cleaned_data['dia_mes'] nuevo_mes_inicio = form3.cleaned_data['mes'] nuevo_semana_inicio = form3.cleaned_data['semana'] new_data_1 = '0' + '' + nuevo_minuto_inicio + '' + nuevo_hora_inicio + '' + nuevo_dia_mes_inicio + '' + nuevo_mes_inicio + '' + nuevo_semana_inicio nuevo_minuto_fin = form4.cleaned_data['minutos'] nuevo_hora_fin = form4.cleaned_data['hora'] nuevo_dia_mes_fin = form4.cleaned_data['dia_mes'] nuevo_mes_fin = form4.cleaned_data['mes'] nuevo_semana_fin = form4.cleaned_data['semana'] new_data_2 = '0' + '' + nuevo_minuto_fin + '' + nuevo_hora_fin + '' + nuevo_dia_mes_fin + '' + nuevo_mes_fin + '' + nuevo_semana_fin form.save(commit=False) form2.save(commit=False) pfin = new_data_2 print pfin form2.save() form.save() In this case, basically what I want is get the data from form3 and form4 and pass it to form2, I tried with initial but it's not working when I use instance I tried with JavaScript but not working.... What can I do to solve this? for example, what's in pfin I need it in form3.properties properties is a field … -
django rest framework hyperlinkrelatedfield for one table using its primary key
I have a table called 'users' and 'location'. Users table has a foreign key that relates to location table. I have a users serializer to get the JSON. What would I do to get the hyperlinks for the users table using its primary key? In django rest framework documentation, I couldn't find a solution. I tried using hyperlinkrelatedfield. But still I couldn't achieve this. Can someone help me in finding the solution? I need the URL like 127.0.0.1:8000/users{userid}. It should give the JSON of the user whose userid is specified in the URL -
split data and save values using django rest framework
I have models- class Web2Types(models.Model): name = models.CharField(max_length=200, unique=True) status = models.IntegerField(default=0) class Web2Domains(models.Model): domain = models.CharField(max_length=255, unique=True) web2type = models.ForeignKey(Web2Types) Now I have a string containing commas, I want that string first split by comma then all values of that list will save into Web2Domains model. I tried some methods in serializer.py but got confused. -
Javascript arrays and updating <ul><li></li></ul> elements with a loop?
I'm struggling with this one a little. I'm a junior python developer by trade and I have been asked to build a website. Naturally I said yes and chose Django. Regardless, I'm having a little issue building a calendar widget. I'm using AJAX to pass the request back to the view, and update certain elements based on whether the user is requesting the previous/next month of days. function getPreviousMonth( event ) { $.ajax({ type: "GET", dataType: "json", url: "{% url 'events' %}", data: { 'month': previousMonth, 'year': previousYear } }) .done(function(response) { console.log(response); nextMonth = response.next_month; nextYear = response.next_year; previousMonth = response.previous_month; previousYear = response.previous_year; currentMonth = response.current_month; currentYear = response.current_year; $('#currentMonth').text(currentMonth); $('#currentYear').text(currentYear); }); }; This all seems to be working well. In the response object I have an array of lists (I think, certainly correct me if I am wrong). On the template side I am using Django to setup the calendar from an array of days arrays: {% for week in weeks %} <ul class="days"> {% for day in week %} {% if day == 0 %} <li></li> {% else %} <li>{{ day }}</li> {% endif %} {% endfor %} </ul> {% endfor %} All looks nice (and … -
store infinity in postgres json via django
I have a list of tuples like below - [(float.inf, 1.0), (270, 0.9002), (0, 0.0)] I am looking for a simple serializer/deserializer that helps me store this tuple in a jsonb field in PostgreSQL. I tried using JSONEncoder().encode(a_math_function) but didn't help. I am facing the following error while attempting to store the above list in jsonb field - django.db.utils.DataError: invalid input syntax for type json LINE 1: ...", "a_math_function", "last_updated") VALUES (1, '[[Infinit... DETAIL: Token "Infinity" is invalid. Note: the field a_math_function is of type JSONField() -
Is it good way to send POST request using jQuery in Django?
form.py class UserCreateForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) class Meta: model = User fields = ['username'] views.py def test(request): if request.method == "POST": return redirect('/test_done/') html CODE : <form class="form-horizontal" method="post" action="."> {% csrf_token %} <div class="form-group"> <label class="control-label" for="id_username">Username(ID)</label> <div>{{ form.username }}</div> </div> <div class="form-group"> <div> <button class="btn btn-default" id="btn_test" type="submit">Create</button> </div> </div> </form> On that code, If I click Createbutton on <button class="btn btn-default" type="submit">Create</button>, on views.py, returned redirect to some uri. But I want do this process by only using jQuery or javascript without html post. Like this. $('#btn_test').click(function () { #alert('It works and you will be gone to redirect uri from views.py') #sleep 3-5sec #do post send }); How can I do this? EDIT: I thought using ajax post call, But wonder there any good way not being ajax. -
How to parse a string list query param in DRF serializers?
I'm building a REST API to handle user requests in the following form: localhost:8000/search/?categories=<category1>,<category2>&parts=<id1>,<id2> Where , is supposed to be the delimiter for the parser. My view processes the request and passes the query params to the serializer, but I just cannot get the raw strings parsed to a list of strings. My attempt so far: class StringListField(serializers.ListField): child = serializers.CharField() class LookupPartsSerializer(serializers.Serializer): categories = StringListField() parts = StringListField() class LookupParts(APIView): def get(self, request, format=None): serializer = LookupPartsSerializer(data=request.query_params) return Response(request.query_params) My desired output is like: { "categories": [ "<category1>", "<category2>" ], "parts": [ "<id1>", "<id2>" ] } But now I'm getting: { "categories": [ "<category1>,<category2>" ], "parts": [ "<id1>,<id2>" ] } So basically I'm looking for an option to pass a delimiter argument to the StringListField or add some custom parsing method. NOTE: I'm aware, that if I change the query pattern from ?categories=<category1>,<category2>... to ?categories=<category1>&categories=<category2>... then I'd get the desired results, but I'd like to stick to my original approach. -
Page not found in Django (404)
I have a little problem with Django 2.0. In my case the debugger responded me this message: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in bajkowo.urls, Django tried these URL patterns, in this order: admin/ bajki/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I'v check the views and urls but i can;t find the bug or typo. Could anyone to check my code? urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('bajki/', include('bajki.urls')), ] bajki/urls.py from django.urls import path from . import views urlpatterns = [ path('bajki/',views.lista_bajek, name='lista_bajek'), ] bajki/views.py from django.shortcuts import render def lista_bajek(request): return render(request, 'bajki/lista_bajek.html', {}) The def lista_bajek should responde me a blank webiste, but responding me a error code 404. Of course I created the bajki/templates/bajki/lista_bajek.html -
No module named 'encodings' error while starting uwsgi
I referred to following three links to upgrade python to 3.6.3 version and create virtual environment and then tried to server django via nginx/uwsgi. However, i'm struggling with the error saying "no module named encodings". If I used below command then the django can be accessed. However, If run over the config file it will raise error saying "no module named encodings". "uwsgi --http :8080 --home /home/testuser1/myproject --chdir /home/testuser1/myprojecttss -w myprojecttss.wsgi " https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-centos-7#setting-up-the-uwsgi-application-server https://www.digitalocean.com/community/tutorials/how-to-set-up-uwsgi-and-nginx-to-serve-python-apps-on-centos-7#set-up-an-app-directory-and-a-virtualenv Error Log: (myproject) [test@VM_134_114_centos ~]$ systemctl status uwsgi -l * uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: disabled) Active: active (running) since Sat 2018-01-20 20:29:47 CST; 9min ago Main PID: 11381 (uwsgi) Status: "The Emperor is governing 0 vassals" CGroup: /system.slice/uwsgi.service `-11381 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: uwsgi socket 0 bound to UNIX address /run/uwsgi/myprojecttss.sock fd 3 Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: uWSGI running as root, you can use --uid/--gid/--chroot options Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: setuid() to testuser1 Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Python version: 3.6.3 (default, Jan 17 2018, 14:02:51) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Set PythonHome to /home/testuser1/myproject Jan 20 20:38:16 VM_134_114_centos uwsgi[11381]: Fatal Python error: Py_Initialize: Unable to get … -
Django Social Auth error: "Missing required parameter: client_id" while trying to authenticate with Google Outh2
I have installed and configured social-auth-app-django and added an option to sign up with google in my login page. But whenever I click the link, I get this error -
Django - unhashable type: 'ReturnDict' error on invoking a view
I am trying to create an API but the serializer is failing . I am not able to figure out what is gone wrong . View : elif request.method == 'POST': data = { 'user':request.user,'skill_item':Skill.objects.get(pk=request.data.get('skill_id')) } serializer = UserSkillSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Serializer : class UserProfileSerializer(serializers.ModelSerializer): skill_item =SkillSerializer(read_only=True,many=True) class Meta: model = User fields = '__all__' def create(self, validated_data): user = User.objects.create(username=validated_data.get('username'),email=validated_data.get('email'),password=validated_data.get('password')) user.set_password(validated_data.get('password')) user.save() UserProfile.objects.create(user=user, user_skills=skill_item) return user class UserSkillSerializer(serializers.ModelSerializer): user = UserProfileSerializer(read_only=False) skill_item = SkillSerializer(read_only=False) class Meta: model = UserSkill fields= '__all__' Model : # This class will more or less map to a table in the database and defines skills at the application level class Skill (models.Model): # this defines a required name that cannot be more than 100 characters. skill_name = models.CharField(max_length=100,unique=True) class Meta: app_label = "wantedly_webapp" # This class will more or less map to a table in the database and defines the many to many relationship between user-skill, this is our intermediate model class UserSkill(models.Model): """ A Model for representing skill in user profile """ unique_together = (('user', 'skill_item'),) user = models.ForeignKey('UserProfile',on_delete=models.CASCADE,related_name='current_user_skills') skill_item = models.ForeignKey(Skill,on_delete=models.CASCADE) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.skill_item.skill_name) # … -
Postgtes a lot of request
I have Django, Python i call - ps -aux postgres 46214 2.4 0.4 252824 139052 ? Ss 15:24 0:07 postgres: postgres mydb [local] SELECT postgres 46216 1.7 0.4 252664 136680 ? Ss 15:24 0:04 postgres: postgres mydb [local] SELECT I have so many such lines (> 10). And very long communication to my database through the /admin page Kill the process does not work - it is restored after some time. As a result, I can not see the database because the request is very long and is terminated by timeout Can anybody help? Or can someone come across this? -
Followers not getting added
I am trying to add followers to my blogger database but unable to do so. I am getting 404 error( No blogger matches with the given query). views.py def follow(request,user_id): user=request.user print(user_id) userFollow=get_object_or_404(Blogger,id=user_id) if request.method=="POST": userFollow.follows.add(user) return redirect('winterblog:blogger_detail',user_id) models.py class Blogger(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) follows = models.ManyToManyField('self', related_name='following', symmetrical=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Blogger.objects.create(user=instance) Help would be appreciated. Thanks! -
Django user uploaded media files in development
I have image field in one of the my models in my project. That image is uploaded by users and working correctly in localhost. But, I can't get it work in production. I'm using heroku to deploy my project and here is my scripts: settings.py MEDIA_URL = "/media/" MEDIA_ROOT = "https://myapp.herokuapp.com/live-static/media-root" urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views import debug_toolbar from .views import signup, SignInView, ResetPasswordView, ConfirmPasswordResetView urlpatterns = [ url(r'^', include('music.urls', namespace='music')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^login/$', SignInView.as_view(), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^register/$', signup, name='register'), url(r'^password_reset/$', ResetPasswordView.as_view(), name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', ConfirmPasswordResetView.as_view(), name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py class Album(models.Model): owner = models.ForeignKey(User) title = models.CharField(max_length=127) artist = models.CharField(max_length=63) release_date = models.DateField() logo = models.ImageField(blank=True, upload_to='album_logos', default='album_logos/no-image.jpg') t_added = models.DateTimeField(auto_now_add=True) slug = models.SlugField(null=True, blank=True, max_length=63) Why images aren't uploaded and displayed in production? -
Django loaddata provide database fixture
I want to switch a site from using sqlite to postgres. Backed up the data into a json with python manage.py dumpdata > db.json then switched the database details in the settings file to postgres now when I try to load using python manage.py loaddata < db.json I get the error below. (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp$ python manage.py loaddata < db.json usage: manage.py loaddata [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] [--app APP_LABEL] [--ignorenonexistent] fixture [fixture ...] manage.py loaddata: error: No database fixture specified. Please provide the path of at least one fixture in the command line. -
python manage.py makemigrations no module named error
Thats the error after using command from title, Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\DELL\SrdW\lib\site-packages\django\core\management\__init__.py" , line 371, in execute_from_command_line utility.execute() File "C:\Users\DELL\SrdW\lib\site-packages\django\core\management\__init__.py" , line 347, in execute django.setup() File "C:\Users\DELL\SrdW\lib\site-packages\django\__init__.py", line 24, in se tup apps.populate(settings.INSTALLED_APPS) File "C:\Users\DELL\SrdW\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\DELL\SrdW\lib\site-packages\django\apps\config.py", line 116, i n create mod = import_module(mod_path) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\lib\importlib\__ init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.staticfilesblog' Thats mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' 'blog.apps.BlogConfig',] Also blog\models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title I set up virtual enviroment end creat project mysite than startapp blog and when i try to makemirgations this error … -
Referencing user object inside model method in Django
I have the following in my model: class Genre(models.Model): name = models.CharField(max_length=100) def my_latest_song(self): song = Song.objects.filter(genre_id=self.id, author_id=XXXXXXXXX).order_by('date') return song[0]; class Song(models.Model): name = models.CharField(max_length=100) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True) date = models.DateField() author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) So with the my_latest_song method I want to obtain for each genre what the latest song is for the user currently logged in. Note: I am already making sure that users MUST be logged in to see this, do not worry about this additional validation. The question is: how can I pass the user id of the user that is currently logged in onto this model method? Where the XXXXXXXXXX is listed I have tried: author_id=request.user.id author_id=user.id author=request.user author=user And many similar options. But I'm new to Django and just not sure about how to properly reference this. Nothing is working yet. -
Get same object in multi Querysets in Python Django
Hope you guys help me to Get same object in multi Querysets in Python. I use Django Framework I assumed that I have 2 Queryset: qrs1 = [1, 2, 3, 5, 9] and qrs2 = [1, 4, 2, 5] I want to print result with this queryset: [1, 2, 5] -
Error on git push : ! [remote rejected] master -> master (pre-receive hook declined) in heroku
I am trying to deploy my django app on heroku but i am getting this error : remote: Error: could not determine PostgreSQL version from '10.1' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-r9b1_s/psycopg2/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to bookmark. remote: To https://git.heroku.com/bookmark.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/bookmark.git' My requirements.txt : Django==1.11.6 gunicorn==19.7.1 Pillow==3.1.2 Markdown==2.6.9 whitenoise==3.3.1 psycopg2==2.6.1 Can someone guide me on this.Thanks -
how to create New user form in django Only those who have filled the my form, can enter my website
Hello i am new with Django an i want to create a New User Form an Only those who have filled the my form, can enter my website! My form required form fields First Name Last Nanme EmailId Mobile No Broker Address Field 1 Address Field 2 Address Field 3 City State PIN AdhaarCard PAN No Bank Account No Bank Name Branch -
Adding a Wiki Field in Django
I'm trying to add a Wiki Field to Django. I however have no experience with how to design it. I need to have a single Wiki Field for a single Product I only want users with certain reputation to directly edit the Wiki and others will be placed in moderation queue much like SO. My main concern is multiple items in moderation queue How do I store and handle and multiple editions while in moderation queue How do I setup a method for moderators to get old revisions if some one messes up? How do SO and SE handle multiple items in moderation queue? This is my current code. class ProductWiki(models.Model): product = models.OneToOneField('Product') approved_revision = models.OneToOneField('productWikiRevision') class ProdcutWikiRevision(models.Model): content = models.TextField() wiki = models.ForeignKey(ProductWiki) revision = models.PositiveIntegerField() author = models.ForeignKey('auth.User') summary = models.CharField(max_length=300, blank=True) added_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False, db_index=True) approved_by = models.ForeignKey(User, null=True, blank=True) approved_at = models.DateTimeField(null=True, blank=True) ip_address = models.GenericIPAddressField(max_length=45, default='0.0.0.0', db_index=True) user_agent = models.TextField() -
Django IntegrityError of this overriding save method
My Model class Worksite(models.Model): firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True, verbose_name="Şantiye Adı") My save method def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_unique_slug() os.mkdir(BASE_DIR+'/file/'+slugify(str(self.firm).replace('ı','i'))+'/'+self.slug) return super(Worksite, self).save(self, *args, **kwargs) My UpdateView def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_unique_slug() os.mkdir(BASE_DIR+'/file/'+slugify(str(self.firm).replace('ı','i'))+'/'+self.slug) return super(Worksite, self).save(self, *args, **kwargs) IntegrityError : (1062, "Duplicate entry '1' for key 'PRIMARY'") If the save method is deleted, the update process is successful. but this time the folder can not be created. so save method is necessary. but this error is annoying. where is the mistakes? Help pls. -
My serializer is returning index instead of the actual fields
I am new to Django and I have been trying to serialize my model object called MoviesCategories. class MoviesCategories(models.Model): name = models.CharField(max_length=120, null=False) def __str__(self): return self.name There is also a Movie model that is as follows class Movie(models.Model): name = models.CharField(max_length=120, null=False) thumbnail = models.CharField(max_length=120, null=False) source_url = models.CharField(max_length=500, null=False) duration = models.TimeField(default=timedelta(hours=2)) added_on = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING) def __str__(self): return self.name class Meta: ordering = ('added_on',) My MoviesCategoriesSerializer looks like this class MoviesCategoriesSerializer(serializers.ModelSerializer): class Meta: model = MoviesCategories fields = ('name', 'movies') What I am getting from this serializer when I do MoviesCategoriesSerializer(MoviesCategories.objects.first()).data is {'movies': [1, 2], 'name': 'Animations'} I expect to get the fields of the movies too. I have created a MovieSerializer class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('name', 'thumbnail', 'source_url', 'duration') But I have no Idea on how to link the two such that MoviesCategoriesSerializer(MoviesCategories.objects.first()).data returns me all movies in the first category -
Model not inheriting User data
So I am working with built-in Django login forms and I want my blogger model to inherit all the users created using the form but it is not showing up in the blogger model. Models class Blogger(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) follows = models.ManyToManyField('self', related_name='following', symmetrical=False) def __str__(self): return self.user.username View for the sign up def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/blog') else: form = SignUpForm() return render(request, 'winterblog/signup.html', {'form': form}) Django form used def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/blog') else: form = SignUpForm() return render(request, 'winterblog/signup.html', {'form': form}) Thanks a lot!