Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to call the next db if I press the button in the Django
my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Macro # Create your views here. def cmacroMacro(request): macro_data = Macro.objects.get(pk=1) context = {'macro_data':macro_data} return render(request, 'macro_pjt/registerMacro.html', context) models.py class Macro(models.Model): tit = models.CharField(max_length=50) pro = models.CharField(max_length=100) pri = models.CharField(max_length=40) pro_i = models.CharField(max_length=1000) re = models.CharField(max_length=10000) link = models.CharField(max_length=500) def __str__(self): return self.pro html <body> <section> <div>b_id / b_pw</div> <textarea cols="30" id="b_id" placeholder="아이디"></textarea> <textarea cols="30" id="b_pw" placeholder="비밀번호"></textarea> <div>title</div> <textarea cols="70" id="title_1" placeholder="제목">{{ macro_data.tit }}</textarea> <div>product</div> <textarea cols="70" id="product" placeholder="상품명">{{ macro_data.pro }}</textarea> <div>price</div> <textarea cols="70" id="price" placeholder="상품가격">{{ macro_data.pri }}</textarea> <div>product_information</div> <textarea cols="70" id="product_information" placeholder="상품정보">{{ macro_data.pro_i }}</textarea> <div>review</div> <textarea cols="70" id="review" placeholder="상품평">{{ macro_data.re }}</textarea> <div>link</div> <textarea cols="70" id="link" placeholder="쿠팡링크">{{ macro_data.link }}</textarea> </section> <div> <div>img1</div> <div>img2</div> <div>img3</div> </div> <button>next page</button> </body> The first row db is in textarea for each item. If you press the next page button, I want to print out the second row db. What should I do? Thank you for your reply in advance. -
Where do I put the validator in Django?
I'm learning to use Django and would like to validate the email address in the form submission. This is my form code right now: from django.forms import ModelForm from django.core import validators from first_app.models import FormSubmission from django import forms class SignupForm(ModelForm): class Meta: model = FormSubmission fields ='__all__' def clean(self): all_clean_data = super().clean() email = all_clean_data['email'] vmail = all_clean_data['verify_email'] and my models code class FormSubmission(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) email = models.EmailField(unique= False) verify_email = models.EmailField(unique = False) text = models.CharField(max_length=250) #botcatcher = models.CharField(required=False, #widget = forms.HiddenInput, #validators=[validators.MaxLengthValidator(0)]) def __str__(self): return "%s %s"% (self.first_name, self.last_name) Should the validator go in the models or the forms file? Thanks! -
using {{ request.get_host }} in template
Template file that is located in one of the apps: {% extends 'base_well_surfer.html' %} {% block content %} <table class="table table-bordered table-hover"> <thead class="thead-dark"> <tr> <th>Options</th> </tr> </thead> <tbody> <tr><td><a href="http://{{ request.get_host }}">Back to home</a></td></tr> <tr><td><a href="{% url 'wellsurfer:search' %}">Dynamically search in Well Surfer Database</a></td></tr> </tbody> </table> {% endblock %} my goal is to have a link that takes me back to the homepage. Is there a more elegant way of creating the link other than hardcoding the "http://" in front of the "{{ request.get_host }}" in the template? Thanks -
How to apply Bootstrap4 form related classes to fields in Django (v3) UserCreationForm?
I'm building a a sign up form. The form is defined as follows: class UserSignUpForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'})) first_name = forms.CharField(max_length=30, required=False, help_text='Optional.',widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=30, required=False, help_text='Optional.',widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(max_length=100, help_text='Required',widget=forms.TextInput(attrs={'class': 'form-control', 'type':'email'})) class Meta: model = User fields = ('username', 'first_name', 'last_name','email', 'password1', 'password2') widgets = { 'password1': forms.TextInput(attrs={'class': 'form-control'}), 'password2': forms.TextInput(attrs={'class': 'form-control'}), } This is what signup.html looks like: <form method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="{{ field.auto_id }}"> {{ field.label_tag }} </label> {{ field }} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Sign up</button> </form> With the above setup, the attributes passed to password1 and password2 fields do not get applied when the form is rendered. -
How to do complex url formation in Django?
I'm looking to add locations to Django urls, particularly zip codes which are housed in a session variables, zip_code. How to create these urls ...../service_name/zip_code -
Heroku Django app not serving, crashing because ModuleNotFoundError:<app> (*not a requirements module*)?
So i have an existing Django project (called 'MLshowcase') i have built over the last several months. I am trying to deploy to Heroku for the first time, have followed all the steps and added all the files I think i need. After about 50 failures (requirements too big) i finally got the project to deploy! One note: i did have to disable collectstatic on heroku in order to deploy, otherwise it kept saying one of my static files "was not in the root 'static'". but it did deploy. However, going to the application (called 'iansworld' on heroku) just shows "application error, page could not be served". I have been fiddling with the settings and wsgi for a day now and still nothing. When i look into Herko logs, it appears it goes build-crash-build-crash-build-crash..etc with several of the logs saying: app[web.1]: ModuleNotFoundError: No module named 'iansworld' full github: here Procfile web: gunicorn iansworld.wsgi --log-file - requirements.txt conda==4.3.16 conda-build==2.1.5 decorator==4.4.1 django==3.0.3 django-heroku djangorestframework==3.9.3 django-crispy-forms==1.9.1 dj_database_url django-adminlte-3==0.1.6 gunicorn html5lib==1.0.1 joblib==0.14.1 json5==0.9.1 jsonschema==3.2.0 matplotlib==3.1.3 numpy==1.18.1 packaging==19.1 pandas==1.0.1 path==13.1.0 requests==2.22.0 scikit-learn==0.22.1 scipy==1.4.1 seaborn==0.10.0 tables==3.6.1 whitenoise settings.py import os import dj_database_url import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = … -
How to get model values passed to a base template in different apps?
I have a base.html template in my application called index. I has a model this template receive some data from my model called footer class footer(models.Model): credits = models.CharField(max_length=200, blank=True, default='') phone = models.CharField(max_length=25, blank=True, default='') email = models.CharField(max_length=25, blank=True, default='') address = models.CharField(max_length=25, blank=True, default='') country_city = models.CharField(max_length=25, blank=True, default='') In the same app, into the folder templates I have the template base.html which takes some values from my model footer <li> <a class="foot-in" href="mailto:{{footer.email}}">{{ footer.email }}</a> </li> <li> <p>{{ footer.phone }}</p> </li> When I run the url in the app called index, everything goes well, but when I use the same template in another app, the url doesn't show the information from the model. How can I make to make that the base.html template works well into the different apps of my website? I hope I had been clear in my problem. Thanks in advance for your help -
Django File Upload Save Delay
Django newbie here, sorry if this is a basic question. I am working on a video submission platform where users will upload video files. I tried to use Django Storages and storing the file in S3 directly. The problem with that is as I assume the file is being moved to the application server and then uploaded to S3. With large video files, the file save operation still keeps me on the page and that would be okay if I could get some kind of progress info on that and show it to the user. Here's a simplified code of what I have tried model.py from django.db import models class sampledb(models.Model): name= models.CharField(max_length=150,null=False) video=models.FileField(blank=True,null=True,upload_to='videos') forms.py from django import forms from .models import sampledb class submissionForm(forms.ModelForm): class Meta: model = sampledb fields = ['name','video'] views.py from django.shortcuts import render from .forms import submissionForm # Create your views here. def moviesubmit(request): form = submissionForm() if request.method == 'POST': form = submissionForm(request.POST, request.FILES) if form.is_valid(): form.save() print("\nS A V E D ") return render(request,'success.html') else : print(form.errors) return render(request, 'sample_forms.html', {'form': form}) I am using s3 storages backend, from django_storages Using Django Storages creates the problem, what is the ideal way to store … -
How to send ajax from Django App to another Django App?
I have 2 Django App, App1 run on 127.0.0.0:8001, and App2 run on 127.0.0.1:8002 . When I use below code in App 1 (from App 1 to own) that Work nice. <script> function hi(){ $.ajax({ data: { Hi:'Hi' }, type: 'POST', url: '/test' }) .done(function (data) { .....do somthing... } } </script> But when I use function hi2 for send to App2 (127.0.0.1:8002) as show as that get error 500 (In App 2). <script> function hi2(){ $.ajax({ data: { Hi:'Hi' }, type: 'POST', url: '127.0.0.1:8002/test' }) .done(function (data) { .....do somthing... } } </script> Error in App 2: <MultiValueDict: {}> Internal Server Error: /test Traceback (most recent call last): File "C:\Users\iii\AppData\Local\Programs\Python\Python36-32\lib\site-package s\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\iii\AppData\Local\Programs\Python\Python36-32\lib\site-package s\django\core\handlers\base.py", line 124, in _get_response raise ValueError( ValueError: The view test.views.test didn't return an HttpResponse object. It returned None instead. [19/May/2020 08:50:46] "OPTIONS /test HTTP/1.1" 500 54850 In this step Ajax send request with OPTIONS as shown as: -
why are static files from aws s3 not loading?
i have hosted my static files on Amazon bucket and configured them in settings but still they are not loading when i run the server and throwing the error as shown in the image errors -
betting game: Update points in Guess model after save Match model
I'm making my first app in Django it's a betting app where users can make a guess on a match and every time the match changes score (superuser changes score Match in Admin and saves) I want the score of all the guesses for that particular game to be updated. I was told to avoid signals so I was looking at overwriting the save() method in the Match model in order to initiate the calculation of the points in the Guess model but I'm stuck. Could someone take a look at my approache? models from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Status(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class Meta: verbose_name_plural = "Statuses" class Country(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Countries" class Match(models.Model): home_team = models.ForeignKey( Country, related_name='home_team_country', on_delete=models.CASCADE) away_team = models.ForeignKey( Country, related_name='away_team_country', on_delete=models.CASCADE) home_team_score = models.PositiveIntegerField(default=0) away_team_score = models.PositiveIntegerField(default=0) play_date = models.DateTimeField(default=None) status_code = models.ForeignKey( Status, on_delete=models.CASCADE, default=1) def save(self, *args, **kwargs): super().save(*args, **kwargs) # here I'm trying t execute the Guess points logic for guess in self.guess_set.all(): # if guess.home_team_score == match.home_team_score and guess.away_team_score == match.away_team_score: guess.score = 5 # rest of the if/else … -
(Django) How do I make this signup model and signupview?
I have been trying to emulate Instagram signup which takes either one of 'phone' or 'email'. The image attached shows what requirements are Below are the files for my 'account' Django app that I created: models.py from django.db import models class Account(models.Model): email = models.EmailField(max_length = 254) password = models.CharField(max_length=700) fullname = models.CharField(max_length=200) username = models.CharField(max_length=200) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'accounts' def __str__(self): return self.username + " " + self.fullname views.py import json import bcrypt import jwt from django.views import View from django.http import HttpResponse, JsonResponse from django.db.models import Q from .models import Account class SignUpView(View): def post(self, request): data = json.loads(request.body) try: if Account.objects.filter(email=data['email']).exists(): return JsonResponse({"message": "ALREADY EXIST"}, status=409) elif Account.objects.filter(email=data['phone']).exists(): return JsonResponse({"message": "ALREADY EXIST"}, status=409) elif Account.objects.filter(username=data['username']).exists(): return JsonResponse({"message": "ALREADY EXIST"}, status=409) hashed_pw = bcrypt.hashpw(data['password'].encode('utf-8'),bcrypt.gensalt()).decode() Account.objects.create( email = data['email'], password = hashed_pw, fullname = data['fullname'], username = data['username'], phone = data['phone'], ) return JsonResponse({"message": "SUCCESS"}, status=200) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=400) Since the user put in either phone number or email, how do I make django to distinguish between the phone and email and put it in the correct model? -
Template won't render URL tag, says values are empty but renders those same values in a different way
I am attempting to create a news feed that includes articles and photo albums. However, I get an error any time Django tries to create a URL to the article page. In short, this works: <li class="card article category"> {{ article.slug }} {{ article.id }} <h5 class="h5"><a href="{# url 'articles:article' article.slug article.id #}">{{ article.title }}</a></h5> <p class="info">{% if article.author %}By <a href="{% url 'articles:author' article.author.slug article.author.id %}">{{ article.author }}</a>{% else %}Author deleted{% endif %}. Created on {{ article.date_created|date:"N j, Y." }}{% if article.updated_later %} <span class="text-nowrap">Updated {{ article.date_updated|date:"N j, Y." }}</span>{% endif %}</p> {{ article.body|linebreaks|truncatewords:100 }} </li> But this doesn't: <li class="card article category"> <h5 class="h5"><a href="{# url 'articles:article' article.slug article.id #}">{{ article.title }}</a></h5> <p class="info">{% if article.author %}By <a href="{% url 'articles:author' article.author.slug article.author.id %}">{{ article.author }}</a>{% else %}Author deleted{% endif %}. Created on {{ article.date_created|date:"N j, Y." }}{% if article.updated_later %} <span class="text-nowrap">Updated {{ article.date_updated|date:"N j, Y." }}</span>{% endif %}</p> {{ article.body|linebreaks|truncatewords:100 }} </li> It gives me this error, as if I passed it empty values: django.urls.exceptions.NoReverseMatch: Reverse for 'article' with arguments '('', '')' not found. 1 pattern(s) tried: ['articles/(?P<slug>[\\da-z]+(-[\\da-z]+)*)/(?P<article_id>[1-9]\\d*)/$'] It's strange because everything works except the one URL. And I'm using links to this page on other … -
Stream a list with Django Rest Framework
I have a function that reads a file and return a list of results. I want to display that result with Django Rest Framework (DRF). But sometimes function returns a huge list, lets say 50 items and I show 10 items per page in the template. DRF loads that 50 items for every page so every time I click "next" or "previous" that 50 items are requested and loaded which slows the pagination. How can I slice that list by 10 on every page? -
Images not showing in Django Admin
I am trying to add an a view for the uploaded images in admin, I have written the following but nothing is showing Here is the model class Post(models.Model): design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) def image_tag(self): return mark_safe('<img src"{}" height="50"/>'.format(self.design.url)) image_tag.short_description = 'Design' here is the admin class PostAdmin(admin.ModelAdmin): readonly_fields = ['image_tag'] What am I doing wrong? -
Django python for template tag not rendering
First, thank you, I'm grateful for any help provided!!! I am trying to render two forms in the same template from separate apps as well as display data from two separate classes in the same model. Essentially I want to Display the name of each the ToolsCategory in the template as titles/headers Display form data from the local form from the Tools app as well as a form from a second app as a sort of 'sub' form. I thought I had the template set up correctly for #1 above, but despite having data available (stored in the database), ToolCategories are not displaying in the template, specifically in this section (template referenced in full at the end of this question): {% for cat in tool_categories %} <h2>{{ cat.name }}</h2> {% endfor %} For #2, I have searched all over including the Django documentation, and have not been able to figure out how to reference another apps' form to include either after the templates local form tag is closed or within it. Do I use includes and some combination of url references from within the template? I have the following: models.py from django.db import models class Tool(models.Model): name = models.CharField(max_length=200) description … -
Creating admin panel for android app using django
I am building an eCommerce android app using java. I have used firebase as a backend for the android app. This e-commerce app will contain all the necessary features for e-commerce platform such as- 1) Authentication 2) Product Browsing 3) Checkout etc. I want to use firebase for an authentication system, but for most frequently used features such as viewing products I want to use a separate backend system that is built on the top of Django. I also want to handle the firebase database right from the Django admin dashboard. The business owner doesn't know how to deal with any coding he'll be working on a nice user interface i.e. our Django admin dashboard. Can you help me figure out how to implement this kind of system and link everything together? -
I want to retrieve profile of my user details into profile page of user so help me on retrieving details of user on profile picture view
My user model class User_Profile(models.Model): userprofilename = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='user_p') image_url = models.ImageField(upload_to=upload_location,null=True,blank=True) date_published = models.DateTimeField(auto_now=True,verbose_name="date published") date_updated =models.DateTimeField(auto_now=True,verbose_name="date updated") profile_slug = models.SlugField(blank=True,unique=False) followers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name = 'is_following',blank=True,null=True) My user post model class Post(models.Model): post_name = models.CharField(max_length=100,null=False,blank=False) video = models.FileField(upload_to=upload_location,null=False,blank=False) description = models.TextField(max_length=500,blank=True) date_published = models.DateTimeField(auto_now=True,verbose_name="date published") date_updated =models.DateTimeField(auto_now=True,verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) slug = models.SlugField(blank=True,unique=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='likes',blank=True) save_post = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='save_post',blank=True) My Post Serializer class PostSerializer(serializers.ModelSerializer): author = serializers.SerializerMethodField('get_author_from_author') class Meta: model = Post fields = ['post_name', 'description', 'video','author'] read_only_fields=['post_name','video','description'] def get_author_from_author(self,post): author = post.author.username return author My User profile serializer class UserProfileSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField('get_username_from_userprofilename') post = PostSerializer(many=True,read_only=True,source='post_set') # followers = FollowerSerializer(many=True,read_only=True) # following=FollowingSerializer(many=True,read_only=True) class Meta: model = User_Profile fields= ['image_url','username','post','followers','following'] read_only_fields=('username','followers','following') def get_username_from_userprofilename(self,post): username = post.userprofilename.username return username My view of user profile @api_view(['GET']) @permission_classes((IsAuthenticated, )) def user_profile(request,id): try: up = get_object_or_404(User_Profile, pk=id) except User_Profile.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': account=request.user post=Post.objects.all().filter(author=account) post_serializer=PostSerializer(post) follower_serializer = FollowerSerializer(up) following_serializer = FollowingSerializer(account) serializer=[follower_serializer.data,following_serializer.data,post_serializer.data] content = { 'status': 1, 'responseCode' : status.HTTP_200_OK, 'data': serializer, } return Response(content) When I run this it says me 'QuerySet' object has no attribute 'author' but when i run in shell without using serializer just using this code "post=Post.objects.all().filter(author=account)" it shows me the posts related to user … -
Deploy PythonAnywhere
I built my Django project on my local PC and then I 'uploaded' all the files to GitHub. For using PythonAnywhere as a clone to GitHub, I thought all the files wouldn't be transfered to PythonAnywhere server, but for my surprise they all gone there. In this way, I have now 3 different locals to get my files stored: local PC, GitHub and PythonAnywhere. When I make changes in my code (PC), I'll have to commit to GitHub and then update to PythonAnywhere? Is that all right or I'm missing something? Thank you! -
How to prevent the error "nice-select.css HTTP/1.1" 404" in django
I have a CSS file "style.css" some noticeable code from 'style.css' are given below: @import url(all.css); @import url(superslides.css); @import url(bootstrap-select.css); @import url(carousel-ticker.css); @import url(code_animate.css); @import url(bootsnav.css); @import url(owl.carousel.min.css); @import url(jquery-ui.css); @import url(nice-select.css); @import url(baguetteBox.min.css); from the above code, all the things are perfectly working except the last second line `@import url(nice-select.css); I'm getting the error "GET /static/css/nice-select.css HTTP/1.1" 404 1683 plz help me -
Django not adding a string to models
I am having a problem after I restarted my project from scratch I can add a value manually to my django model, but when it comes from a variable the user entered, it only pass a blank string.. Some pictures of the logs to be more explicit: Process: So, I am having a simple model Tech and I have a page where you can add a new name to Tech model. I enter the name (here i entered the name ede dede), click add, then i send it to the backend using AJAX. In the shell in VSCODE I see I received the element, but when I add it to my django model Tech, and then print the new object in Tech, it has an ID, everything, but the name is a blank string "" Moreover, When i print it in my python code, it doesnt even give me the queryset, i have nothing. How come? Here is a piece of my code VIEWS.PY: @ajax_required @require_http_methods(["POST"]) def AddNewEmployee(request): newtechname = request.POST.get('new_employee').title() response_data = {} print('new employee: '+newtechname) print(type(newtechname)) if Tech.objects.filter(name=newtechname).exists(): response_data['success'] = False response_data['result'] = 'This name already exists' return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: techname = Tech(name=newtechname) techname = … -
Model to create slider from bootstrap 4 IN DJANGO
created the slider with bootstrap 4 - now want to get is from admin upload images i have h1 and h3 tag also how i manage this with admin. how can i work with media {% block content2 %} <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <!-- <img class="d-block w-100" src="img/background.png" alt="First slide"> --> <img class="d-block w-100" src="{% static "blog/images/background.png" %}" alt="not found"> <div class="carousel-caption"> <h1 class="display-4">Welcome to igyaan.co.in</h1> <h3>Python Developer</h3> <!-- <button type="button" class="btn btn-outline-light btn-lg">View Demo</button> --> <!-- <button type="button" class="btn btn-outline-light btn-lg">Get Started</button> --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="">Get Started</button> </div> </div> <div class="carousel-item"> <!-- <img class="d-block w-100" src="img/background.png" alt="Second slide"> --> <img class="d-block w-100" src="{% static "blog/images/background.png" %}" alt="not found"> <div class="carousel-caption"> <h1 class="display-4">Welcome to igyaan.co.in</h1> <h3>Python Developer</h3> <!-- <button type="button" class="btn btn-outline-light btn-lg">View Demo</button> --> <!-- <button type="button" class="btn btn-outline-light btn-lg" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Get Started</button> --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="">Get Started</button> </div> </div> -
Django e-commerce project as beginner rabbitmq installing problem on windows 10
Kindly help but keep it simple as I am a beginner. Django e-commerce project, installed Erlang 64-bit and rabbitmq on windows 10, still when I try to install rabbitmq on bycharm terminal using : apt-get install rabbitmq .......It gives me this : 'apt-get' is not recognized as an internal or external command, operable program or batch file. Then tried replacing apt-get with choco and got the same response -
Profile model (extending custom user model) not getting registered in django admin
Note- list_display = ('email', 'first_name',) 'email', 'first_name' which defined in custom user model User I am not getting errors but it not registering the Profile model to admin why? if i am adding phone from Profile model to list_display = ('email', 'first_name', 'phone') i m getting error (admin.E108) The value of 'list_display[2]' refers to 'phone', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'users.User'. How can i add phone in list_display? I uses post_save_user_model_receiver() to auto create profile when user is created is it best way to do it? how can i add all Profile model fields for edit/update in users.admin (which is below). profile model from django.db import models from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth import get_user_model # or from users.models import User User = get_user_model() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) phone = models.IntegerField(null=True, blank=True) country = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=150, null=True, blank=True) bio = models.TextField(max_length=150, null=True, blank=True) def __str__(self): return str(self.user.email) def post_save_user_model_receiver(sender, instance, created, *args, **kwargs ): if created: try: Profile.objects.create(user=instance) # it create those user's profile except: pass post_save.connect(post_save_user_model_receiver, sender=User) Admin from django.contrib import … -
Django is not saving my images in my media files
In my project i have a model which includes a imageField, this model i am showing it in the templates as ModelForm through a CreateView setting a form_class, i've already set the media directory and its respective settings.py file configurations, however when i try to create an object or update it, i am not able to see the files neither in my view and in media files,i would also like to know the best to show this up in a detailview, how to show this file, i will leave my code and any other recommendations are accepted! Thanks! This is my model, as you can see, the field 'Estudios' is the one the requires the imagefield. I'm not sure if i messes in the 'upload_to' attribute, if this is the problem, i would like to know the correct way of doing it. Model class Consults(models.Model): #General Consult Info Paciente = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='Paciente') Fecha = models.DateField() Motivo = models.CharField(max_length=500,null=True) Padecimiento = models.CharField(max_length=500,null=True) #Main Patient Info Presion = models.CharField(max_length=20,blank=True,null=True) Temperatura = models.FloatField(blank=True,null=True) Peso = models.FloatField(blank=True,null=True) Talla = models.FloatField(blank=True,null=True) #Any Exams done before Estudios = models.ImageField(upload_to='studies',blank=True) #Interrogatory by System Digestivo = models.CharField(max_length=500,blank=True,null=True) Endocrino = models.CharField(max_length=500,blank=True,null=True) Renal = models.CharField(max_length=500,blank=True,null=True) Linfativo = models.CharField(max_length=500,blank=True,null=True) Respiratorio = models.CharField(max_length=500,blank=True,null=True) …