Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django_Hosts Import Error
What I'm trying to do is make the website redirect to www(eg"example.com" to "www.example.com") I used pip to install django_hosts, and then followed the documentation on the website Here is my settings.py file: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'lsjz5tm#+0(99cv@mg=himl8=4w-vd^qq07jpd3d5278!hv06x' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ # 'example.com', # 'www.example.com', '*', ] # Application definition INSTALLED_APPS = [ 'Reviews', 'Contact', 'Lessons', 'News', 'QNA', 'Home', 'About', 'Pupils', 'Website', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party 'django_hosts' ] MIDDLEWARE_CLASSES = [ 'django_hosts.middleware.HostsRequestMiddleware' 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_hosts.middleware.HostsResponseMiddleware' ] ROOT_URLCONF = 'mysite.urls' ROOT_HOSTCONF = 'mysite.hosts' DEFAULT_HOST = 'www' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
Django model not saving changes via save_model method
I have overridden the admin save_model function to do some extra logic based on custom buttons I have added to the admin site. The save_model function is shown below: def save_model(self, request, obj, form, change): obj.last_updated = timezone.now() send_request = False if request.method == 'POST' and "text_gig" in request.POST: if not obj.status: obj.status = Event.APPROVED send_request = True messages.success(request, 'Event has been approved and tweeted!') elif _check_tweet(request, form, obj): if change: obj.tweet = form.cleaned_data.get('tweet') send_request = True messages.success(request, 'Event has been tweeted!') obj.save() if send_request: send_text.delay(obj.id, phone=False) The instance's "last_updated" should change to the current time, and the "status" field should be set from NULL to the defined constant. However, this is not happening. I know the code flow is proper because I receive the "Event has been approved and tweeted!" message, and because my "send_text" task is firing. Furthermore, I have output from debug logs showing the SQL UPDATE: UPDATE `booking_event` SET `reference` = '046A', `recorded` = '2017-02-26 15:59:29', `customer_id` = 1, `start` = '2017-02-28 17:00:00', `end` = '2017-02-28 20:00:00', `num_bartenders` = 1, `rate` = '20.00', `location` = 'xxx', `attendees` = 100, `description` = 'dsd', `special_requests` = 'dsd', `minimum_training_id` = 2, `contracted` = NULL, `assigned` = NULL, `signed` = … -
How to make User able to create own account with OneToOne link to Profile - Django
so I'm stuck with a particular issue regarding user creation. On my site I would like the user to be able to create his/her own user account including username and password + the profile information in the same form. I have looked at the post_save options but it's not working. As described on https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone the view requests the instance=request.user, however this part gives me an error 'AnonymousUser' object has no attribute '_meta'. I am also trying to implement this as a class view, which is different to how it's done on the website. However the function based view gives the same issue. It seem like his way of doing it requires the user to be logged in already. Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) organisation = models.CharField(max_length=100, blank=True) occupation = models.CharField(max_length=100, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Views.py class IndexView(View): template_name = 'homepage.html' form_class = UserCreationForm profile_form = ProfileForm success_url = '/' def post(self, request): user_form = self.form_class(request.POST, instance=request.user) profile_form = self.profile_form(request.POST, instance=request.profile) if user_form.is_valid() and profile_form.is_valid(): user_id = user_form.save() profile_form.save(commit=False) profile_form.user = user_id profile_form.save() return render(messages.success, request, … -
nginx reverse proxy for nginx+gunicorn+django server
A django app is running on django_server.com and I can't get the nginx reverse proxy working to server that app. When connecting directly to the django server, let's say django_server.com/ every thing works fine, the user is redirected to django_server.com/user/login. The app is running on gunicorn + nginx (upstream and unix socket) Now all traffic has to go over one server, lets say https://www.reverse_proxy.com/django_app, and I can not get this connection working. The connection to reverse_proxy.com is https, the connection from reverse_proxy.com to django_server.com is http. The reverse_proxy is serving several other site and works well, I also tested a connection to the django_server.com with a static html-site, that works, too. So the problem seems so be the django-side, but I can't figure out the error. There are no error-messages in the error logs of both nginxs, it is simply an 404 error. Here is the nginx-configuration on the django_server.com: upstream gunicorn_socket { server unix:/home/django/w_plan/django/fakw/fakw.sock fail_timeout=0; } server { server_name django_server.com; listen 80 default_server; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://gunicorn_socket/; } } And here the reverse_proxy: ... location /django_app { proxy_pass http://django_server.com:80/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto … -
Models list as choices in a Model
Hello there I'm working on small personal project for fun and I need to have all models as choices in a field in a model, I made a function to get all models names: def get_models(): choices = [ct.model_class().__name__ for ct in ContentType.objects.all()] return choices and my Model: class Action(models.Model): model = models.CharField(max_length=70, null=False, blank=False, choices=lazy(get_models())) act = models.CharField(max_length=3, null=False, blank=False, choices=ACTIONS_CHOICES) description = models.TextField(max_length=400, null=True, blank=True) count = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.config class Meta: unique_together = (('model', 'act'),) But when I run the code I have this error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I tried to get the models differently using: from django.apps import apps models = apps.get_models() But I had the same error again, what I did understand is that I'm trying to get the models before that Django can load them, my question is: is there any way to work around this issue? thanks -
Django React with i18n
Wondering what is the best practices to use django with React when i18n needed. Currently I'm loading javascript_catalog on global scope. all the translations controlled by django i18n. From react components I'm using gettext django javascript catalog function to translate all the necessary texts. For localization i'm also using django i10n support provided by javascript_catalog. anyone have better practices for this using i18n in both django and react -
What is the default value of django's model field options ``blank`` and ``null`` when they're not set?
In the documentation, I was not able to find an answer to this. If I want a field to be left blank, do I have to explicitly set blank=True ? -
I am getting Error only in css file in django 1.10
https://github.com/rafaellg8/IV-PLUCO-RLG/blob/master/pluco/static/css/stylish-portfolio.css may be there is error in referring static file from css. plz check it -
Extending a model in Django
I am trying to create a custom user model. This model has to extend another model and also link to built-in django User. Currently I have: class Entity(models.Model): name = models.CharField(max_length=256, null=True, blank=True) class Profile(Entity): user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() But when I try to create a user I get an error: UNIQUE constraint failed: project_profile.entity_ptr_id. Do I need to add another function to create entity first? Or should I structure my models in another way? -
should I learn Python and Django or Java first? [on hold]
So I'm starting to learn Android programming and got all the tools but I kinda don't have any idea how they work so I dunno what should I do first. I've got a kinda simple idea to work on as my first app and for that I need to know server-side programming ( which I also don't have any idea about...ikr) a friend of mine recommended Python and Django for server side programing. and I know I should learn Java for Android development. -so what I'm wondering is > Which language should I learn first? < -or in other words , when dealing with apps that involve both server side and client side stuff , where should I start coding? the server side or the client side ? (and sry for bad english) -
AssertionError: The `.update()` method does not support writable nestedfields
I have a DeviceSerializer and DeviceGroupSerializer. DeviceSerializer has ios field as foreignkey and i have used save_ios, create and update function for it to save in database along with devices. But i need to add one more field of device_group and the relation of device_group and device is one to many(a device can be on one group but a group can have multiple devices). Here is my serializer class DeviceGroupSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() class Meta: model = DeviceGroup fields = ('name',) class DeviceSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) ios = DeviceIOSerializer(read_only=False, many=True, required=False) device_group = DeviceGroupSerializer(required=False) class Meta: model = Device fields = ('id', 'name', 'description', 'ios', 'device_group') def save_ios(self, device, ios): for io in ios: token = io.pop('token', None) if token is None: DeviceIO.objects.create(device=device, **io) else: DeviceIO.objects.filter(token=token, device=device).update(**io) def update(self, instance, validated_data): ios = validated_data.pop('ios',[]) instance = super(DeviceSerializer, self).update(instance, validated_data) if len(ios): self.save_ios(instance, ios) return instance def create(self, validated_data): ios = validated_data.pop('ios',[]) instance = super(DeviceSerializer, self).create(validated_data) if len(ios): self.save_ios(instance, ios) return instance When i try to create a new group, i get following error AssertionError: The .update() method does not support writable nestedfields by default. Write an explicit .update() method for serializer device_api.serializers.DeviceSerializer, or set read_only=True on nested serializer … -
Redirect to Bootstrap modal instead of error404, Django request.user
I am struggling with an request.user statement in Django. Through those all hours what I wanted to achieve is: Only the "user" (author) of the ShiftReport (simply a post) should be able to edit the ShiftReport. So far I have managed to do that, and when I am logged in as another user I receive an error 404, whereas logged in as a post creator I am able to edit the post - Great!. However, instead of that 404 Error I would just like to throw a Bootstrap modal saying access denied. My 'views.py': def update(request, shiftreport_id=None): title = 'Edit Shift Report by' instance = get_object_or_404(ShiftReport, pk=shiftreport_id, user=request.user) form = shiftreportForm(request.POST or None, request.FILES or None, instance=instance) confirm_message = None if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() title = "Thanks" confirm_message = "Shift Report has been updated!" form = None context = { "title": title, "instance": instance, "form": form, "confirm_message": confirm_message, } return render(request, 'shift/edit.html', context) My 'detail.html': <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-center"> <li><a href="{% url 'new' %}">New Shift Report</a></li> <li><a href="{% url 'all' %}">All Shift Reports</a></li> {% if not request.user %} with above statement I can edit my own post and I get Error404 … -
How to redirect 404 requests to homepage in Django single page app using Nginx?
I have a django single page application. Currently when you visit a url on the site that doesn't exist a 404 error is displayed. However, in this case I want to redirect to the homepage of the site. I am not sure if I should how to do this with Nginx, or is there a way to do this within Django? Attached is my Nginx file below. I tried using the below setting but it did not work. error_page 404 = @foobar; location @foobar { return 301 /webapps/mysite/app/templates/index.html; } upstream mysite_wsgi_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/webapps/mysite/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name kanjisama.com; rewrite ^ https://$server_name$request_uri? permanent; } server { listen 443; server_name kanjisama.com; ssl on; ssl_certificate /etc/letsencrypt/live/kanjisama.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/kanjisama.com/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; client_max_body_size 4G; access_log /webapps/mysite/logs/nginx_access.log; error_log /webapps/mysite/logs/nginx_error.log; location /static/ { alias /webapps/mysite/app/static/; } location /media/ { alias /webapps/mysite/media/; } location / { if (-f /webapps/mysite/maintenance_on.html) { return 503; } proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $host; proxy_redirect off; # Try to serve static files … -
C# HttpClient PostAsync won't work with django rest framework
in Django (DRF) in test.views.py class TestAPIView(APIView): permission_classes = (AllowAny,) def post(self, request, format=None): print(request.data) return Response(request.data) in test.urls.py from django.conf.urls import url from .views import TestAPIView urlpatterns = [ url(r'^test/$', view=TestAPIView.as_view()), ] as you can see, my test url should return the post data. and which does works well in browsable api and Unity WWW(something like httpclient which unity provides). but it wont work with HttpClient PostAsync(or SendAsync either) this is my C# code in Xamarin / C# Post newPost = new Post { Title = "asdfasfa", Content = "asdfasffasf" }; var content = JsonConvert.SerializeObject(newPost); Debug.WriteLine(content); var response = await _client.PostAsync("http://127.0.0.1:8000/test/", new StringContent(content)); var responseString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseString); and the results from the console.... in C# Console the commented string was written by me. not from the console {"Id":0,"Title":"asdfasfa","Content":"asdfasffasf"} // <- this is the sent data. Thread started: #6 Thread started: #16 Thread started: #17 {} // <- and the received data and... in Django(DRF) Console [26/Feb/2017 13:37:34] "POST /account/test/ HTTP/1.1" 200 2 <QueryDict: {}> where did my post datas gone??? django received <QueryDict: {}> and this only happens for httpclient. and maybe only with django. i tested it with => https://jsonplaceholder.typicode.com/posts and the post creation just worked … -
How do I write a Python test that checks that my code imports a module
I have a Python project that relies on a particular module, receivers.py, being imported. I want to write a test to make sure it is imported, but I also want to write other tests for the behaviour of the code within the module. The trouble is, that if I have any tests anywhere in my test suite that import or patch anything from receivers.py then it will automatically import the module, potentially making the test for import pass wrongly. Any ideas? (Note: specifically this is a Django project.) -
CrispyForm not saving
I am trying to save crispy-form form data to the database however, it does not save, despite all the code after the job.save() executing properly and it redirecting with a success message. I have tried doing a simple job_form.save(commit=True) however that doesn't work either views.py class NewJobPage(LoginRequiredMixin, generic.TemplateView): template_name = 'app/new_job.html' http_method_names = ['get', 'post'] def get(self, request, *args, **kwargs): user = self.request.user if "job_form" not in kwargs: kwargs["job_form"] = forms.JobForm(instance=user) return super(NewJobPage, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): user = self.request.user job_form = forms.JobForm(request.POST, request.FILES, instance=user) if not job_form.is_valid(): messages.error(request, "There was a problem with the form. Check your inputs.") job_form = forms.JobForm(instance=user) return super(NewJobPage, self).get(request, job_form=job_form) else: job = job_form.save(commit=False) job.requester = user.profile_user job.save() messages.success(request, 'Your job has been added!') return redirect('app:jobs') models.py class PrintJob(models.Model): print_id = models.UUIDField(default=uuid.uuid4, editable=False, blank=False, primary_key=True, unique=True, auto_created=True) print_name = models.CharField(max_length=20, verbose_name="Print Name", blank=False) requester = models.ForeignKey(Profile, on_delete=models.CASCADE, editable=False, auto_created=True) notes = models.TextField(verbose_name='Notes', blank=True) file = models.FileField(verbose_name="CAD File", upload_to='cad_files', blank=False) datetime_submitted = models.DateTimeField(editable=False, auto_now_add=True) datetime_actioned = models.DateTimeField(editable=False, blank=True, verbose_name="Job last actioned") job_status = models.CharField(max_length=40, editable=False, blank=True, verbose_name="Job Status") def __str__(self): return format(self.name) class Meta: ordering = ['-datetime_submitted', '-datetime_actioned'] verbose_name = 'Print Job' verbose_name_plural = 'Print Jobs' forms.py class JobForm(forms.ModelForm): def __init__(self, … -
Django conditional require for an entire form
How do I conditionally require the filling of an entire form based on a field of another form that is on the same page? forms.py: from django import forms class OptionForm(forms.Form): """Whether or not the user wants to fill the contact form""" fill_form = forms.BooleanField(initial=True) class ContactForm(forms.Form): name = forms.CharField() email = forms.EmailField() phone = forms.CharField(required=False) # ... and many more fields Specification: If the user ticks the checkbox in OptionForm, it means that he/she wants to fill in ContactForm, so we must make sure that ContactForm is filled and is correct/validates. On the other hand, if the user unticks the checkbox, we should ignore all input in ContactForm. How do I achieve the specification outlined above? I am using function based views. One solution I can think of is to only run is_valid() based on the value of the checkbox. The complication with this is that the rendered html ContactForm's inputs have the required attribute, preventing the user from submitting the form if ContactForm is blank even though the user has unchecked the checkbox. -
Django - Include dynamic tamplates
I want to include dynamic template with include tag. So basically, when I include template with static path, like below, everything is Ok. {% include "stories/Princess_Run_Story/Princess_Run_Story.html" %} And in my case, I transfer this path in value. And using then, exactly the same. {% include story_counter %} But I catch error below, and main point here, that both value are same, even I manually transfer that path from first example. Using engine django: django.template.loaders.filesystem.Loader: C:\Work-Projects\Web\WebWorkBook\templates\'stories\Cave_Monsters_Story\Cave_Monsters_Story.html' (Source does not exist) django.template.loaders.app_directories.Loader: C:\Program Files\Python27\lib\site-packages\django\contrib\admin\templates\'stories\Cave_Monsters_Story\Cave_Monsters_Story.html' (Source does not exist) -
How can I sort my model output in Django?
I'm quite new in the development with django and I hope someone can help me. I have two main models in one view and in one template. Each one of my "main" models has its own "sub" model (with a foreign key). My output is fine and it works so far. My problem is, I would like to sort the sub model of my second main model by name. Is this possible, or what do I need to change this? In my example, I want to sort 'occupant.last_name' by name. I have a picture what it looks like right now: occupant.last_name My models.py class Management[...] class Employee[...] class Houses(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Occupant(models.Model): house = models.ForeignKey(Houses, on_delete=models.CASCADE) last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) room = models.IntegerField(default=0) def __str__(self): return self.first_name My views.py class IndexView(ListView): context_object_name = 'all_management_list' template_name = 'blackboard/index.html' queryset = Management.objects.order_by('order_number') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['Houses'] = Houses.objects.all() # And so on for more models return context My template.html {% for houses in Houses %} <h3>{{ houses.name }}</h3> <table><tbody> {% for occupant in houses.occupant_set.all %} <tr> <td>{{ occupant.last_name }}, {{ occupant.first_name }}</td> <td>{{ occupant.room }}</td> </tr> [...] Thank you so … -
Following the Django Tutorial - but saying 404 not found
I am on the first Django tutorial (https://docs.djangoproject.com/en/1.10/intro/tutorial01/), and I am just nearing the end of the first page. However when I go to localhost:8000/polls, is says 404 this page is not found. It was working fine until I added the code to the python files at the bottom of the page as it tells you to. I have included screenshots of all the code I have typed so far and the error message, and I was wondering whether anyone had any idea about what was wrong. Thanks, MIlo -
HTML Select dropdown with dynamic list in Django ModelForm
In the view : I need to display a dropdown list of years starting from a fixed value (say 2005) to the current year. Now, this list, though dynamic, does not come from the database. Also, I want the list to expand as time goes by. In the model : I want this field to be like an IntegerField(?) which saves values only from 2005 to, say, 3000, and throws a validation error otherwise. What I could do - Make the dropdown as a ChoiceField in the View, and set up a validator for the model. What I want - I want to use ModelForm in Django since this field, along with others in the form maps to the fields of my model. It means that I wont be defining fields in my Form, but only in the model. The question is, therefore, what should my approach be? This I have tried so far- class Member(models.Model): d = int(datetime.datetime.now().strftime("%Y")) ch = [(X,X) for X in range(2005,d)] first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) membership_type = models.IntegerField(validators=[validate_membership_type]) batch = models.IntegerField(choices= ch) This generates the form with desired select field but the values do not change. I replaced 'Years' by 'Minutes' to test … -
Create a list of choices automatically
I am making an on-line theater booking app in django (v1.10.5) and python. models.py: TheaterLocation = [ (1, 'Naharlagun'), ] FloorLevel = [ (1, 'Ground Floor'), (2, 'Balcony'), ] Row = [ ] Column = [ ] class Seat(models.Model): theater_location = models.PositiveIntegerField(choices=TheaterLocation) floor_level = models.PositiveIntegerField(choices=FloorLevel) row_id = models.PositiveIntegerField() column_id = models.PositiveIntegerField() @property def seat_id(self): return "%s : %s : %s : %s" % (self.theater_location, self.floor_level, self.row_id, self.column_id) What I would like to do is, create a list of choices for Row and Column automatically like this: Row = [ (1, 'A'), (2, 'B'), ... ... (8, 'H'), ] Column = [ 1,2,3,4,5, ... , 22 ] How can I achieve like the above? -
Django Cart add transport
I have a working shopping cart. Now I would like to add a variety of transport and cart_detail to me summed up the price of transport to the total cost. It seems to me that it can create a new function in the class Cart in cart.py which will be taken from the database of transport then I have to create a function that will count the cost. Then I think I need to create a form and view and add it to the cart> detail.html. I do not know too much how to do this. this is my cart.py class Cart(object): def __init__(self, request): """ Inicjaliazacja koszyka na zakupy. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # pusty koszyk w sesji cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False, size=None, update_size=False): """ Dodanie produktu i zmiana ilości """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'size': size, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity if update_size: self.cart[product_id]['size'] = size else: self.cart[product_id]['size'] += size self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): """ Usunięcie produktów z koszyka """ product_id … -
Linking to another web page using <a> tag, absolute and relative path concept, I guess
I am trying to link my html files which are under the same folder called "templates". One of the file is called "home.html" which has a link to another html file called "page2.html". The following code works perfectly: <a href="/page2">Click Me</a> But, this gives the url something link this: 127.0.0.1:8000/page2 instead of what I actually want. I want it to be something link this: 127.0.0.1:8000/home/page2. I am making a django web app, but I am new to linking the web pages in the desired form. Is there a way in which I can achieve the above using html tag or using javascript or something from the django app? Is it related to absolute or relative path? If yes, how? Kindly help... -
Django Template Won't Show My Variables That I Pass From My View
I have a Simple Template That Should Print A Variable That I Return From Views.py I return My Variable Using This Command today = datetime.now().date() return render(request,"register.html",{'today' : today}) and I want To Show That Using <p> {{today}}</p> But It Does Not Show The Today Value.