Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loop not adding data to table
The for loop works, but instead of adding the data to the table, it adds the data beneath the existing table. laptop_list.html <div class="container"> <div class="table-responsive-sm"> <table class="table"> {%for laptop in laptops%} <div class="table-responsive-sm"> <tbody> <tr> <td>{{laptop.laptop_id}}</td> <td>{{laptop.make}}</td> <td>{{laptop.model}}</td> <td>{{laptop.specification}}</td> <td>{{laptop.warranty}}</td> <td>{{laptop.condition}}</td> <td>{{laptop.price}}</td> </tr> </tbody> </div> </table> {%endfor%} </div> </div> models.py class Laptop(models.Model): make = models.CharField(max_length = 100) model = models.CharField(max_length = 100) specification = models.CharField(max_length = 100) warranty = models.CharField(max_length = 100) condition = models.CharField(max_length = 100) price = models.CharField(max_length = 100) added_by = models.ForeignKey(User, default = None, on_delete=models.CASCADE) views.py def laptop_list(request): laptops = Laptop.objects.all() return render(request,'laptops/laptop_list.html',{'laptops':laptops}) -
Django stores uploaded file outside project directory
I'm using Django 2 I have a model Course to create a course and upload banner image as ImageField() class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) banner = models.ImageField(upload_to='course/%Y/%m/%d', blank=True) In my settings files located at app/settings/local.py # at top of settings file, defined BASE_DIR BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_dir') ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root') The image is uploading perfectly but it's uploaded location is outside of project directory. Say if my project resides in my_project directory which contains app module and other modules along with static_dir to store static files. But the static_cdn directory is created outside my_project directory. I want it to be inside my_project directory. What is wrong there? -
I'm trying to update and delete a user and i get this error " 'user' object is not iterable"
I'm trying to update and delete a user, but while I am iterating threw users in view.py I get 'User' object is not iterable in index.html {% block body %} <table> <tr> <th>Edit</th> <th>Id</th> <th>Name</th> <th>Age</th> </tr> {% for user23 in context %} <tr> <td><a href="{{user23.id}}">delete</a></td> <td>{{ user23.id }}</td> <td>{{ user23.name}}</td> <td>{{ user23.age}}</td> </tr> {% endfor %} </table> {%endblock%} in forms.py class userform(forms.ModelForm): class Meta: fields = ['name', 'age'] model = user in urls.py urlpatterns = [ #/library/ url(r'^$', views.index, name='index'), url(r'^createprofile/$', views.createpro, name='createprofile'), url(r'^(?P<id>[0-9]+)/$', views.updateuser, name='updateuser'), url(r'^(?P<id>[0-9]+)$', views.deleteuser, name='deleteuser'), ] in views.py def index(request): context = user.objects.all() return render(request, 'index.html', {'context': context}) def createpro(request): if request.method == 'POST': form = userform(request.POST) if form.is_valid(): form.save() return redirect('index')#render(request, 'createprofile.html', {'form': form}) else: form = userform() return render(request, 'createprofile.html', {'form': form}) def updateuser(request, id): context = user.objects.get(pk=id) form = userform(request.POST or None, instance=context) if form.is_valid(): form.save() return redirect('index') return render(request, 'index.html', {'context': context, 'form':form}) def deleteuser(request, id): context = user.objects.get(pk=id) if request.method == 'POST': context.delete() return redirect('index') return render(request, 'deleteuser.html', {'context':context}) in model.py class user(models.Model): name = models.CharField(max_length=50) age = models.IntegerField(max_length=10) def __str__(self): return self.name please help me where the error is? please ignore this block of text **********I have 3 models: … -
Adding existing users to group in django via HTML page
I have created a django app in which users can register via SignUp Form.I have created two groups Admin Users and Staff Users.When any user signs up he is not allocated to any of the group.I want to create a webpage where all the users will be displayed and there should be a dropdown in front of user names which will let the logged in user( a member of Admin User group,I will restrict this page to Admin Users group only) to select the group among the available groups.In simple words any member of group Admin User should be able to add any other member who is not assigned to any group. I need a basic help on how the views.py and HTML page should be look like -
Django Rest Framework Filter related model field
I have trouble giving this a proper title. These are my models: class User(models.Model): # standard django User model from django.contrib.auth.models class Person(models.Model): name = models.CharField(...) class Note(models.Model) person = models.ForeignKey(Person, related_name='PersonNote') ower = models.ForeignKey(User) date_added = models.DateTimeField(auto_now_add=True) I would like to filter all persons, whose last note from the User with ID = 5 has the action = 'helloed'. The pseudo SQL is perhaps like this: SELECT name from person, action, date_added from note, id from user WHERE 1 = 1 AND action = 'helloed' AND id = 5 AND date_added = MAX(date_added) I understand this can be done via raw sql queries, but I would like to insert this into a viewset and thus I would prefer the django ORM way. -
Django getting error 403
I'm working on multi file upload. Everything works fine but there is one problem. Files are moving to the directory which i want but when i try to display them i get this error: Forbidden You don't have permission to access /media/taka-se/image026.jpg on this server. Here is views.py: def post(self, request): form = PhotoForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data gallery = cd['gallery'] for image in cd['image']: Photo.objects.create(gallery=gallery, image=image) return redirect(reverse('account:gallery', kwargs={'postid': gallery.pk})) Here is forms.py: class PhotoForm(forms.ModelForm): image = MultiImageField( min_num=1, max_num=25, max_file_size=429916160, ) class Meta: model = Photo fields = ('gallery',) -
Django form not validating when trying to update an existing row from database
I am working on my first Django project. But I get following errors: edit_file template <form method="POST" action="{% url 'edit_file' file.id %}"> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} <div class="form-group row"> <label for="id_version" class="col-sm-3 col-form-label"> File Name </label> <div class="col-sm-4"> {% render_field form.name|add_class:"form-control" %} </div> </div> <div class="form-group row"> <label class="col-sm-3 col-form-label">File Path</label> <div class="col-sm-4"> {% render_field form.directory_path|add_class:"form-control" %} </div> </div> <div class="form-group"> {% render_field form.script_code|add_class:"form-control" %} <pre id="id_script_code" style="height: 40pc;">{{ form.script_code }}</pre> </div> <button type="submit" class="btn btn-success mr-2">Save Changes</button> <a href="{% url 'list_files_from_version' file.version_id %}" class="btn btn-light">Back</a> </form> Views.py def edit_file(request, id): instance = get_object_or_404(File, id=id) if request.method == "POST": form = EditFileForm(request.POST, instance=instance) # , instance=file if form.is_valid(): print('Form validation => True') form.save() return HttpResponse('<h1> Looks pretty damn good! </h1>') else: print('Form validation => False') file = File.objects.latest('id') context = {'file': file, "form": form} return render(request, 'edit_file.html', context) else: instance = get_object_or_404(File, id=id) form = EditFileForm(request.POST or None, instance=instance) file = File.objects.latest('id') context = {'file': file, "form": form} return render(request, 'edit_file.html', context) forms.py class EditFileForm(ModelForm): # field_order = ['field_1', 'field_2'] class Meta: print("forms.py 1") model = File fields = ('name', … -
django-pyodbc-azure no module named 'sql_server'
I am attempting to use a corporate SQL Server as the backend for my Django project with Python 3.5.2. I have installed Django 2.0.3, pyodbc==4.0.22, django-pyodbc-azure 2.0.3, pypiwin32==219 (pip freeze below). I have also configured DATABASES in my site's settings.py (see below). When attempting to run the server I get the following error: No module named 'sql_server'. I referenced other questions, the most relevant of which appeared to be: No module named sql_server.pyodbc.base, which concluded that the django-pyodbc-azure and Django versions needed to be identical. This did not solve my problem, however; the same error persists. Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "C:\Users\K5SH\venv\lib\site-packages\django\core\management\__init__.py" , line 338, in execute_from_command_line utility.execute() File "C:\Users\K5SH\venv\lib\site-packages\django\core\management\__init__.py" , line 312, in execute django.setup() File "C:\Users\K5SH\venv\lib\site-packages\django\__init__.py", line 18, in se tup apps.populate(settings.INSTALLED_APPS) File "C:\Users\K5SH\venv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\K5SH\venv\lib\site-packages\django\apps\config.py", line 198, i n import_models self.models_module = import_module(models_module_name) File "C:\Users\K5SH\AppData\Local\Programs\Python\Python35-32\lib\importlib\__ init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, … -
Add django-material app/view at root/home (http://www.example.com/)
I try to understand how it is possible to do the same as on http://demo.viewflow.io with the view 'Introduction'. How I can integrate a ?app or view? on root/home of my domain in the menu of the django-material layout? see http://www.schneewind.ch/stackoverflow/demo.viewflow.io.png I tried different ways, but not yet found the right one. I thing I didn't understand something right (perhaps on django-layer?) -> Not the same but similar idea for worldpress: how to make this http://www.example.com/demo To http://www.example.com -
Django Form Add Button Sending The Same Response
My product display page add to cart buttons are adding the same product. It is passing the same product_id. For ex: when I add Charging port then LCD Assembly gets add. Prdocut display Following is the template <form role="form" class="product-form clearfix" method="post" action {% url 'product:add-to-cart' product_id=product.product.pk slug=product.product.get_slug %}" novalidate> {{ product.product.pk }} {% bootstrap_field product.form.variant %} <div class="product__info__quantity"> {% bootstrap_field product.form.quantity %} </div> <div class=""> <button id="{{ product.product.pk }}" class="btn primary"> {% trans "Add to cart" context "Product details primary action" %} </button> </div> </form> Following is the views.py def home(self, request): products_display = [] products = products_for_homepage()[:8] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) webpage_schema = get_webpage_schema(request) for product, availability in products: form = handle_cart_form(request, product, create_cart=True)[0] products_display.append({ 'product': product, 'availability': availability, 'form': form }) Following is the handle cart form def handle_cart_form(request, product, create_cart=False): if create_cart: cart = get_or_create_cart_from_request(request) else: cart = get_cart_from_request(request) form = ProductForm( cart=cart, product=product, data=request.POST or None, discounts=request.discounts) return form, cart If there is a better way to do this, please guide me. -
I have permission error in ubuntu when I upload media file
as title, when I upload media file, permission error happened. I think I have to change nginx settings, but I dont know how to... this is my nginx setting server { listen 80; server_name ~~~; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/qing; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/qing.sock; } } And this is error log Traceback: File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./accounts/views.py" in signup_mentor 59. mentor.save() File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/db/models/base.py" in save 729. force_update=force_update, update_fields=update_fields) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/db/models/base.py" in save_base 759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/db/models/base.py" in _save_table 820. for f in non_pks] File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/db/models/base.py" in 820. for f in non_pks] File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/db/models/fields/files.py" in pre_save 287. file.save(file.name, file.file, save=False) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/db/models/fields/files.py" in save 87. self.name = self.storage.save(name, content, max_length=self.field.max_length) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/core/files/storage.py" in save 49. return self._save(name, content) File "/home/ubuntu/Env/qing/lib/python3.5/site-packages/django/core/files/storage.py" in _save 236. os.makedirs(directory) File "/home/ubuntu/Env/qing/lib/python3.5/os.py" in makedirs 241. mkdir(name, mode) Exception Type: PermissionError at /accounts/signup/mentor/ Exception Value: [Errno 13] Permission denied: '/home/ubuntu/qing/media/profile/2018/03/18' -
Django 2.0 allauth Facebook 2018
I got Twitter and Google login with Django all-auth. Having issues with Facebook now. Tried every single combination between localhost/127.0.0.1/etc (also went extreme routes by changing my hosts to local.domain.com - even got an SSL thing going as Facebook apparently blocks http access (since March 2018). Got this far... now I get this error Can anyone lead me into the right direction? I'm about to pull my hair out. KeyError at /accounts/facebook/login/token/ 'access_token' Request Method: POST Request URL: https://localhost:8000/accounts/facebook/login/token/ Django Version: 2.0.3 Exception Type: KeyError Exception Value: 'access_token' Addition details: http://localhost:8000/accounts/facebook/login/callback SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', ], 'LOCALE_FUNC': lambda request: 'en_GB', 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': False, 'VERSION': 'v2.5', } } -
Should i use Django or Flask? [on hold]
What i want to achieve: I have a machine learning model on python which predicts a single result i wish to have a website which connects to the machine learning script I want to pass a few parameters entered by the user on the website to the script to predict the result and then send it back to the website which will display it to the user I also want to have User Authentication for my website using django or flask What i know after some research: i need to use a REST API like django or flask. Most guides online were conufusing in the later stages. I am new to python but know the basics and have no past experience in django or flask and i need your suggestions on what to use (if possible guides for the same). All this is for a project and i have limited time to implement the same -
Saving class-based view formset items with a new "virtual" column
I have a table inside a form, generated by a formset. In this case, my problem is to save all the items after one of them is modified, adding a new "virtual" column as the sum of other two (that is only generated when displaying the table, not saved). I tried different ways, but no one is working. Issues: This save is not working at all. It worked when it was only one form, but not for the formset I tried to generate the column amount as a Sum of box_one and box_two without success. I tried generating the form this way too, but this is not working: formset = modelformset_factory( Item, form=ItemForm)(queryset=Item.objects.order_by( 'code__name').annotate(amount=Sum('box_one') + Sum('box_two'))) This issue is related to this previous one, but this new one is simpler: Pre-populate HTML form table from database using Django Previous related issues at StackOverflow are very old and not working for me. I'm using Django 2.0.2 Any help would be appreciated. Thanks in advance. Current code: models.py class Code(models.Model): name = models.CharField(max_length=6) description = models.CharField(max_length=100) def __str__(self): return self.name class Item(models.Model): code = models.ForeignKey(Code, on_delete=models.DO_NOTHING) box_one = models.IntegerField(default=0) box_two = models.IntegerField(default=0) class Meta: ordering = ["code"] views.py class ItemForm(ModelForm): description = … -
Django using NGINX HTTP2 SSL is Brotli Secure?
I'm using NGINX as my web server for hosting my Django application. I've come across GZIP should be turned off if using HTTPS (SSL), as gzipping content via TLS shall open up CRIME/BREACH attack. My question, is does this apply for Brotli as well? -
Django doesn't respect the maxlength widget attribute
I have the following field in model: short_description = models.CharField(max_length=205) and the widget in ModelForm: 'short_description': forms.Textarea(attrs={'rows': '3', 'minlength': 250,'maxlength': 250}) The issue: In HTML, input, Django adds correctly minlength value, but for the maxlength value he get the value from the model field and not the one specified in the widget. <textarea name="short_description" cols="40" rows="3" minlength="80" maxlength="205" required="" id="id_short_description"></textarea> How do I "force" Django to take in consideration what is specified in the widget and not in the model field. -
Passing values from html to python in django
I have an html page that contains a form with 2 input of type text and a submit button.. What i want is to click on the button the values need to be passed into a python program and the program would have a function that sums the two values and then that values needs to be displayed in my html page.. Can anyone plz help. thanx in advance -
How to add few payment methods to django-oscar
I already add cash_on_delivery payment method to my project. But i want to add one more method. How i can do it. At this moment i have code of checkout views like this: class PaymentDetailsView(PaymentDetailsView): template_name = 'checkout/payment-details.html' template_name_preview = 'checkout/preview.html' def get_context_data(self, **kwargs): ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) ctx['signature'] = gateway.hmac_gen(ctx) ctx['amount'] = '%s' % ctx['order_total'].incl_tax ctx['price'] = '%s' % ctx['basket'].lines.all()[0].price_incl_tax ctx['source'] = ctx return ctx # def handle_payment_details_submission(self, request): # # Validate the submitted forms # shipping_address = self.get_shipping_address( # self.request.basket) # address_form = BillingAddressForm(shipping_address, request.POST) # # if address_form.is_valid(): # address_fields = dict( # (k, v) for (k, v) in address_form.instance.__dict__.items() # if not k.startswith('_') and not k.startswith('same_as_shipping')) # self.checkout_session.bill_to_new_address(address_fields) # return self.render_preview(request, billing_address_form=address_form) # # # Forms are invalid - show them to the customer along with the # # validation errors. # return self.render_payment_details( # request, billing_address_form=address_form) def handle_payment(self, order_number, total, **kwargs): reference = gateway.create_transaction(order_number, total) source_type, is_created = SourceType.objects.get_or_create( name='Cash on Delivery') source = Source( source_type=source_type, currency=total.currency, amount_allocated=total.incl_tax, amount_debited=total.incl_tax ) self.add_payment_source(source) self.add_payment_event('Issued', total.incl_tax, reference=reference) Maybe i can make with payment like with adding shipping methods? -
Using signal instance to get last_login from user table
I'm using one of django's in built signals and I want to use the instance passed to my receiver method to get the current users last_login before its updated. from django.db.models.signals import pre_save from allauth.account.signals import user_logged_in from django.dispatch import receiver from ..models import User @receiver(pre_save, sender=User) def isFirstLogin(instance, **kwargs): return instance.email -
django-filter button in template
I'm using the django-filter package. My page displays all books. I have 5 genres. I want someone to be able to click a "scary" button, and have that filter my book list (user shouldn't have to also click "submit", just the genre button). But right now when I click a genre button, it doesn't filter. Unless I use a checkbox widget in my filters.py (commented out), check the box, and then click the genre button, but this looks ugly. Thanks in advance for the help! Filters.py class BookFilter(django_filters.FilterSet): genre = django_filters.ModelMultipleChoiceFilter(queryset=Genre.objects.all(), #widget=CheckboxSelectMultiple) class Meta: model = Book fields = ['genre'] book_list.html <form method="get"> <ul> {% for genre in filter.form.genre %} <li> <button type="submit" class="button"> {{ genre }} </button> </li> {% endfor %} </ul> </form> -
django bootstrap datetimepicker
i am trying to implement the datepicker using the django bootstrap datepicker widget, but the datepicker is not showing on the webpage ("welcome.html) i have passed the form to the views and called the form in the webpage any help will be appreciated forms.py class DateForm(forms.Form): todo = forms.CharField( widget=forms.TextInput(attrs={"class":"form-control"})) date_1=forms.DateField(widget=DatePicker( options={"format": "mm/dd/yyyy", "autoclose": True })) def cleandate(self): c_date=self.cleaned_data['date_1'] if c_date < datetime.date.today(): raise ValidationError(_('date entered has passed')) elif c_date > datetime.date.today(): return date_1 def itamdate(self): date_check=calendar.setfirstweekday(calendar.SUNDAY) if c_date: if date_1==date_check: pass elif date_1!=date_check: raise ValidationError('The Market will not hold today') for days in list(range(0,32)): for months in list(range(0,13)): for years in list(range(2005,2108)): continue views.py def imarket(request): #CREATES A FORM INSTANCE AND POPULATES USING DATE ENTERED BY THE USER if request.method=='POST': form = DateForm(request.POST or None) #checks validity of the form if form.is_valid(): itamdate=form.cleaned_data['date_1'] return HttpResponseRedirect(reverse('welcome.html')) return render(request, 'welcome.html', {'form':form}) welcome.html {% extends 'base.html' %} {% load bootstrap %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script> {% block content %} <title>welcome</title> <form action = "{% url "imarket"}" method = "POST" role="form"> {% csrf_token %} <table> {{form|bootstrap_horizontal}} </table> <div class = "form-group"> <input type ="submit" value= "CHECK" class="form control"/> </div> </form> {% endblock %} -
Django URLs management
I'm a full beginner on Django. Therefore, I'm sorry if my question is not making so much sense. I'm studying Django tutorial - step 1. I installed properly Django and created my first Django project named 'vanilla'. The urls.py script of the vanilla project is from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] When I start Django with this 'vanilla' project and start the development server at http://127.0.0.1:8000/, I correctly see the expected page with a correct. In a second project that I named 'djtutorial', I created as requested in Django tutorial - step 1 a 'polls' app. As requested, I modified urls.py file in djtutorial\polls which now has following content: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] If I start the server the url http://127.0.0.1:8000/polls/ is working properly. However, if I launch the root url of the site (i.e. http://127.0.0.1:8000/), I now have a 404 error. Why is the 'root url' of the site now hidden? -
Content Tools on Django gives forbidden errors
I tried to install Content Tools on my Django site using this github project, and I've come across an issue. After editing the page using content tools, it tells me it failed to save (indicated with a big X on the screen), I went into the console and found a 403 Forbidden error when it tries to access /api/add My suspicion is a difference in the code in api.js and my runserver arguments api.js API.domain = 'http:\\52.XX.XXX.1:80' command to run server python3 manage.py runserver 0.0.0.0:80 -
Django, html, css - Footer style applies to all the body
I have a webpage structured as follows and I want to have a background-color: red property to apply only to the footer. <body> {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %} {% block content %}<!-- default content text (typically empty) --> <!-- Navigation Bar --> <section class="navbarSection"> <div class="topnav" id="myTopnav"> ... </div> </section> <!-- End of Navigation Bar --> <!-- Articles --> <section class="articleSection"> <div class="articles" id="myArticles"> {% for article in articles %} ... {% endfor %} </div> </section> <!-- Footer --> <footer id="site-footer"> <div id="footer1"> <p> footer text </p> </div> </footer> <!-- End of Footer --> </body> The footer is styled as follows #footer1 { background-color: #aa2222; } At the moment the page is displayed with all the body with background-color:red instead of only the footer. It seems to be related to Django because using the code in a web editor it applies the background color properly. Could you please help? -
How can I link a virtualenv Django environment to my website in AWS EC2?
I have a website deployed on AWS EC2 using nginx (right now it only points to the Public DNS - http://ec2-XX-XX-XXX-XX.us-east-1.compute.amazonaws.com and I want to use Django to build out the back-end for storing data from the website. I'm following these instructions from Mozilla to build out a Django app and while it is going well, I obviously cannot use http://127.0.0.1:8000/ to view the Django site, since: Django is running on a virtual environment within EC2 and EC2 redirects to the website above. My question is: how can I link the Django app I create in the virtualenv of EC2 with the nginx website I've created on EC2?