Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Graphene/GraphQL find specific column value
For some reason, I can't figure out how to simply find a specific piece of data in my SQLAlchemy database. In the graphene-python documentation it simply does this query to match the id (which is a string): book(id: "Qm9vazow") { id title } Now here's my Flask-Graphene-SQLAlchemy code for my BookSchema and I want to find a specific title instead of an ID: class BookModel(db.Model): __table__ = db.Model.metadata.tables['books_book'] # Schema Object class BookSchema(SQLAlchemyObjectType): class Meta: model = BookModel interfaces = (relay.Node, ) # Connection class BookConnection(relay.Connection): class Meta: node = BookSchema # GraphQL query class Query(graphene.ObjectType): node = relay.Node.Field() allBooks = SQLAlchemyConnectionField(BookConnection) schema = graphene.Schema(query=Query, types=[BookSchema]) When I run this query, everything is fine and returns 3 book titles: { "query": "{ allBooks(first: 3) { edges { node { title } } } }" } However, once I try to match a specific title, it stops working. For example: # I tried all these queries, none worked 1. { allBooks(title: \"some book title\") { edges { node { title } } } } 2. { allBooks(title: \"some book title\") { title } 3. { allBooks(title: 'some book title') { edges { node { title } } } } The error: … -
What is the best strategy to call a home made python package from a Django application?
I’m working actually on a Django project based on some algorithms (that I developped in a separated python project as a package). I did use Python 3.7.3 and Django 2.2.2. I would like to have your opinion about the best way to add this resource to my Django project ? Simply add my package to my Django project and import it, or maybe use a wheel and install it like any other managed resource ? Maybe other practice could be a better one ? Sorry if my question is not relevant. It’s my first Django application and I would like to seize this opportunity for learning how to do things right way. Thx in advance -
NoReverseMatch error for update and delete view
I've a trouble with an update view and a delete view. Below the code: views.py from django.shortcuts import get_object_or_404, redirect, render from django.utils.text import slugify from .forms import BlogTagForm from .models import BlogTag def updateBlogTag(request, slug_tag=None): update_tag = get_object_or_404(BlogTag, slug_tag=slug_tag) form = BlogTagForm(request.POST or None, instance=update_tag) if form.is_valid(): update_tag = form.save(commit=False) update_tag.slug_tag = slugify(update_tag.tag_name) update_tag.save() return redirect('tag_list') context = { 'form': form, } template = 'blog/editing/create_tag.html' return render(request, template, context) def deleteBlogTag(request, slug_tag): if request.method == 'POST': tag = BlogTag.objects.get(slug_tag=slug_tag) tag.delete() return redirect('tag_list') models.py from django.db import models from django.urls import reverse class BlogTag(models.Model): tag_name = models.CharField( 'Tag', max_length=50, help_text="Every key concept must be not longer then 50 characters", unique=True, ) slug_tag = models.SlugField( 'Slug', unique=True, help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents", ) def __str__(self): return self.tag_name def get_absolute_url(self): return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag}) class Meta: ordering = ['tag_name'] forms.py from django import forms from .models import BlogTag class BlogTagForm(forms.ModelForm): tag_name = forms.CharField( max_length=50, help_text="<small>Write a tag here. The tag must be have max 50 characters.</small>", widget=forms.TextInput( attrs={ "placeholder": "Tag", "type": "text", "id": "id_tag", "class": "form-control form-control-lg", } ), ) class Meta: model = BlogTag fields = ["tag_name"] tag_list.html <table class="table … -
Django throws an error on any command: AttributeError: 'NoneType' object has no attribute 'startswith'
I deployed my Django app to PythonAnywhere. I need to run some commands in their Console. I created virtual environment using command: mkvirtualenv --python=/usr/bin/python3.6 venv Then I installed all my dependencies (including Django) pip install -r requirements.txt After, I want to migrate my database using command: python manage.py migrate I get this traceback: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect conn_params = self.get_connection_params() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 201, in get_connection_params if settings_dict['HOST'].startswith('/'): AttributeError: 'NoneType' object has no attribute 'startswith' By the way it's happeninng on each django comand … -
Django Match-team-player relationship player select
i have player-team-match model 1 team have more than 5 players ( with substitute player (maybe 8 maybe 10+ player)) However, there must be 5 players in each team in one match. My question; How can I choose the player in the match (for that team) I want like this; A team= 8 players a,b,c,d,e,f,g,h their name and a,b,c,d,e play in this match. B team= 7 players k,l,m,n,o,p their name and k,l,m,n,o play in this match class Team(models.Model): name=models.CharField(max_length=255,verbose_name="Takım ismi") short_name=models.CharField(max_length=25,null=True,blank=True) slug=models.SlugField(max_length=120,unique=True) bio=models.TextField() class Player(models.Model): slug=models.SlugField(unique=True,max_length=120) team= models.ForeignKey(Team,related_name='player',verbose_name='Team',on_delete=models.PROTECT,null=True,blank=True)... class Match(models.Model): name=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) map=models.ForeignKey('GameMap',null=True,blank=True,related_name='matchmap',on_delete=models.PROTECT) league=models.ForeignKey('League',blank=True,null=True,on_delete=models.PROTECT,related_name='matchleague') team1=models.ForeignKey('Team',related_name='team1') team2=models.ForeignKey('Team',related_name='team2')... -
Accessing and saving a field that is not included in fields attribute in extending generic class-based CreateView
I'm trying to display the user a form with comments not included. When the user submits the form, then, I want to manually add something to my comments, and then only, saving the object. With default implementation, it doesn't do anything with comments. ! app/views.py class ContactUsView(SuccessMessageMixin, CreateView): model = Contact fields = ['first_name', 'last_name', 'email_address'] success_message = "Thank you for your enquiry. We' ll be in touch shortly." ! app/models.py class Contact(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True) email_address = models.EmailField() comments = models.TextField() def get_absolute_url(self): return reverse('contact') def __str__(self): return self.first_name -
Django migration issue for boolean field
I have models and there was no Boolean field in the very beginning when i run makemigraiton and migrate In that mean time, i added some post... later i added new field called is_printable as boolean field... this is my current models: from django.db import models import datetime from django.utils import timezone Create your models here. class Article(models.Model): title = models.CharField(max_length=50) body = models.TextField() category = models.CharField( null=False, blank=False, max_length=50, ) is_printable = models.BooleanField() date = models.DateTimeField(timezone.now) when i add is_printable = models.BooleanField() I cant run migrate command, it throws me an error called django.core.exceptions.ValidationError: ["'2019-07-07 06:56:52.693378+00:00' value must be either True or False."] What is possible solution for this? -
Django deleting large Porstgres table content raises out of memory error
I have a Django model (Payment) with 1335888 instances, and I am calling a Payment.objects.all().delete(), but I get the following exception: Traceback (most recent call last): File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: out of memory DETAIL: Failed on request of size 262144. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 662, in delete collector.collect(del_query) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/deletion.py", line 220, in collect elif sub_objs: File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __bool__ self._fetch_all() File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql cursor.execute(sql, params) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.OperationalError: out of memory DETAIL: Failed on request of size 262144. I don't know why I am getting it, but I suppose it is … -
How to create realtime mp4 streaming service using Django?
I have created a Django application, which reads mp4/rtsp streams using OpenCV, then I process each frame using OpenCV and Tensorflow. Then I return processed frames using StreamingHttpResponse. How can I return processed frames as mp4 or m3u8 stream? Processed streams then will be read by Android and IOS applications, that's why I need mp4 or m3u8 stream -
django.db.utils.ProgrammingError: column "rtd" of relation "classroom_itembatch" already exists Keeps on coming evrytime
I'm working on a project with my team and whenever we update our app "django.db.utils.ProgrammingError: column "rtd" of relation "classroom_itembatch" already exists" errors keeps on coming and it with throw same error on every table in data base untill all the database are recreated and remigrated. I don't know why this error keeps on coming everytime and the only sollution I have to this is to drop my database using postgress which is the worst sollution I think. Please help me to resolve this error. -
How can i add default user to object when the user who created the object was deleted
I have Model "Tasks" contains "User" foreign key when user deleted , how can i add another user to that object as a backup user when creator is deleted ? first_user = User.objects.get(username='nagah') class Task(models.Model): taskname = models.CharField(max_length=30) created = models.DateTimeField(auto_now=True) is_complete = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, default=first_user.id) -
Passing custom html template doesn't work with reset password in django
I am implementing reset page for my django application. Everything works fine if i use auth_views.PasswordResetView.as_view() without passing in template_name. It uses default django provided templates and i get confirmation email and password is successfully reset but i want to pass in my own template to do so which has simple form with an image and one input tag for email. The view shows up fine but when i click submit it only shows 1 post request in console. I have tried implementing registration directory since in source code it uses that but no luck so far. I have also changed input to a button for submitting. I tried removing extra styling classes for css too. I am using following path for reset page. path('login/password-reset/', auth_views.PasswordResetView.as_view(), name = 'password_reset' ), Passing following generated the view but when i submit the email it doesnt get me to reset_done. path('login/password-reset/', auth_views.PasswordResetView.as_view(template_name = 'login/password_reset_form.html'), name = 'password_reset' ), -
not working update method in rest API framework
I want to be able to edit registered User profile by using UpdateModelMixin class. The forms to edit is existed but when we want to PUT the new information , the new one is not applied and the pervious info is displayed. views.py: c lass ProfessorDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView): queryset = Professor.objects.all() serializer_class = ProfessorDetailSerializers def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) serializers.py: class ProfessorDetailSerializers(serializers.ModelSerializer): user = CustomUserSerializer() professor_no = SerializerMethodField() class Meta: model = Student fields = ( 'user', 'professor_no', ) def get_professor_no(self, obj): return str(obj.professor_no) There is not any changes applied on information -
how to use forms in APIView to send post request in django
i'm making an OTP app using class based views. the bottom is the class for generating and sending OTP to a phone number. the template works good and when i press the submit button in my html form it sends a post request and it returns response: 'phone number is not given in post req' so the template and API works! but the {{form}} in the html template doesn't work so i can't send the OTP to the number submitted in the form. so what am i doing wrong? forms.py exists in my project with 1 field class ValidatePhoneSendOTP(APIView,TemplateView): template_name = 'accs/reg.html' def post(self, request, *args, **kwargs): form = PhoneRegForm(request.POST) phone_number = request.data.get('phone') if phone_number: phone = str(phone_number) user = User.objects.filter(phone_number__iexact = phone) if user.exists(): return Response({ 'status': False, 'detail': 'user exists' }) . . . . . . . . else: return Response({ 'status' : False, 'detail' : 'phone number is not given in post req' }) i tried to pass FormView in the class after the APIView,TemplateView but i couldn't get that to work. -
Can't import django even though it says requi
I had some django projects in a directory and they were spinning up fine with runserver. The projects were all very similar, so I created a subdirectory and moved the django projects inside this subdirectory. Now when I try runserver I get the following error. virtualenv is activated and pip says django is already installed, but for some reason it can't import django. Why am I getting this error now? jpanknin:spinup2/ (master) $ source virtualenv/bin/activate [22:56:28] (virtualenv) jpanknin:spinup2/ (master) $ pip install "django<1.12" [22:56:37] Requirement already satisfied: django<1.12 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (1.11.22) Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from django<1.12) (2018.5) (virtualenv) jpanknin:spinup2/ (master) $ python manage.py runserver [22:56:53] Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Nginx upstream prematurely closed connection, but files still being written
I have a Django and Nginx server running in docker containers. Here is the docker compose file. This is the Dockerfile for the django app: FROM python:3.7 RUN mkdir -p /opt/services/djangoapp/src WORKDIR /opt/services/djangoapp/src RUN pip install gunicorn COPY . /opt/services/djangoapp/src RUN pip install -r facefind/requirements.txt EXPOSE 8000 CMD ["gunicorn", "--chdir", "facefind", "--bind", ":8000", "FaceFind.wsgi:application"] When uploading files, I get errors like this: 2019/07/07 02:07:25 [error] 6#6: *4 upstream prematurely closed connection while reading response header from upstream, client: [ip], server: localhost, request: "POST /addface/4 HTTP/1.1", upstream: "http://[ip]:8000/addface/4", host: "example.com", referrer: "https://example.com/addface/4" [ip] - - [07/Jul/2019:02:07:25 +0000] "POST /addface/4 HTTP/1.1" 502 174 "https://example.com/addface/4" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0" "99.252.117.58" 2019/07/07 02:08:01 [warn] 6#6: *7 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000003, client: [ip], server: localhost, request: "POST /addface/4 HTTP/1.1", host: "example.com", referrer: "example.com" [ip] - - [07/Jul/2019:02:08:01 +0000] "GET /media/flower.jpeg HTTP/1.1" 200 20775 "-" "OxfordCloudService/1.0" "40.85.225.30" 2019/07/07 02:08:01 [error] 6#6: *7 upstream prematurely closed connection while reading response header from upstream, client: [ip], server: localhost, request: "POST /addface/4 HTTP/1.1", upstream: "http://[ip]:8000/addface/4", host: "example.com", referrer: "https://example.com/addface/4" [ip] - - [07/Jul/2019:02:08:01 +0000] "POST /addface/4 HTTP/1.1" 502 174 "https://example.com/addface/4" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0" … -
Cant create user with django-knox
I am having issues creating a user serializer.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Invoice class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = Userfields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], None, validated_data['password']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" This is the error message I am getting. tuple' object has no attribute '_meta' -
How can I count the number of SQL queries needed to render a Django admin page?
Part of my django admin site that uses a lot of Inlines is running slowly and based on this question I think that it might have to do with the number of SQL queries it generates. I'd like to count the number of SQL queries so I can test some changes. I know how to do this on a custom-written view but I can't figure out how to do it for a standard admin view. Here's how I would test my own view. The view is called weight_plot and the app is called runner. from django.test.client import RequestFactory from django.conf import settings settings.DEBUG = True from django.db import connection import runner.views myview = runner.views.weight_plot request = factory.get('/weights') response = myview(request) n_queries = len(connection.queries) This works, and now I'd like to see how many queries are needed to load the page at https://example.com/admin/runner/MODEL_NAME/add/. But I can't figure out what view to use for this instead of myview above. -
OSError when opening .heic image with PIL
My django app allows users to upload images to their account. I'm using jquery file upload to process asynchronously. In my upload view, I'm using PIL to do some basic image manipulations (resize, rotate if necessary). Relevant portion of view for image upload below: def group_photo_upload_desktop(request): if request.method == 'POST': try: group_id = request.POST.get('group_id') uploaded_image = request.FILES.get("image", default=None) image = Image.open(uploaded_image) image = autorotate_image(image) image = resize_image(image) Occasionally, I have started to see the code fail when PIL attempts to open the image. The failing image is always .heic format and as of now, is only occurring with one user (only have 7 users so not large sample set) who is uploading the image from an iPhone (not sure of exact version). What is really confusing me is that the vast majority of .heic images upload just fine for the user and will often upload successfully after several hour delay. A traceback of a recent error is below. File "/home/EscapeKit/socialwaiver/core/views_group_detail_desktop.py", line 308, in group_photo_upload_desktop image = Image.open(uploaded_image) File "/home/EscapeKit/.virtualenvs/venv/lib/python3.5/site-packages/PIL/Image.py", line 2622, in open % (filename if filename else fp)) OSError: cannot identify image file <TemporaryUploadedFile: 20190706_154803.heic (application/octet-stream)> And request.FILES <MultiValueDict: {'image': [<TemporaryUploadedFile: 20190706_154803.heic (application/octet-stream)>]}> I've had the user send me … -
How to store media file uploaded from Django Admin panel on the AWS S3?
Thanks for taking the time to read my question! I hope I was clear enough, in case I wasn't please let me know, I will try to provide more content. I successfully configured the settings.py to store all the static on the S3 after running the "manage.py collectstatic" command. I have tried to follow different guides on how to achieve the same thing for the media files. All of them focus on uploading files from a website form, which isn't my case. What I ideally want is to have my S3 bucket have 2 folders 'static' and 'media'. Where media folder will have subfolder based on which of my Django models I have update with an image. So one file might look something like this on AWS S3: "media/myprojects/personal_website.jpg" and then of course display that image on the website. So let me show you what I have now. models.py (For the my_projects App) from django.db import models class Project(models.Model): title = models.CharField(max_length=200) cover = models.ImageField(upload_to='project-images/') def __str__(self): return self.title settigns.py ... AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' … -
How could a field in another table in a datatable of angular by means of a foreign key?
I have data table in angular and one of the fields or column of that table is a foreign key, I mean an ID (computer_id), but I want to show in place of that ID a field of another table, that is, I have in the table records (table that I am showing) a team id as a foreign key and I want to show the name of that team, which is a column of the table of equipment (table of which I have its id as a foreign key in the table of records). I have no idea how to do it in angular, if you gave me an idea they would help me a lot. PD: to bring me the data from the database, I am consuming the api through http queries and using django rest framework, my doubt would be if I have to bring me by query http get the two tables but then as I do relation for the table records. As a database manager I am using MYSQL -
Modifing fields form order of CustomUser model
I created a customUser model so that the default User is overwritten. This is my customUser model: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser from crispy_forms.helper import FormHelper class CustomUserCreationForm(UserCreationForm): helper = FormHelper() class Meta(UserCreationForm): model = CustomUser fields = ('first_name', 'username', 'email', 'last_name', 'organization', 'location', 'postcode', 'phone', 'agree_conditions') class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm): model = CustomUser fields = ('username', 'email', 'first_name', 'last_name','organization', 'location', 'postcode', 'phone', 'agree_conditions') Everything works perfectly however I am not able to change the order of the "User default" fields. I know how to re-order the form fields, I can simply change the order in the fields = (a, b, c). For example if I want "c" to appear before "a" and "b" in the form, I can do: fields = (c, a, b). HOWVER I want to move up the password and password confirmation but I do not know how to do so because I do know know their name in the User default model. Ideally I want this: fields = ('username', 'email', 'PASSWORD_WHICH_I_DONT_KNOW_THE_NAME', 'CONFIRMPASSWORD_WHICH_I_DONT_KNOW_THE_NAME' 'first_name', 'last_name','organization', 'location', 'postcode', 'phone', 'agree_conditions') -
Adding extra-fields signup User without using {{ form.as_p }} but bootstrap
I am new to Django, I am trying to add extrafields when the user signup. The fields I am adding are: 'first_name', 'last_name', 'organization', 'location', 'postcode', 'phone' to the already existing 'username' and 'password'. My base app is called: mysite This is what I am doing: 1) Create an app users (It is my understanding this app is a special app inside Django and contains some default values) python manage.py startapp users 2) Add 'users.apps.UsersConfig' in my mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', ] 3) Telling Django in mysite/settings.py NOT to look at the deafault User but to my new User model. AUTH_USER_MODEL = 'users.CustomUser' 4) Add in users/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): first_name = models.CharField(max_length=100, default='') last_name = models.CharField(max_length=100, default='') organization = models.CharField(max_length=100, default='') location = models.CharField(max_length=100, default='') postcode = models.CharField(max_length=100, default='') phone = models.CharField(max_length=100, default='') def __str__(self): return self.email 5) Create touch users/forms.py With inside: (Here I am not sure why we need there 2 classes and what their functionality is) from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): … -
How can I grab articles with the same tag, so within a template I can display those articles?
I'm new to Django, so thanks for any help. I have an Article model, and I would like to display related/similar articles by assigning tags to each article. I've tried making a function/filter in my views.py that inherits from self (that particular article) and filters out the articles with the same tag, but with no success. from django.db import models class Article(models.Model): title = models.CharField(max_length=200, blank=True) thumbnail = models.ImageField(max_length=200, blank=True) tag = models.CharField(max_length=200, blank=True) from .models import Article class ArticleView(DetailView): template_name = "article/article.html" model = Article def related_articles(self): tagged = Article.objects.filter(tag=self.tag) return tagged {% if articles.objects.all %} {% for article in article.objects.all|related_articles %} <div> <img src="{{ article.thumbnail.url }}"> <span>{{ article.title }}</span> </div> {% endfor %} {% endif %} So, whenever I try to use this filter I get no results. -
When a scroll event occurs using animate I want to position scroll up a bit
When a scroll event occurs using animate I want to position scroll up a bit The current scrolltop code looks like this: $ (". go_btn"). click (function () { const number = $ (". go_input"). val (); if (number == 1) { $ ('html, body'). animate ({ 'scrollTop': $ ("# index_first"). offset (). bottom }); } $ ('html, body'). animate ({ 'scrollTop': $ ("# index _" + number) .offset (). top }); }} But the problem is like the picture. It is moved, but the upper part is covered by the navigation bar. I want to prevent row data from being obscured by the navigation bar I want the scrolling up a bit. Is there any good way?