Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add class to model form label Django
I've done a lot of digging on how to accomplish this, and aside from using 3'rd party modules is there not a simple way to customize labels for auto-generated forms in Django? i.e. models.py from django.db import models class Foo(models.Model): email = models.CharField(max_length=200) forms.py from django.forms import ModelForm from FooApp.models import Foo class FooForm(ModelForm): class Meta: model = Foo index.html <form action={% url 'FooApp:results' %} method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> views.py from .forms import FooForm def index(request): form = FooForm() return render(request, 'foos/index.html', {'form': form}) This seems to be the most "Django" way of doing things, but it offers little flexibility in terms of using frameworks such as bootstrap (which requires classes to be added to specific elements including input labels) I have read many answers that use widget customization, for example if I wanted to add the class bar to my email field on my FooForm: forms.py from django.forms import ModelForm from FooApp.models import Foo class FooForm(ModelForm): class Meta: model = Foo widgets = { 'email': TextInput(attrs={ 'class': 'bar' }), } however, I still can't figure out how to add a bar class to the label that is generated along with this input … -
Converting Naive Datetime object to user selected timezone in Django Template
I have Naive Datetime object stored in my Postgresql DB. I know the timezone used in the django project. Now, I have to convert these time objects into user selected timezone values in the template. Is there any way to make all the naive datetime objects to aware objects in the DB using proper migration? -
does django db_index=True index null value?
for example if i have a field name slug = models.CharField(null=True, db_index=True,max_length=50) and while saving data if left slug empty. will database index this saved null value? -
How to initialise a field in Django models using other fields in the model
I would like to call an API that will return the latitude and longitude from a postcode which is part of my Django Model class Nurse(models.Model): firstName = models.CharField(max_length=100, default="") lastName = models.CharField(max_length=100, default="") postCode = models.CharField(max_length=10, default="") area = models.CharField(max_length=100) phoneNumber = models.CharField(max_length=20) email = models.EmailField(max_length=100, null=True) latitude = models.FloatField(max_length=10, null=True) longitude = models.FloatField(max_length=10, null=True) So when a nurse object is created, I would like to call an api (postcode.io) which means I am able to get a latitude and longitude based on the postcode that saves these values to the data model. I need to have the latitude and longitude because I have use for it in a template where I need to access this information. Thanks! -
is there a function that return current path but in Django class
I need function that return part of url but inside ListView(where"XXXX") About project: its just a shopping list. I have 2 classes in models(ShoppingList and ShoppingItem). ShoppingItem looks like this: name = models.CharField(max_length=50, null=False) count = models.IntegerField(null=False) list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE, related_name='shopping_items')** date_created = models.DateTimeField(auto_now_add=True) My ListView class: class ListDetailUpdateView(ListView): model = ShoppingItem template_name = 'xlist_app/ListDetailUpdateView.html' context_object_name = 'products' queryset = ShoppingItem.objects.filter(list = XXXX) My idea is to cut last part of url (for example when i enter list number 2 i have adress http://127.0.0.1:8000/ListDetails/2) and replace "XXXX" with such a function. In my mind it should look like: queryset = ShoppingItem.objects.filter(list = int(request.path.split('/')[-1]) (if there is a better way to do that i will aprreciate all sugestions) -
Django update number of items on each save or delete
I am new to Django and still learning. I am looking to keep track of how many events I have under a test. My current model looks like class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) num_of_events = models.IntegerField(default=0) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) test = models.ForeignKey(Test,on_delete=models.CASCADE) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name def save(self): obj, created = Test.objects.update_or_create(name=self.test) obj.num_of_events += 1 super().save() def delete(self): self.test.num_of_events -= 1 super().delete() I thought I could just override the save() function but it does not update on the admin panel and still shows 0. I am trying to figure out what I am doing wrong. -
Django message variable not available in If.. statement
I am trying to use the Django message system to send the user back to their previous page. I have a Delete Customer FBV that can be accessed from multiple locations and after deleting the customer I want to send the user back to where they were. If I do this it works well and I get the behavior I expected: @login_required def delete_customer(request, custpk): del_cust = Customer.objects.get(pk=custpk) returnURL = '' if request.method == "POST": storage = get_messages(request) for message in storage: returnURL = message.message storage.used = True del_cust.delete() return redirect(returnURL) context = { 'del_cust': del_cust } return render(request, 'delete_customer.html', context) However, I want to be able to use that returnURL variable both in the If "POST" section and in the context variable to send to the render statement. Why when I do this does it not work? @login_required def delete_customer(request, custpk): del_cust = Customer.objects.get(pk=custpk) returnURL = '' storage = get_messages(request) for message in storage: returnURL = message.message storage.used = True if request.method == "POST": del_cust.delete() return redirect(returnURL) context = { 'del_cust': del_cust, 'returnURL': returnURL } return render(request, 'delete_customer.html', context) Why does this not work? When the redirect hits it says there is nothing to redirect to. How can I … -
how to access multiple models' classes chained with foreign keys in Django
I have 5 models chained with foreign keys in Django (version 3.0.5, Python 3.6.5). Theses models are as follow: class MyUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('nick name '), max_length=48, unique=True) first_name = models.CharField(_('First name '), max_length=48) last_name = models.CharField(_('family name '), max_length=48) email = models.EmailField(_(' Emial address'), unique=True) date_joined = models.DateTimeField( _('date_joined'), auto_now=False, auto_now_add=True) date_updated = models.DateTimeField( _('date_updated '), auto_now=True, auto_now_add=False) is_active = models.BooleanField(_('is your account active '), default=True) is_staff = models.BooleanField( _('is the user among admin team '), default=True) avatar = models.ImageField( upload_to='profile_image', blank=True, null=True) class ForumsPosts(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Post_Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=64) content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) class ForumsPostImages(models.Model): id = models.AutoField(primary_key=True) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) images = models.ImageField(upload_to='ForumsPostimages/%Y/%m/%d', blank=True, null=True ) class ForumsComments(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) comment_content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) class ForumsCommentImages(models.Model): id = models.AutoField(primary_key=True) comment = models.ForeignKey(ForumsComments, on_delete=models.CASCADE) images = models.ImageField(upload_to='ForumsCommentimages', blank=True, null=True ) I made request using GET method passed through ajax. The GET method has one parameter which is "ForumsPosts ID" . In Django I have a view function as … -
slug field to an existing database and unique slug generator
I already had a database created without the slug field. I wanted to add a unique slug field into my database. I have read the document django document on non nullable unqiue slug and have gone through the video: Master code online. And here is what I have done: I have created a slug field with params max_length and blank=True. Created utils.py in my project folder with function unique_slug_generator. Run python manage.py makemigrations. Added RunPython in migrated file. Run python manage.py migrate. Again changed the slug params to unique=True and repeated the process again. shop/models.py: class products(models.Model): image = models.ImageField(upload_to='products/') name = models.CharField(max_length=50) title = models.CharField(max_length=50) slug = models.SlugField(max_length=150, unique=True) price = models.FloatField() def __str__(self): return self.name project/utils.py: from django.utils.text import slugify import random import string def random_string_generator(size): return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)) def unique_slug_generator(model_instance, name, slug_field): slug = slugify(name) model_class = model_instance.__class__ while model_class.objects.filter(slug=slug).exists(): new_slug = "{slug}-{randstr}".format(slug=slug, randstr=random_string_generator(4) ) return slug After first makemigrations: # Generated by Django 3.0.4 on 2020-04-16 17:41 from django.db import migrations, models from project.utils import unique_slug_generator def update_slug(apps, schema_editor): products = apps.get_model('shop', 'products') for query in products.objects.all(): if not query.slug: query.slug = unique_slug_generator(query, query.title, query.slug) query.save() class Migration(migrations.Migration): dependencies … -
Speed tuning for mysql fetching in Django
I have model like this class MyJson(models.Model): created_at = models.DateTimeField(null=True) tweet_status = JSONField() is_show = models.BooleanField() def __str__(self): return self.tweet_id class Meta: indexes = [ models.Index(fields=['is_show']), models.Index(fields=['created_at',]) ] class MyJsonSerializer(serializers.ModelSerializer): tweet_status = serializers.SerializerMethodField() def get_tweet_status(self,obj): return obj.tweet_status class Meta: model = MyTweet fields = ('id','tweet_status','created_at') class MyJsonFilter(filters.FilterSet): is_show = filters.BooleanFilter(method='is_show_filter') created_at = filters.DateTimeFilter(lookup_expr='gt') def is_show_filter(self, queryset, name, value): return MyJson.objects.filter(is_show=1) then I want to fetch 5000 rows from more than 200000 rows where is_show = 1 order by created_at. But it takes more than 1 min. It's a bit too slow, I want to speed up more.... Where is the bottle neck???or where should I improve?? I set is_show and created_at as index. Is there any setting for this case??? -
Why are my users messages not appearing fully?
Ok, so I am building an inbox and messaging system for my DatingApp. I have been able to display the conversations between my user and other users in my view 'Messages'. Now, I am attempting to display the contents of the conversations through messages via the Message view but I am failing. Because only the sent messages from request.user are showing. I attempted doing two queries at once through my InstantMessage model (which has a foreign key to my Conversation model), a query for request.user and one for user, but still, only the messages sent from request.user are showing up. And furthermore, when you click on the conversation, it should only show messages between that specific user but I am showing ALL messages sent out by request.user to ALL users. So I got two problems here. I'm super stuck on this, so any help would be HIGHLY appreciated. views.py/Message and Messages #Displays contents of a conversation via messages def message(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user) | Q(sender_id=profile_id)).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) conversations = Conversation.objects.filter(members=request.user) context = {'messages' : messages, 'conversations':conversations} return render(request, 'dating_app/message.html', context) #Displays conversations a user is having def messages(request,profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user) | Q(sender_id=profile_id)).\ values('sender_id','receiver_id', 'message', 'date', … -
How can i get error logs on my live Django/Django channels app?
I deployed a Django/Django Channels application to a VPS using Nginx, Gunicorn, Daphne and systemd, everything seems to work for now, but when i try to reach a Websocket consumer of my app using this: ws = create_connection("ws://mydomain/receiver") ws.send('Test') I get a Connection refused error, which means that something is not right on my Django Channels side. Since the Django app is running on a linux VPS, i do not have access to a console like i would during development. Is there any way to check the errors of my application, or a console or anything that would help me see what's happening behind the scenes here? -
Django model that stores multiple other models that store multiple other models
I am learning Django so this is all very new to me. What I am trying to create is a bit of functionality in my admin panel that will allow me to create a layout like this. Test -Event1 --Property1 --Property2 --Property3 --Property4 -Event2 --Property1a --Property2b --Property3c --Property4d -Event3 --Property1aa --Property2bb --Property3cc --Property4dd -Event4 --Property1aaa --Property2bbb --Property3ccc --Property4ddd I want to have multiple tests. My current model setup looks like this: from django.db import models from django.forms import ModelForm TYPE_CHOICES = ( ("string", "string"), ("integer", "integer"), ("array", "array"), ("boolean", "boolean") ) class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) test_id = models.IntegerField() class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name class Property(models.Model): name = models.CharField(max_length=255) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = models.CharField(max_length=255) class Meta: verbose_name = 'Property' verbose_name_plural = 'Properties' def __str__(self): return self.name class TestForm(ModelForm): class Meta: model = Test fields = ['name', 'description'] I have my admin panel setup so that I can create multiple properties. But then when I go to the "Events" section in my admin panel I can only create events. I want … -
NameError at /contact/ name 'ContactForm' is not defined error:
I am creating a contact page where an email is sent to the user. When I go to access the contact page I run into the error "NameError at /contact/ name 'ContactForm' is not defined" Any idea? Code: def Contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') template = get_template('/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['servwishes@gmail.com'], headers = { 'Reply To': contact_email } ) enter code here email.send() return redirect('blog:success') return render(request, 'users/contact.html', {'form':Contact_Form }) -
Django Rest Framework - ImproperlyConfigured: Could not resolve URL for hyperlinked relationship
Similar to this question, but I do not have namespaces or base-names, so none of the solutions in that question have worked. I have 2 models: Organisation Student A student can belong to an organisation. When I retrieve an organisation, I want a child object in the returned JSON that lists the 'related' students as hyperlinked urls (as per HATEOS). models.py class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True, related_name='students') serializers.py class OrganisationSerializer(serializers.ModelSerializer): students = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='student-detail', lookup_url_kwarg='organisation_id') class Meta: model = Organisation fields = ('id', 'name','students') class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' urls.py from rest_framework import routers from .views import OrganisationViewSet, StudentViewSet from django.conf.urls import url router = routers.DefaultRouter() router.register(r'api/v1/organisations', OrganisationViewSet) router.register(r'api/v1/students', StudentViewSet) urlpatterns = router.urls views.py from .models import Organisation, Student from rest_framework import viewsets, permissions from .serializers import OrganisationSerializer, StudentSerializer # Organisation Viewset class OrganisationViewSet(viewsets.ModelViewSet): queryset = Organisation.objects.all() serializer_class = OrganisationSerializer permission_classes = [ permissions.AllowAny ] # Student Viewset class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer permission_classes = [ permissions.AllowAny ] So this should work as this … -
daphne in supervisor not working. How to make it work?
alltime in console browser i see it WebSocket connection to 'ws://(amazon_www...).compute.amazonaws.com/ws/chat_view/43/' failed: Error during WebSocket handshake: Unexpected response code: 404 [program:gunicorn] directory = /home/ubuntu/site command=/home/ubuntu/env/bin/gunicorn --workers 1 --bind unix:/home/ubuntu/site/app.sock djangoshop.wsgi:application autostart=true autorestart=true stopasgroup=true [program:platform_asgi_workers] command=/home/ubuntu/env/bin/python3 /home/ubuntu/site/manage.py runworker channels process_name=asgi_worker%(process_num)s numprocs=1 stdout_logfile=/var/log/worker.log [program:daphne] socket=tcp://localhost:9000 directory = /home/ubuntu/site command=/home/ubuntu/env/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --endpoint fd:ft fd:fileno=0 --access-log - --proxy-headers djangoshop.asgi:application numprocs=1 autostart=true autorestart=true stopasgroup=true stdout_logfile=/var/log/worker.log daphne BACKOFF Exited too quickly (process log may have details) gunicorn RUNNING pid 20882, uptime 0:00:16 platform_asgi_workers:asgi_worker0 BACKOFF Exited too quickly (process log may have details) per 1 sec supervisor out daphne STARTING gunicorn RUNNING pid 20882, uptime 0:00:22 platform_asgi_workers:asgi_worker0 STARTING nginx: upstream app { server wsgiserver:8000; } upstream ws_server { server localhost:9000; } server { listen 80; server_name (my_www).compute.amazonaws.com; client_max_body_size 20M; location / { try_files $uri @proxy_to_app; } location /ws { try_files $uri @proxy_to_ws; } location @proxy_to_ws { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://ws_server; } location @proxy_to_app { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_pass http://app; } location /static/ { alias /home/ubuntu//djaro/site/static_in_dev/; } Gunicorn worked, daphne not, with manage.py … -
Django xhtml2pdf non-editable, read-only pdf?
I've got xhtml2pdf version 0.2.3 working in Django, to output a certificate for a user once a course has been completed. The only issue with it is that the PDF is editable, which means the user could change information on it (name, course name, date, etc.) before printing it out. I couldn't find anything in the docs or my searches that referenced whether or not you can make the PDFs read-only once generated. The view: import io from io import BytesIO from xhtml2pdf import pisa from django.core.files import File from django.template.loader import get_template def generate_course_certificate(earned_credit): template = get_template("reports/course_certificate.html") context = {"earned_credit": earned_credit} html = template.render(context) output = BytesIO() inmemoryfile = io.BytesIO(output.getvalue()) pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), inmemoryfile) earned_credit.proof_of_completion.save( f"{earned_credit.course.name} {earned_credit.pk}.pdf", File(inmemoryfile) ) earned_credit.save() I found it odd that it was editable by default. Is there a way to make it read-only? -
Error message : No DjangoTemplates backend is configured
I'm a pretty old guy who used a little bit Django 5-6 years ago. A friend helped me to develop a small program for my needs and I was very impressed by the flexibility of the tool. After 1 year, no more needs, so I stopped using it. Today, coming back to Django, I spend a day to understand how to reinstall Python and Django on Windows 10 and I tested Django with different old codes I used for learning. I still have the files (code, template, input, and output) but I get an error message. I suppose that this message can come from a change in the syntax (new version ??) or an incomplete installation. For a specialist, it would be maybe easy to solve the problem but for me, it is like to climb Everest. So, if anybody has an idea, I would appreciate a lot. To help, I prepare some information. 1/ - _ code _ errors messages (at running) _ template _ input _ output (I got before) 2/ - _ Installation of Python and Django (commands I used) Thanks a lot for your help ! 1/.....==== ==== code (file : main.py) ==== from django.conf import … -
DigitalOcean: Deploying Dockerized Django/PostgreSQL and pointing to domain
I have been following the Django for Professionals book by William Vincent for a little while. After a few weeks, I've successfully completed my first Dockerized Django/Postgres project. Rather than deploy to Heroku, I'd like to try my hand at a DigitalOcean "one click install" Docker droplet; however, I've been struggling. Steps I've taken to deploy: Created droplet Created SSH key, new user CD'd into a directory to pull my repo $cd home/user/<repo dir> Pulled my repo $git pull <repo> Built the Docker machines docker-compose -f docker-compose-prod.yml up --build -d # dockerfile # pull base image FROM python:3.7 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /code # install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # copy project COPY . /code/ # docker-compose-prod.yml version: '3.7' services: web: build: . # command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn layoffs.wsgi -b 0.0.0.0:8000 environment: - ENVIRONMENT=production - SECRET_KEY=mysecretkey ports: - 8000:8000 depends_on: - db db: image: postgres:11 env_file: - myenv.env Building the Docker containers works, I'm able to do things like create a superuser using docker-compose exec web python manage.py createsuperuser, run migrations, and using docker-compose logs shows that … -
How do I configure my model such that my generated Django migration doesn't result in an error?
I'm using Django and Python 3.7. When I run my command to generate a migration ... (venv) localhost:web davea$ python manage.py makemigrations maps Migrations for 'maps': maps/migrations/0003_auto_20200416_1017.py - Alter field name on cooptype - Alter unique_together for cooptype (0 constraint(s)) The generated migration looks like ... # Generated by Django 2.0 on 2020-04-16 15:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maps', '0002_auto_20200401_1440'), ] operations = [ migrations.AlterField( model_name='cooptype', name='name', field=models.CharField(max_length=200, unique=True), ), migrations.AlterUniqueTogether( name='cooptype', unique_together=set(), ), ] However, running the migration results in an error ... (venv) localhost:web davea$ python manage.py migrate maps System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: maps Running migrations: Applying maps.0003_auto_20200416_1017...Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in … -
Is there any issue about installation of Django?
enter image description here Hello all ,I am creating my very first project in django using VS code editor its very basic but giving error unexpected indent pylint error -
Sidebar content list is coming below profile image in django webpage bootstrap 4
Everything was right until I used profile pic in webpage. The sidebar content which was on the right of webpage is now coming below profile pic. If I use float-right it comes to the right but still below profile pic. I'm using sublime 3 for this django project. My code for profile pic is- {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle" width="100px" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <!-- FORM HERE --> </div {% endblock content %} And that for sidebar content is- <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest Posts</li> <li class="list-group-item list-group-item-light">Announcements</li> <li class="list-group-item list-group-item-light">Calendars</li> <li class="list-group-item list-group-item-light">etc.</li> </ul> </p> </div> </div> And my webpage actually looks like this- "PROF username ILE email PIC" Sidebar content Sorry I couldn't upload image -
What is the purpose of app_name in urls.py in Django?
When include()ing urlconf from the Django app to the project's urls.py, some kind of app's name (or namespace) should be specified as: app_namespace in include((pattern_list, app_namespace), namespace=None) in main urls.py or app_name variable in app's urls.py. Since, I guess, Django 2, the second method is the preferred one Although I copy-pasted first function signature from Django 3 documentation. But that's not the main point. My current understanding of namespace parameter of include() is that it's what I use when using reverse(). What is the purpose of app_name in app's urls.py or app_namespace in main urls.py? Are these exactly the same thing? How is it used by Django? Existing questions (and answers) I've found here explain HOW I should specify it rather than WHY. -
Create auto increment number for every user when ordering
This is the most asked question, but I am failing to accomplish this task. I have a Book model with book_history field like class Book(Models): customer = models.ForeignKey(Customer) book_history_number = models.CharField(max_length=120) def _get_book_customer_id(self): b_id = self.customer num = 1 while Book.objects.filter(customer=b_id).exists(): num += 1 return cus_ord_id def save(self, *args, **kwargs): if not self.book_history_number: self.book_history_number = self._get_book_customer_id() my objective is to increment by when a user book something for example I have A and B users and A booked smth and book_history_number should be 1 next time it should 2 like this: A: 1, 2,... n because A booked two times B: 0 B did not booked but if B user did it would be 1. with above code I cannot able to solve this problem. Any help please -
How can I move my django project to another directory?
There have been questions asked about similar things, but over 4 years ago. I'm sure those things don't apply because I have tried them and they didn't work. I was working in a directory where I had my virtualvenv and django project but I wanted to create a new folder and move them to that new folder: old path: dev/python/django/ new path: dev/python/django/blog I then activated my virtualenv and moved into the directory where the manage.py file was and, as I always have, ran python manage.py runserver however it shot out an error: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I haven't changed anything in my manage.py file, in fact, I didn't change anything since the last time I ran this project. Since I moved the project and the virtualenv attached to it, it no longer runs. I tried reinstalling django in my env, but it says it already exists. I tried running python3 manage.py runserver as some other posts suggest, but that doesn't work either. Same error... What am I missing? All of the paths in my files are from the BASE_DIR variable and no paths are absolute. What am I missing? How can I …