Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the console respond that: Article encountered an unexpected pub_date parameter?
enter image description here I study django and while creating my blog I ran into such a problem enter image description here -
Should I start with Learning Django or Python [closed]
I have chosen to learn web programming and I selected the Django framework as my development choice. However I know that Django is Python based so my question is. Should I start to learn Python first then move to Django or should I learn Django first then commence with Python? -
ModelChoiceField options not taken into account in the HTML rendering
I am currently working on an application and I have a problem with my ModelForm. I feel like the options that I put in my ModelChoiceField is not being taken into account. This is my forms.py: class PlayerModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return '{} from {} at {} '.format(obj.name, obj.team, obj.price) class Form(forms.ModelForm): def __init__(self, contest_id, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) contest = ContestLOL.objects.filter(id=contest_id)[0] teams = contest.teams.all() players = Player.objects.filter(team__in=teams).order_by('-price') self.fields['top'].queryset = players.filter(role='Top') self.fields['jungle'].queryset = players.filter(role='Jungle') self.fields['mid'].queryset = players.filter(role='Mid') self.fields['adc'].queryset = players.filter(role='ADC') self.fields['support'].queryset = players.filter(role='Support') self.fields['top'].initial = players.filter(role='Top')[0] self.fields['jungle'].initial = players.filter(role='Jungle')[0] self.fields['mid'].initial = players.filter(role='Mid')[0] self.fields['adc'].initial = players.filter(role='ADC')[0] self.fields['support'].initial = players.filter(role='Support')[0] class Meta: model = Model fields = {'top': PlayerModelChoiceField( queryset=Player.objects.filter(role='Top'), widget=forms.RadioSelect(), empty_label=None, to_field_name="top"), 'jungle': PlayerModelChoiceField( queryset=Player.objects.filter(role='Jungle'), widget=forms.RadioSelect(), empty_label=None, to_field_name="jungle"), 'mid': PlayerModelChoiceField( queryset=Player.objects.filter(role='Mid'), widget=forms.RadioSelect(), empty_label=None, to_field_name="mid"), 'adc': PlayerModelChoiceField( queryset=Player.objects.filter(role='ADC'), widget=forms.RadioSelect(), empty_label=None, to_field_name="adc"), 'support': PlayerModelChoiceField( queryset=Player.objects.filter(role='Support'), widget=forms.RadioSelect(), empty_label=None, to_field_name="supp") } fields = {'top', 'jungle', 'mid', 'adc', 'support'} This is is my view.py: def contest(request, slug=None): contest = get_object_or_404(ContestLOL, slug=slug) matches= Match.objects.filter(contest=contest.id) form = Form(contest.id, request.POST or None) if form.is_valid(): bet = form.save(commit=False) bet.user = request.user bet.contest = contest bet.save() messages.success(request, 'Bet was saved') form = Form(contest.id) output = { "contest": contest, "form": form, "matches": matches } return render(request, "questions/contest.html", output) And this is … -
What does migrate mean in django?
I'm currently learning Django using python. I'm using the Django website as my reference and there is one line of code that I am supposed to enter " python manage.py migrate'. I'm wondering what does migrate means and what does it do? Thank You! -
Django force_str for table choices returns original value
I have the following model: SERVICE_STATE_RECEIVED = 'RECEIVED' SERVICE_STATE_WAITING_FOR_ASSESSMENT = 'WAITING_FOR_ASSESSMENT' SERVICE_STATE_WARRANTY = 'WARRANTY' SERVICE_STATE_QUOTED = 'QUOTED' SERVICE_STATE_SCHEDULED = 'SCHEDULED' SERVICE_STATE_REPAIRING = 'REPAIRING' SERVICE_STATE_DOWN = 'DOWN' SERVICE_STATE_FINISHED = 'FINISHED' SERVICE_STATE_DELIVERED = 'DELIVERED' SERVICE_STATE_CHOICES = ( (SERVICE_STATE_RECEIVED, _("Recibido")), (SERVICE_STATE_WAITING_FOR_ASSESSMENT, _("Esperando valoración")), (SERVICE_STATE_WARRANTY, _("En Garantía")), (SERVICE_STATE_QUOTED, _("Cotizado")), (SERVICE_STATE_SCHEDULED, _("Programado")), (SERVICE_STATE_REPAIRING, _("En Reparación")), (SERVICE_STATE_DOWN, _("Baja")), (SERVICE_STATE_FINISHED, _("Servicio Concluido")), (SERVICE_STATE_DELIVERED, _("Entregado")), ) class ServiceStatus(CustomModel): service = models.ForeignKey(Service, on_delete=models.PROTECT, related_name='status', verbose_name=_("Servicio")) status = models.CharField(max_length=25, choices=SERVICE_STATE_CHOICES, verbose_name=_("Estatus")) timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora")) comment = models.TextField(null=True, blank=True, verbose_name=_("Comentarios")) update = False class Meta: verbose_name = _("Estado del Servicio") verbose_name_plural = _("Estados de los Servicios") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.service.id, self.status, self.timestamp) And the following serializer: class ServiceForListSerializer(CustomModelSerializer): product = serializers.SerializerMethodField() serial_number = serializers.SerializerMethodField() reception_date = serializers.SerializerMethodField() status = serializers.SerializerMethodField() class Meta: model = models.Service fields = ('id', 'product', 'serial_number', 'client_name', 'client_phone', 'comment', 'reception_date', 'status') def get_product(self, instance): product = instance.item.product.name return product def get_serial_number(self, instance): serial_number = instance.item.serial_number return serial_number def get_reception_date(self, instance): reception_date = instance.status.all().order_by('timestamp').first().timestamp reception_date_to_return = reception_date.strftime("%d/%m/%Y") return reception_date_to_return def get_status(self, instance): status = instance.status.all().order_by('timestamp').last().status status_to_return = force_str(status) return status_to_return I want the field status to bring the verbose content of choices tupple, but I get the string value in the database: I … -
getting an image from static/img into a template in Django
I have a Django project with a static/img folder I want to get this image loaded but since it's in a variable and static points to my static folder, not static/img I'm not sure how to get it in. I tried f'img/{project.image}' project.image is set to equal "01.jpg" <img class="card-img-top" src="{% static project.image %}"> -
Django Query For Max Value For Column Which Includes Foreign Key Table Also In Result
I have two related models - class Auction(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) # other properties and class MaxBid(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) value = models.DecimalField( decimal_places=2, max_digits=10, validators=[MinValueValidator(MINIMUM_TRANSACTION_VALUE)] ) created = models.DateTimeField(default=timezone.now) auction = models.ForeignKey( 'Auction', on_delete=models.CASCADE, related_name='bids' ) user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="bids" ) I want to get the maximum bid a user has made in an auction and the auction columns in a SINGLE django SQL query. This SO question - SQL select only rows with max value on a column - has helped me to see a way of doing it in raw sql - SELECT * FROM "products_maxbid" as m JOIN "products_auction" as a on m.auction_id = a.uuid WHERE m.uuid in ( SELECT m.uuid FROM "products_maxbid" as m INNER JOIN ( SELECT auction_id, Max(value) as value FROM "products_maxbid" WHERE user_id = '2' GROUP BY auction_id ) n on m.auction_id = n.auction_id and m.value = n.value and m.user_id = '2' ) ORDER BY a.square_id # can apply any orders now to the auction table like normal I don't know where to begin to achieve this in Django - well, the docs obviously, but nothing stands out in there. All I've worked out is the … -
GeoDjango Point fields widget does not show coords properly
in a Django application I use PointField point = models.PointField(_('Point'), null=False, blank=False) I use normal long lat system, so [50, 15] should be a point in Europe, in the Czech Republic I think. But then in the administration there is a nice interactive widget with a map which shows the point somewhere in the Red sea. When I check the value in the code of the widget It says the coords are completely different (some numbers in millions), but when I want to output the coords to the console, it says normaly [50, 15] print(Datapoint.objects.get(pk=pk).point) # Output: SRID: 4326; Point(50, 15) Does anyone have an idea what could go wrong here? I know there are more SRIDs, but even when I change every possible SRID attribute (Model, AdminSite, Form, Widget), still does not work... Thanks, RA -
Can I manipulate my django dataset utilizing the view?
I'm developing with django an application for the management of the company budget. All you need to have to work a lot with the db. I noticed that with django to be able to modify the data contained in my db I always have to go through a required view. But, once I have installed the data through a form, I would like to make changes to the dataset? it's possible? I'll give you an example: through my form I collect the data of the monthly collections per business unit: | ____ Jan ____ | ___ Fab _____ | Business unit_1 | ____ 100 ___ | _____ 100 ____ | Business unit_2 | ____ 100 ____ | ____ 100 ____ | If I wanted to have a second db that brings me back the total per month: | ____ Jan ____ | ___ Fab _____ | total | ____ 200 ____ | ____ 200 ____ | And I want that, if I delete a row in business unit, automatically the total is udpdated. Do you think I can do it directly in the view and so utilziing only django?? if yes how? or do you recommend another way ?? -
How to serialize object to json with custom fields in python
I have a class class Person(object): def __init__(self,age,name): self.person_age = age self.person_name = name And i want to serialize object to json. I can do so: person = Person(20,'Piter') person.__dict__ But such an approach will return it: {'person_age':20,person_name:'Piter'} I want serialize my object to json with my own fields. Instead of 'person_age' - 'age'. Instead of 'person_name' - 'name': {'age':20,name:'Piter'} How can this be done if the class has many fields? -
django template rendering using for loop
i am rendering the 4 items in a row through a for loop , the problem is that in the first line it renders 4 items but the rest of the items that come in the loop are rendered in separate line. code <div class="card-group"> {% for item in wt %} <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.product_name}}</h5> <p class="card-text">{{item.thumbnail_desc}}</p> <a href="blog_detail/{{item.post_id}}" class="btn btn-primary">View Product</a> </div> </div> {% if forloop.counter|divisibleby:4 %} </div> {% endif %} {% endfor %} here i am using bootstrap and django framework... i also used "row" class but it also doesnt work very well -
Django| Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P<username>[^/]+)$']
I am following django tutorial by @CoreyMSchafer. I got error while practicing i can't find solution to it. According to my understanding its problem with reversing of url. but can't find out what is wrong This is what I'm getting as an error Error: NoReverseMatch at / Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)$'] For some reason error is in head of base.html where I'm linking bootstrap. I also tried removing that link then its giving same error but at line 0 of base.html views.py: class UserPostListView(ListView): model = Post context_object_name = 'posts' template_name = 'blog/user_posts.html' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.all().filter(author= user).order_by('-date_posted') urls.py file: from django.urls import path, include from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeletelView, UserPostListView from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeletelView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), ] user_posts.html: {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num … -
How do I make changes on a live Django website?
I have a live Django website I need to make changes on and I want to know what's the best / most correct way of updating the code of the website, I have access to the remote server and access to the git. Thanks in advance!!! -
trying to build an app with graphql & Django
I am an inter and they assigned me a new project. I've never used Django before so I'm kinda lost. for this project, I have to use an existing database (SQL server), and so I had to recreate my User class by extending "AbstractBaseUser" and "PermissionsMixin". and as I said it should use graphQL (my first time also) so I am using graphene. I managed to do queries, but when it comes to authentication (using "graphql_jwt"), I can query to get a Token, but when I use the token to authenticate I always get the user not authenticated. (I am using a decorator @ Login_required form graphql_jwt) I think I am failing to understand how the authentication works in Django. can anyone explain it further to me? -
My Django app won't detect settings.py, and won't detect SECRET_KEY
I have a problem with my Django app. For some reason it won't detect settings.py nor SECRET_KEY. First, here is my structure of the project dir C:. │ manage.py │ ├───Accounts │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ ├───templates │ │ login.html │ │ signup.html │ │ │ └───__pycache__ │ omitted │ ├───Blog │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ └───templates ├───Learning │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ __init__.py │ │ │ └───templates ├───static │ │ compiled_sass.css │ │ compiled_sass.css.map │ │ │ └───sass-styles │ │ styles.sass │ │ │ ├───src │ │ omitted │ │ │ └───static │ omitted │ └───tf │ local_settings.py │ settings.py │ TODO.md │ urls.py │ wsgi.py │ __init__.py │ ├───templates └───__pycache__ omitted Now, when running I get django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. That's how my settings.py look like … -
How do I view and delete an admin migration
I tried running my Django project and I got a warning on unapplied migrations. The problem is, I didn't make any changes that would arouse any migration so I set out to look for the migration files but I couldn't find any. I ran python manage.py showmigrations to see the migrations that were pending I then discovered there were two admin migrations that were pending [ ] 0004_auto_20200124_1105 [ ] 0005_auto_20200124_1107 I've been trying all day to trace these files or to even see the changes to no avail. Please help -
Django how to display choosen file name on custom input file?
Hae all, My problem is quite simple to understand. I have made a form where user will input his/her personal information. That personal information also requires to upload a file. I want that whenever user opens his profile then he/she must be able to see already attached file name in custom input field or atleast if he/she doesn't choose any new picture, input file field value must be set to previously attached picture url. This is what I tried to do but didn't worked when setting value of custom input field. Kindly suggest some way around of it. <div class="col-md-6 mb-3"> {% if details.picture.url != '' %} <label for="front">Picture <span class="text-muted"> <a href='{{details.picture.url}}'>{{details.picture}}</a></span></label> {% else %} <label for="front">ID Card (front) <span class="text-muted">Take a snap and upload</span></label> {% endif %} <input type="file" class="form-control" id="front" name="front" value="{{details.picture.url}}" > </div> -
Django: Is it faster to use Ajax or built in Methods?
I've got a question regarding Posting Data from a Template to the server using Ajax or built in Django Methods. Consider the following example: What i mean by Django Methods: views.py: def block_user(request, lobby): target_id = util.get_other_user(Chat.objects.get(lobby=lobby), request.user).id request.user.profile.block(User.objects.get(id=target_id)) return HttpResponseRedirect(reverse('chat-explicit', kwargs={'lobby': lobby})) template: <button type="button" class="btn btn-danger" id="block-user-btn" onclick="location.href='{% url 'user-block' chatroom.lobby %}';">Block</button> What i mean by using Ajax: views.py: def block_user(request): lobby = request.POST.get("lobby", None) target_id = util.get_other_user(Chat.objects.get(lobby=lobby), request.user).id request.user.profile.block(User.objects.get(id=target_id)) return HttpResponse('') template: <button type="button" class="btn btn-danger" id="block-user-btn">Block</button> <script> $("#block-user-btn").click(function() { $.ajax({ headers: { "X-CSRFToken": getCookie("csrftoken") }, url: "{% url 'block-user' %}", data: { 'lobby': '{{ lobby }}' }, type: 'post', dataType: 'json', async: false, success: function(data) { location.reload(); }, failure: function(data) { console.log("error"); } }); }); </script> Both methods work, but which one is faster? or which one is better practice? 1) In this case the response from the server just tells javascript to reload the page. Considering other cases: 2) What, if i wanted to load another page as response? What would be better practice then? 3) And what would be better, if i neither wanted to redirect the user nor reload the page, but just Post data to the server and run server side code? -
How can I use a third-party repo, which requires a conda environment, within my Django project
I'm setting up a Django project on an Ubuntu 18.06 Digital Ocean droplet. I'm using python3-venv to create virtual environment in my project root, and have installed django and other dependencies within this. I'm using a DRF class SplitTrackView(APIView): within which I want to call the separator.separate_to_file method from the spleeter project: https://github.com/deezer/spleeter I've currently cloned the spleeter repo into my project folder, and installed miniconda in my home directory, but the second step in the spleeter setup instructions is: conda install -c conda-forge spleeter So here I'm creating a new virtual envorinment in conda to allow spleeter to run. My questions are: Is cloning the repo into my project root the best approach? How do I handle dependency management when I have a virtual environment for my Django project, and a separate conda one to run spleeter? Many thanks. -
css does not apply style to templates in django
The theme applied by css does not work. In the past it used to apply but i do not what i did that its not executable anymore. base.htmnl is core template for other pages. In base.html i have : <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'nana/css/main.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <body> <nav class='navbar mynav-fixed-top navbar-expand-lg bg-dark' role='navigation' id='navbar'> <div class="container-fluid"> </div> </nav> <div class="container-fluid"> {% block content %} <div class="main"> </div> {% endblock %} main.css body{background-color: yellow} settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] The css does not work. I do not knwow why the application does not apply changes in css file. Would appreciate your though and help how to fix it. -
Django - Issue viewing media files on admin page
In my user model, I have a property called profilePic. This is set to an image within my media folder at the root of my project. I display the profilePic image in a template, and it is displayed successfully. However in my admin page, when I click the link set to the profilePic attribute, I get returned a 404 error. Here is my models.py: class User(AbstractUser): profilePic = models.ImageField(upload_to='profile_pics/', default='media/default-profile.png') settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) template: <!DOCTYPE html> <html lang="en"> <body> <img src="{{ user.profilePic }}"></img> </body> </html> The image is successfully displayed in the browser, however in the admin, when I click the path that links to the file, I get s 404 Page Not Found Error. The url changes when I click the path, it changes too http://localhost:8000/media/media/default-profile.png. An extra /media/ is in the url. This may be due to what I set the default property to on the profilePic attribute, however when I remove the media/ and the beginning of the default property, the image cannot be viewed in the browser no longer, however can be viewed in the … -
django ajax click function - change value of foreign key textchoice field
I have 2 models ToDoList and Tasks. In Tasks model I set a ForeignKey to ToDoList (one ToDoList can have many tasks). What I want to do is: I want to have next to every task in the detail view a button. When I click on the button the "status field" of this specific task should change to trash. I want to use ajax and trying to understand it (Iam new to that). Can somebody please help/guide and support me. models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class TimeStamp(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class ToDoList(TimeStamp): class STATUS(models.TextChoices): PUBLISHED = "published", "Published" TRASH = "trash", "Trash" WORKINGDRAFT = "workingdraft", "Workingdraft" headline = models.CharField(max_length=200) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED) def __str__(self): return self.headline def get_absolute_url(self): return reverse('notepad:todo_detail', args=[str(self.id)]) class Tasks(TimeStamp): class STATUS(models.TextChoices): PUBLISHED = "published", "Published" TRASH = "trash", "Trash" WORKINGDRAFT = "workingdraft", "Workingdraft" todos = models.CharField(max_length=250) todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE, related_name='tasks') status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED) def __str__(self): return self.todos views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from django.forms.models import … -
How to fix django.db.utils.IntegrityError: insert or delete on table in Django 3.x
From today morning I'm getting django.db.utils.IntegrityError: insert or update on table "Department_course" violates foreign key constraint "Department_course_Course_type_id_71e71f3c_fk_Departmen" DETAIL: Key (Course_type_id)=(UG) is not present in table "Department_coursetype". error while migrating django models. Help me to fix this problem guys. Today morning I tried to create another two models with foreign keys of department model. From that time the issue was started.But now I deleted these two models. And still i got same error. help me to fix it models.py from django.db import models # Create your models here. class departments(models.Model): # department = models.CharField(max_length = 40, null = True) name = models.CharField(max_length=40, unique=True, primary_key = True) img = models.ImageField(upload_to="Dept_img", null = True) desc = models.TextField(null = True) def __str__(self): return self.name class department_detail(models.Model): name = models.OneToOneField(departments, on_delete=models.CASCADE, null = True) About = models.TextField(null = True) def __str__(self): return self.name.name class course(models.Model): COURSE = ( ('UG','UG'), ('PG','PG') ) Department_name = models.ForeignKey(departments, on_delete=models.CASCADE, null = True) Course_type = models.CharField(null=True, max_length=40, choices=COURSE, default = None) Course_name = models.CharField(null = True, max_length=80) Course_duration = models.CharField(null=True, max_length=30) def __str__(self): return self.Department_name.name class carousel(models.Model): Department = models.ForeignKey(departments,on_delete=models.CASCADE, null = True) Image = models.ImageField(upload_to='Carousel', null = True) Img_title = models.CharField(max_length=30, null=True) Img_desc = models.CharField(max_length=500, null=True) date_created = models.DateTimeField(auto_now_add=True, … -
Multiple Django projects on one domain under sub urls using NGINX and proxy_pass
I have a Django app on mydomain.com/. I want to have another app on, lets say, mydomain.com/staging/. 1st app: mydomain.com/ 2nd app: mydomain.com/staging/ How do I configure it in Nginx and Django? After this location ~* ^/staging/ { rewrite ^/staging/(.*) /$1 break; proxy_pass http://127.0.0.1:18000; }` I still have my 2nd app redirect me to my 1st app. When I use mydomain.com/staging/admin/, it redirects me to mydomain.com/admin/, and every URI I use does the same. What is the proper way of configuring multiple sub-url Django apps? -
How do I solve this error and install Django?
SSL module is not available in Python