Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO: Pass a specific variable from template to view when button is pressed
I am building an online store that displays products with various fields to show in the template (name, price, item ID, etc), and I am doing this for every product passed in. So when the page loads I have many tags that share the same name. My problem is that I don't know how to pass the item ID into the next view. This value is the unique identifier so I need it to perform a select statement from my database to retrieve all of the items information. That information can then be displayed on another page where the user can see all details and add it to their cart. I tried to use a hidden form and use POST to get the value but I can't seem to get the exact element that I want since there are many with the same div tag ID. When each item is hovered over, a button appears to view the item details. When that button is pressed, this is where I need to send the item ID from the labeled div tag into the next view. views.py # Products page to view all items def products_page(request): args = { 'products': products, } … -
How to debug django staticfiles served with whitenoise, gunicorn, and heroku?
I've got a project that runs on Heroku from a Dockerfile and heroku.yml. The site generally works, but I am having trouble with static files. collectstatic is run when building the pack. I'm trying to use whitenoise but not sure why it's not working. It sounds so simple so I'm sure it's something silly. heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn records_project.wsgi settings.py MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sites.middleware.CurrentSiteMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', ... more stuff here... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # for referencing files with a URL STATIC_URL = '/static/' # where to find static files when local STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] # location of satatic files for production STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # how Django should look for static file directories; below is default STATICFILES_FINDERS = [ # defaults "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # This gives me a 500 error # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns here... ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
unexpected indent error installing django
Working through book "Django for Beginners". Have successfully completed 3 projects. Starting on Chapter 4. Forgot to exit pipenv from previous project. Created new directory, issued "pipenv install django==2.2.5", which resulted in following: PS C:\users\phil\desktop\django\blog> pipenv install django==2.2.5 Creating a virtualenv for this project… Pipfile: C:\Users\Phil\Desktop\django\Pipfile Using c:\users\phil\appdata\local\programs\python\python38\python.exe (3.8.2) to create virtualenv… [= ] Creating virtual environment...Already using interpreter c:\users\phil\appdata\local\programs\python\python38\python.exe Using base prefix 'c:\users\phil\appdata\local\programs\python\python38' New python executable in C:\Users\Phil.virtualenvs\django-nLBe_sZT\Scripts\python.exe Command C:\Users\Phil.virtu...T\Scripts\python.exe -m pip config list had error code 1 Failed creating virtual environment pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\cli\command.py", line 235, in install pipenv.exceptions.VirtualenvCreationException: retcode = do_install( pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 1734, in do_install pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 570, in ensure_project pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 505, in ensure_virtualenv pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 934, in do_create_virtualenv pipenv.exceptions.VirtualenvCreationException: raise exceptions.VirtualenvCreationException( pipenv.exceptions.VirtualenvCreationException: Traceback (most recent call last): File "c:\users\phil\appdata\local\programs\python\python38\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\phil\appdata\local\programs\python\python38\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 2628, in main() File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 860, in main create_environment( File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1173, in create_environment install_wheel(to_install, py_executable, search_dirs, download=download) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1019, in install_wheel _install_wheel_with_search_dir(download, project_names, py_executable, search_dirs) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1046, in _install_wheel_with_search_dir config = _pip_config(py_executable, python_path) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1128, in _pip_config config[key] = … -
How can I fetch all news headlines from nested tags?
For starters, i'm new in Python and i'm working with BS not too long. I am trying to get all the news headlines from all the articles on the website, but for some reason these loops doesn't work properly. But why?! I do not understand.. With this program code I tell the computer that I want to find and fetch all the 'a' tags that are inside multiple nested tags, isn't it? And i'm iterating over a nested tag to the next nested tag so i can fetch the "a" tag which contain the news headline. My code: url = "https://loudwire.com/category/news/" content = sessions.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") section = soup.findAll('section', {'class': 'blogroll row-standard carbonwidget-taxonomy outgrow no-band'}) for stn in section: blog = stn.findAll('div', {'class': 'blogroll-inner clearfix'}) for blogroll in blog: article = blogroll.findAll('article') for i in article: posts = i.findAll('div', {'class':'content'}) for wrapper in posts: a = wrapper.findAll('a', {'class': 'title'}) for link in a: print(link.get('title')) context = {'contex': link.get_text(strip=True)} return render(request, 'music/news.html', context) So, what am I doing wrong? Maybe you can show me where did i make a mistake and how to do this correctly? Thank you, any help will be invaluable! -
Django using custom icon in admin change list view
I want to have custom links in the change list view in Django admin. Currently, I can setup the links and get the three links in the last column: However, I would like to have three images instead of the text, but I do not know how to reference the static files for the images inside the corresponding models.py file. I tried: def get_icons(self): """ Icons with link for admin """ iconV = reverse('submission_view_details', args=[self.id]) imgV = mark_safe(f"<img src='statics/icons/icon_view.png'>") icon_V = mark_safe(f"<a href={iconV} target=_blank>{imgV} </a>") iconE = reverse('submission_edit', args=[self.id]) icon_E = mark_safe(f"<a href={iconE} target=_blank>Edit </a>") iconP = reverse('submission_pdf', args=[self.id]) icon_P = mark_safe(f"<a href={iconP} target=_blank>Print</a>") return icon_V + icon_E + icon_P #--- but this results in: In principle, the static files are well configured since I use custom css and jquery files stored in the static folder where the icons are located. -
Wndows IIS 10 will not serve static files from Django 2.2. . . How can I fix this?
The website displays to localhost without css, js, or images. I setup Windows IIS according to this blog including the final section about static files. The methods outlined are similar to answers from this question, this question, this blog, and this youtube video on how to serve static files from django with IIS. Django settings: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') # tested in shell, it is where I expect at the same level as manage.py The directory "static" was created with manage.py collectstatic in the expected STATIC_ROOT location with all of the static files contained The static directory was then added as a virtual directory: Then I removed the django handler I created from the static directories handler mappings: I unlocked the handlers at the root: The django application did display properly, with static files, when I tried using Wampserver w/ Apache and mod_wsgi. Unfortunately, it appears windows IIS will be the better solution for other unrelated reasons. Not too mention Wampserver is a development server, not a production server. I defined a path for the environment variable WSGI_LOG, the logs generated have no errors. Just states wfastcgi.py was initialized and will restart when there are changes to … -
Django InlineFormSet differentiate existing db forms vs extra forms
Consider my database has 2 existing instances of MyModel. My InlineFormSet displays both existing instances and 1 extra. Forms with existing instances only the state can be changed Forms with the extra all fields can be changed How do I achieve this? ==== (user can edit bold; italics is locked) [MyModel1 Name] . . [MyModel1 State] [MyModel2 Name] . . [MyModel2 State] [NewExtra Name] . . [NewExtra State] <-- both can be changed ==== I was trying to use {{ form.name.instance }} vs {{ form.name }} But I don't know how to differentiate between existing instances and extras. # forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ["name", "state"] MyModelFormSet = inlineformset_factory( MyParent, MyModel, form=MyModelForm, can_delete=False, extra=1 ) # views.py class UpdateMyModelsView(UpdateView): template_name = "update_mymodel.html" model = MyParent fields=[] success_url = reverse_lazy('update_success') def get_object(self, *args, **kwargs): return MyParent.objects.get(admin=self.request.user) def get_context_data(self, **kwargs): context = super(UpdateMyModelsView, self).get_context_data(**kwargs) parent= MyParent.objects.get(admin=self.request.user) context['parent'] = parent if self.request.POST: context['mymodel_formset'] = MyModelFormSet(self.request.POST, instance=self.object) else: context['mymodel_formset'] = MyModelFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() mymodel_formset= context['mymodel_formset'] with transaction.atomic(): self.object = context['parent'] if mymodel_formset.is_valid(): mymodel_formset.instance = self.object mymodel_formset.save() else: return super(UpdateMyModelsView, self).form_invalid(form) return super(UpdateMyModelsView, self).form_valid(form) # update_mymodel.html <form method="POST" class="pretty-form"> {% csrf_token %} {{ mymodel_formset.management_form … -
Data structure for internally generated images on Django
Let's say I have a django app where many images are internally generated after post requests made by users. Where should I stock these images ? As it is internally generated and not uploaded by users, it does not seem necessary to use the file storage systems and the /media/ location. But it does not seem clever to use the /static/ directory either, as many images will be added (and removed) then they are not static. Moreover I'd like to use a model that contains the images and other information about them. What model field class should I use to handle these images ? As the images are not uploaded by users models.ImageField does not seem appropriate. Thank you :) -
What am I unable to send email using Django?
I have turned on the 'allow less secure apps' on my google account. But when I submit the password reset form, it goes to the password_reset_done.html and DOESN'T show any error. But the mail is not sending. It's neither in my sentbox nor in the inbox of the email it's supposed to send to. This is what my urls.py looks like : from django.contrib.auth import views as auth_views path('password_reset/', auth_views.PasswordResetView.as_view(template_name="my_app/password_reset.html"), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name="my_app/password_reset_done.html"), name="password_reset_done"), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="my_app/password_reset_confirm.html"), name="password_reset_confirm" ), path('reset_password/', auth_views.PasswordResetCompleteView.as_view(template_name="my_app/password_reset_complete.html"), name="password_reset_complete" ), And here is the settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my_g_mail_id_here@domain.com' EMAIL_HOST_PASSWORD = '**********' I have literally read every other question and tried everything. Nothing is working for me. I am dying here to find out a solution, please help. -
Django sessions behavior
i am trying to understand how django sessions work so in my cart view i set a session variable named cart_id if i does not already exists , in my inspect element storage i see the session_id and i have a value let's say session_id = 1 ( i am not logged in) now when i login the session_id is different let's say session_id=2 but i am still able to retrieve the data from the previous session (1) , i mean if the session changes i shouldn't be able to do that , why can i do that ?? can anyone explain to me the session behavior ? -
How to create video streaming feature with django?
I want to create video streaming feature that, like twitch or something like that, who have any ideas? -
"double salting" a password with python
I am currently reworking a website that was written in php, in django and I need to copy over the old users. The problem is that the old website uses a "double salted" sha1 hashed password and I don't know how to replicate that with python. The code for the double salted password: sha1($salt . sha1($salt . sha1($password))); Addtionaly I really do not know much about php. Hopefully someone can help me with my issue. -
How to access Django database with JS
I have developed a website for an interactive game (mafia) using Django (python), but then i realized i need the displaying data(such as list of alive players, player messages, list of voted for lynch players, etc.) to be real-time and update instantly, whereas my website needs to be refreshed in order to see the updated database content. This is how it looks After realizing that, I started learning JavaScript, but now that I'm almost done, I noticed that Django and JavaScript functions cannot be called interactively, meaning I can't do JS functions and change database attributes at the same time. So I need an interactive frontend that updates data instantly, while being able to access and change database attributes as well(JS doesn't do this apparently). What should I learn for that? Thanks in advance. -
How to pass request.user / user to message in Django
So I want to let a user message another user. I want the 'sender' field automatically to be 'request.user' and the receiver field to be the user whom the sender clicked on through their profile page. How would I go about passing those into the form? forms.py/InstantMessageForm class InstantMessageForm(forms.ModelForm): class Meta: model = InstantMessage fields = ('receiver','sender','message') def save(self, commit=True): user = super(InstantMessageForm, self).save(commit=False) user.receiver = cleaned_data['receiver'] user.sender = cleaned_data['sender'] user.message = cleaned_data['message'] if commit: user.save() return user views.py/instant_message def instant_message(request): if request.method == 'POST': form = InstantMessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:home') else: form = InstantMessageForm() context = {'form':form} return render(request, 'dating_app/instant_message_form.html',context) models.py class InstantMessage(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) message = models.TextField() class InstantMessage(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) message = models.TextField() instant_message_form.py {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} <h1>Start chatting now!</h1> <div class='container'> <form method="post" action="{% url 'dating_app:instant_message' %}" > {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> </div> {% endblock content %} -
Elasticbeanstalk Django issues with ondeck vs current version
Using Elasticbeanstalk to deploy a Django application. Within the .ebextensions directory I've got the following (this is just a subset): commands: 00_pip_upgrade: command: /opt/python/run/venv/bin/pip install --upgrade pip leader_only: true 01_pip_install: command: /opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt leader_only: true container_commands: 111_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/ondeck/app/manage.py collectstatic --noinput" leader_only: true The issue is that anything with ondeck isn't found. I am having trouble finding AWS documentation regarding the transitions between bundle, ondeck, and current directories. When I ssh into the instances I don't see any directory at all for /opt/python/ondeck. Can someone help to explain if /opt/python/ondeck should still be used or what my issues may be? -
rest_framework_simplejwt post to an APIView
I have this settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } And this view: class Config(APIView): def get(self, request, *args, **kwargs): if 'config' in request.GET.dict(): if os.path.isfile(settings.CONFIG): yaml = read_config(settings.CONFIG) return Response(yaml) else: return Response({ "success": False, "error": "config file not found!"}) else: return Response({"success": False}) def post(self, request, *args, **kwargs): if 'data' in request.data: print(request.data['data']) return Response({"success": False}) With axios I manage my api calls, for example: axios.post('api/config/?config', { data: obj, headers: { Authorization: 'Bearer ' + rootState.auth.jwtToken } }) The problem is now, that I can not post data. I get an Unauthorized (401) error and in the response message it says: {"detail":"Authentication credentials were not provided."} Can you please tell me, what I'm missing here and how can I fix this issue? -
ReactJs: Passing a prop and using it within a map()
I'm trying to take a user inputted code and compare it to code within my database. Right now I can bring the code and display it outside the map function but when I try to add it, it doesn't work. here is my database: [ { "dwelling_code": "ABC-XYZ", "dwelling_name": "Neves Abode", "has_superAdmin": true, "room": [] } This is the parent component: class Dwel2 extends Component { state = { house: [], selectedMovie: null, data: "ABC-XYZ" } componentDidMount() { fetch('Removed for question', { method: 'GET', headers: { } }).then(resp => resp.json()) .then(resp => this.setState({ house: resp })) .catch(error => console.log(error)) } houseClicked = h => { console.log(h) } render() { return <div> <EnterCode dataFromParent={this.state.data} house={this.state.house} houseClicked={this.house} /> </div> } } This is the child component: function EnterCode(props) { return ( <div> <div> *THIS BIT DISPLAYS THE CODE*{props.dataFromParent} </div> {props.house.map(house => { var test = house.dwelling_name var code = house.dwelling_code if (code === {props.dataFromParent}) { test = "Test" } return ( <React.Fragment> <div>{test}</div> </React.Fragment> ) })} </div> ) } I just want to compare the code in the database to the code defined in the parent component -
Why Django does admin change page displays html instead of link after upgrading from Django 1.11 to 2.2?
I recently upgraded to Django 2.2 and now the HTML of my link is display instead of an actual link. Here is the code I suspect has changed in behavior: class RequestAdmin(admin.ModelAdmin): ordering = ('id', 'status', ) list_display = ('detail_link', 'status', 'requester', 'added', 'type', 'change_description', 'approve_or_deny') ... omitted for brevity ... # ID in list is rendered as link to open request details page def detail_link(self, obj): return '<a href="%s%s%s%s%s" target="_blank">%s</a>' % (('https://' if self.request.is_secure() else 'http://'), self.request.META['HTTP_HOST'], (settings.GUI_ROOT if settings.GUI_ROOT != '/' else ''), '/#/requests/', obj.id, obj.id) Before this would render a link. But now if renders this text instead: <a href="http://app-dev-001.example.com:5200/gui/#/requests/1" target="_blank">1</a> -
Sharing a database on 2 Django projects
I made a webapp on django and it's working great. However, I got feedback that my userbase prefers an app over visiting a website. This is completely understandable and I started researching in how to develop one for both android and iphone phones. I came across flutter and got to work. My flutter frontend has to communicate with an api which communicates to the same database as my webapp. So I installed djangorestframework and got it to work. The problem here is that I want to use token authentication for my app and basic authentication for my website. Since you can't have both [:(] I started the api as an extra project. Project 1 has the web application, built on Django. Project 2 is the rest API for my mobile phone apps. Now comes the great question, how do I make them share one database? -
django-encrypted-filefield with cloud storage
I'm new to this and can't find any resources, except this which does not provide a final answer and the orignal demo which only does things locally. I have a django-encrypted-filefield in a model, and a method to get the url: class Item(models.Model): file = EncryptedFileField(upload_to="files/") def get_url(self): return self.file.url This then pushes to an S3 bucket, say https://bucket.org/assests/. As mentioned in the docs, urls contains the line: url(r"^fetch/(?P<path>.+)", MyFetchView.as_view(), name=FETCH_URL_NAME), and the required environment variables are present. In the docs, when attempting to get the local url, we could simply access: {{ object.get_url }} And from that url we could download a non-encrypted version. However, in the bucket case, accessing in that way will return something resembling fetch/https://bucket.org/assets/files/item.txt, which is not a valid url. I know I am probably missing something very simple, but I can't remove the fetch because that would catch all urls. I don't know how to write a view that solves this either. Please could someone advise me or link me to a tutorial that helps with this. Thanks, Joshua. -
NoReverseMatch at /post/31/
I am new to django and creating a blog of which while using class-based views, my post detail was displaying properly. I decided to use function-based views and I am coming up with this error. Please help. This is my views.py file # class PostDetailView(DetailView): # model = Post # template_name = 'ecommerce/post_detail.html' # def get_context_data(self, *arg, **kwargs): # context = super().get_context_data(**kwargs) # form = CommentForm() # context['form'] = form # Your comment form # return context def post_detail(request, pk): post = get_object_or_404(Post, pk = pk) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context ={ 'post':post, 'is_liked':is_liked, } return render(request, 'ecommerce/post_detail.html', context) My urls.py path('post/<int:pk>/', views.post_detail, name='post-detail'), My post_detail.html {% extends "ecommerce/base.html" %} {% load crispy_forms_tags %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small> {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> </div> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token … -
django add to model from model have foreign key to this model from admin
models.py from django.db import models # Create your models here. class Client(models.Model): name = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(max_length=150, blank=True, null=True) class ClientNum(models.Model): number = models.CharField(max_length=20, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) class Ad(models.Model): num = models.CharField(max_length=20, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) i want to be able to add client from Ad model from django admin as i able to add number to client from client model i'm able to add user from Ad model in django admin but it opens new window i want to be in same window Acmin.py from django.contrib import admin # Register your models here. from .models import ClientNum, Client, Ad class ClinetNumAdmin(admin.TabularInline): model = ClientNum extra = 1 class ClinetNumRel(admin.ModelAdmin): inlines = [ClinetNumAdmin] class ClinetAdmin(admin.TabularInline): model = Client extra = 1 admin.site.register(ClientNum) admin.site.register(Client, ClinetNumRel) admin.site.register(Ad) -
how ajax work in Django getting id for new page this problem
$(document).on("click", "#transactRequest", function() { var request_no = $("#request_no").val(); $.ajax({ url: "{% url 'bond_fund:create-transaction/' request_no%}", method: "GET", success: function(data) {}, }); }); url path('create-transaction/', create_transaction), -
Serving two websites on one VPS
I am trying to serve two Django sites on one VPS (Digital Ocean) using Nginx and Gunicorn. I have an application called life-cal. When I type www.thelifecal.com into my browser address bar, I get exactly the response I am looking for and the Django app is served. However, when I just type thelifecal.com (no www.) I get the "Welcome to Nginx" page displayed. I used the following two tutorials to set up my server: https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#copy-this-code-paste-it-in-and-save https://medium.com/@caterinadmitrieva/serving-multiple-django-apps-on-second-level-domains-with-gunicorn-and-nginx-a4a14804174c /etc/nginx/sites-enabled/life-cal server { listen 80; server_name 167.71.116.21 thelifecal.com www.thelifecal.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/keegadmin/pyapps/life_cal; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/life-cal.sock; } } And a screenshot form namecheap: -
How to use for loop
I'am making movie website in django and I want to order my list of all movies from database .So I have found this second card with image on https://materializecss.com/cards.html but I really don't know how to use {% for %} {% endfor %} so I could have descriptions ,name of movie and image(poster) of movies in database.Can someone here could help me ?