Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tutorial part 3 - bad link or directory structure
I'm doing the tutorial at: https://docs.djangoproject.com/en/2.2/intro/tutorial03/ It says to make a templates directory under the polls application (which is under 'mysite'), such that I have a tree that looks like this: mysite settings.py urls.py wsgi.py polls migrations templates polls index.html views.py models.py admin.py apps.py tests.py urls.py manage.py In the template they want me to write: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available</p> {% endif %} The page loads, but if I click the link it wants to take me to 'localhost:8000/polls/polls/1' and that does not exist. There are one too many '/polls' Question is, was the template directory supposed to go one level higher, under mysite? or should be not have '/polls' in the hyperlink? Despite their little explanation, I do not understand why we'd want to have 'polls/templates/polls'. It seems to me that we can tell it is polls if it is under polls already. -
Nginx Serve React build and proxy_pass Django Rest api server
domain.conf looks like this I am proxy passing the Django API server using Nginx. Nginx uses letsencrypt SSL certificates and is currently listening on port 80 and 443. Nginx perfectly serves the react build files while accessing the Django API using Axios in react app results in 502 bad gateway. Axios is trying to access "/api/v1/" as baseURL. server { listen 80; listen [::]:80; location /.well-known/acme-challenge/ { root /var/www/certbot; } return 301 https://example.com$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # redirects www to non-www. wasn't work for me without this server block return 301 https://example.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name example.com www.example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { root /var/www/frontend; try_files $uri $uri/ /index.html; } location /api/ { proxy_pass http://localhost:8000; proxy_redirect default; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } part of docker-compose.yml looks like this backend: build: context: . dockerfile: dockerFiles/backend/DockerFile tty: true ports: - "8000:8000" expose: - 8000 volumes: - ./backend:/backend env_file: - backend/.env depends_on: - db frontend: image: node:latest command: sh start.sh working_dir: /frontend tty: true volumes: … -
Django Webpack Loader Breaking Vue Router Links
Short Version When I visit localhost my django/vue app renders fine. But when I click into a link, rather than being brought to localhost/about I'm brought to http://localhost/http:/0.0.0.0:8080/about because of my webpack and vue.config.js settings. Details I have an application running (in docker-compose) Django on the backend and Vue on the frontend. The app uses django-webpack-loader and webpack-bundle-tracker to render the application in Django. # Django settings.py WEBPACK_LOADER = { "DEFAULT": { "CACHE": DEBUG, "BUNDLE_DIR_NAME": "/bundles/", "STATS_FILE": os.path.join(FRONTEND_DIR, "webpack-stats.json"), } } # Django urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.views.generic import TemplateView urlpatterns = [ path("admin/", admin.site.urls), re_path("^.*$", TemplateView.as_view(template_name="application.html"), name="app"), ] if settings.DEBUG: urlpatterns = ( urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ) <!-- Template --> {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="/favicon.ico"> <title>My Website</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"> </head> <body> <noscript> <strong>We're sorry but this application doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"> <app></app> </div>{% render_bundle 'app' %}<!-- built files will be auto injected --> </body> </html> // vue.config.js const BundleTracker … -
Django Tempus Dominus TimePicker Format
When I submit a form after picking a time using the django-tempus-dominus TimePicker widget, I receive no error, but the form is not saved to the database, and does not show up in the admin page. I receive a visual browser indication that something is incorrect with my TimeFields. I can successfully create a new form from the admin page, and only see the issue when submitting from my form page. I'm not sure whether this is an issue with the 'format' of the TimePicker widget in my forms.py, an issue with my TIME_INPUT_FORMATS in my settings.py, or something else. If I use a DateTimeField with a DateTimePicker widget for start_time and end_time, and change the 'format' in my widget to 'YYYY/MM/DD hh:mm: A', instead of using a TimeField with a TimePicker widget, the form works correctly, and when submitted, can be viewed from the admin page. In my settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Kentucky/Monticello' DATETIME_INPUT_FORMATS = ['%Y/%m/%d %I:%M %p', ] DATE_INPUT_FORMATS = ['%Y/%m/%d', ] TIME_INPUT_FORMATS = ['%I:%M %p', ] USE_I18N = True USE_L10N = False USE_TZ = True In my models.py: start_time = models.TimeField( verbose_name="Start Time", help_text="Time the issue first occurred.") In my forms.py: from django import forms … -
Getting Django channel access in Celery task
I have a Django app that's using channels to monitor a WebSocket to kick off backend tasks in Celery. It currently sleeps for a given amount and then returns true. The problem is I don't know how to get access to the WebSocket from within the celery task so I can notify the UI once it's done. celery==4.3.0 channels==2.2.0 Django==2.2.4 django-celery-results==1.1.2 djangorestframework==3.10.2 my tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task import time @shared_task def gotosleep(timeInSecs): time.sleep(timeInSecs) return True My consumer.py from channels.generic.websocket import WebsocketConsumer import json from access.tasks import gotosleep class AccessConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] if message.isnumeric() == True: print("------------------------------------------------------") print(message) gotosleep.delay(int(message)) self.send(text_data=json.dumps({ 'message': 'We are dealing with your request' })) else: self.send(text_data=json.dumps({ 'message': 'Give me a number' })) Any Ideas? Many Thanks -
How to call a Python script in a Django server from JavaScript?
Salut! I have a HTML running properly in a Django server, also I have a function in a Python file which send an e-mail. I would like to execute this function when an submit input is clicked. So, how can I call this function using JavaScript? I've read about using AJAX, but I think that this could be code easily. Am I wrong? -
How I can show http 404 with djangofilterbackend?
django rest framework is showing http 202 ok when I set a wrong value and I want to show http 404 on the api django rest framework, when set a wrong value in djangofilterbackend but I don't know how to implement it. my views.py: from rest_framework import viewsets from .models import Producto from .serializers import ProductoSerializer from django_filters.rest_framework import DjangoFilterBackend class ProductoViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ['Codigo_Producto'] queryset = Producto.objects.all() serializer_class = ProductoSerializer my serializers.py: from .models import Producto from rest_framework import serializers, viewsets class ProductoSerializer(serializers.ModelSerializer): Nombre_Producto = serializers.SerializerMethodField class Meta: model = Producto fields = [ 'id', 'Nombre_Producto', 'Codigo_Producto', 'Precio_sugerido', 'stock', ] def get_Producto_name(self,obj:Producto): return obj.Producto.get_full_name() urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework import routers from GestionadorApp.views import ProductoViewSet # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register('Producto', ProductoViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('api/', include(router.urls)), path('admin/', admin.site.urls), ] -
Is there a way to get around 'NoneType' object has no attribute 'DoesNotExist'
I am trying to render the same page "billing" but with different variables depending on if the user have an active subscription or not. The problem is that I get 'NoneType' object has no attribute 'DoesNotExist' when I try to make an exception. I have tried to use if membership is False: return redirect without success. @login_required(login_url="/login") def billing(request): membership = False cancel_at_period_end = False user = request.user pay = payment.objects.filter(user=user).last() if request.method == 'POST': stripe.api_key = settings.STRIPE_SECRET_KEY #attempting cancelling subscription subscription = stripe.Subscription.retrieve(pay.stripe_subscription_id) subscription.cancel_at_period_end = True pay.cancel_at_period_end = True cancel_at_period_end = True pay.paid = False subscription.save() pay.save() messages.success( request, "Thankyou, for using our services Your membership will run to the end of your billing cycle.") else: try: if pay.paid: membership = True if pay.cancel_at_period_end: cancel_at_period_end = True except pay.DoesNotExist: membership = False return render(request, 'billing.html', {'membership': membership, 'pay': pay, 'cancel_at_period_end': cancel_at_period_end}) Traceback: File "/Users/iamsuccessful/totdapp-2/totdapp/views.py" in billing 94. if pay.paid: During handling of the above exception ('NoneType' object has no attribute 'paid'), another exception occurred: File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, … -
query database via foreignkey
I'm querying database: def get_queryset(self): queryset = {'test_suites': TestSuite.objects.filter(user__id=self.request.user.id), 'username': self.request.user)} return queryset from this model field: class TestSuite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... ... User here is the auth User model from Django. I'm trying to filter data from TestSuite by its user's id. Keep getting error: Cannot resolve keyword 'user' into field -
How to identify the source of a NoReverseMatch error in Django?
I am learning the django framework and want to create a webstore where User's who are designated as 'artists' can post to the webstore. To avoid confusion thcWebsite is the PROJECT NAME. thcStore is an APP in the project! I am receiving the following error when trying to load localhost:8000/thcStore/ NoReverseMatch at /thcStore/ Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['thcStore/(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] Request Method: GET Request URL: http://localhost:8000/thcStore/ Django Version: 2.2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['thcStore/(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] Exception Location: C:\Users\TAHAAR~1\Envs\MYPROJ~1\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 the following is the error Traceback Environment: Request Method: GET Request URL: http://localhost:8000/thcStore/ Django Version: 2.2.2 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'cart.apps.CartConfig', 'orders.apps.OrdersConfig', 'accounts', 'payment.apps.PaymentConfig', 'thcStore'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Template error: In template C:\Users\Taha Arif\Desktop\Web Development\Personal Website\django_THC\thcWebsite\templates\base.html, error at line 51 Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['thcStore/(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] 41 : <div class="dropdown-menu" aria-labelledby="navbarDropdown"> 42 : <a class="dropdown-item" href="{% url 'accounts:user_profile' user.display_name %}">Profile</a> 43 : <a class="dropdown-item" href="#">Settings</a> 44 : <a class="dropdown-item" href="{% url 'accounts:thanks' %}">Logout</a> 45 : </div> 46 : {% … -
Django DRF- OneToOneField How to limit unique User to the type of UserAccount
Problem I am writing an app that has two different type of user accounts (Students and Teachers) that which links my base user (which is a custom user inherited from django.contrib.auth.models.AbstractUser) using a OneToOneField. when working with django rest framework Create view using the CreateModelMixin, I was able to create a Student account using a just created base user, THEN I was able to use the same base user to create a Teacher account. Only one type of user (either teacher or student) should be created using one unique base user However that is not the case, I can now create both a student and a teacher account with just one base user. Background So I have the following data structure below in my django app to describe the structure of my users auth.models.User accounts.models.CustomUserModel (inherited from AbstractUser) student.models.StudentModel (OneToOne to CustomUserModel) teacher.models.TeacherModel (OneToOne to CustomUserModel) with the following to be the model schema for StudentModel, and TeacherModel students.models.StudentModel.py class StudentModel(models.Model): # settings.AUTH_USER_MODEL = accounts.CustomUserModel user = models.OneToOneField( settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) teachers.models.TeacherModel.py class TeacherModel(models.Model): # settings.AUTH_USER_MODEL = accounts.CustomUserModel user = models.OneToOneField( settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) students.api.views.py class StudentUserCreateListSearchView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'id' serializer_class = StudentUserSerializer def perform_create(self, serializer): serializer.save() Question How … -
Handle mutitple forms in django template for loop
I am facing problems handling forms in django template for loop using jquery {% for comment in commets %} <!-- reply to comment --> <form id="replyform" action="" method="POST"> <input type="hidden" name="comment-id" value="{{comment.id}}"> <textarea id="text"> </textarea> </form> {% endfor %} <script> $("#replyform").submit(function(event){ event.preventDefault() var gettext= $("#text",this).val(); }) </script> Since the form is in a for loop, it there for means more than one form is created, depending on the number of comments present. The problem arises when i click the submit button, my jquery submit function is not working , but works only for the first form created in the for loop. How can i go about making all the forms created work with jquery submit. -
Creating a function in the view. "Referenced before assignment"
I'm trying to create a simple function to receive my request data. Well i create: def get_request(field_name): data = request.GET.get('%s'%(field_name), False) return data This raises the following exception: local variable 'brand' referenced before assignment But when i using in my view data = request.GET.get('field_name', False) all works correctly. What is missing in my function to make it work in my views.py file.My view.py using view with look like this: def home(request) get_request(field_name) return render(request, 'home.html') Any help will be appreciated. -
Django return with params
I have reset form and verif form first time reset form is render, and after user submit it will render verif form (at same view). def get(self, request): reset_form = ResetPasswordForm() verification_code = VerificationCode() return self.render_to_response({ 'reset_form': reset_form, 'verification_code': verification_code, 'base_url': settings.BASE_URL, }) def post(self, request): reset_form = ResetPasswordForm(request.POST) verification_code = VerificationCode() if reset_form.is_valid(): messages.success( request, _('Your reset password request has been processed, please check your email.')) verif = False elif verification_code.is_valid(): messages.success( request, _('Code Valid')) verif = True return self.render_to_response({ 'reset_form': reset_form, 'verification_code': verification_code, 'verif': verif, 'base_url': settings.BASE_URL, }) template.html {% if verif %} {% crispy verification_code %} {% else %} {% crispy reset_form %} {% endif %} -
Simple connection of Angular login to Django authentication
I can't seem to find anywhere that simply explains how I can link an Angular login form and take advantage of the Django login/user authentication side of things. I want to make my app require a login before managing any data. The post/delete requests already don't go through if not signed in but you can still access and press the buttons. If this is a repeated thread then I apologise but I couldn't seem to find what I need? I might just be thinking about it the wrong way, any help appreciated! -
How to pass image to requests.post in python?
Sorry Guys, i am new to Django, i am stuck with images upload. what i am doing is, i have a REST_API for image upload. I pass the image and inside API get that image by using request.FILES['fileToUpload']. Now i have an external API, which uploads image on my behalf, that's API is working fine on postman. Here is path of that API. http://164.68.110.65/file_load.php But in Django. i am not able to pass image to this API. i have tried many ways. like these. image = request.FILES['fileToUpload'] temp = Image.open(image) byte_io = BytesIO() temp.save(byte_io, 'png') files = {'fileToUpload': byte_io.getvalue() } response = requests.post( self.URL, files=files) print(response.status_code, response.content, response.reason) but it always giving me error that image format is not matched. can you please tell me, in python requests, how we should pass images or files that are got my request.FILES['file_name_any']. Thanks. I will be very thankful for your favor. -
Django tried these URL patterns error 404
my site used to be ok but since I moved my website from my old server to new one suddenly my inner pages does not appear to work (my main page works ok) and I get 404 error with saying none of url patterns match the link. I think I should change something due to changing the server but I don't know what. this is my primary urls.py: urlpatterns = [ url(r'^',include('BestOfBrands.urls')), url(r'^admin/', admin.site.urls), # url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^accounts/', include('allauth.urls')), url(r'^search/', include('haystack.urls')), ] and this is my urls.py file which is in "BestOfBrands" Folder (my webapp folder): urlpatterns= [ url(r'^$', views.index, name='index'), url(r'^(?P<cg>[-\w]+)-Category/$', views.category, name='category'), url(r'^(?P<cg>[-\w]+)-Category/(?P<scg>[-\w]+)-SubCategory/(?P<s2cg>[-\w]+)-Brands/$', views.sub2category, name='sub2category'), url(r'^(?P<cg>[-\w]+)-Category/(?P<scg>[-\w]+)-SubCategory/(?P<s2cg>[-\w]+)-Brands/(?P<br>[-\w]+)/$', views.brand, name='brand'), url(r'^(?P<sub2category_id>[0-9]+)/vote/$', views.vote, name='vote'), url(r'^(?P<brand_id>[0-9]+)/comment/$', views.comment, name='comment'), url(r'^(?P<comment_id>[0-9]+)/replycomment/$', views.replycomment, name='replycomment'), url(r'^(?P<s2url>[-\w]+)/addbrand/$', views.addbrand, name='addbrand'), url(r'^(?P<usern>[-\w]+)-Profile/$', views.profile, name='profile'), url(r'^Change-Avatar/$', views.changeavatar, name='changeavatar'), url(r'^upload-avatar/$', views.uploadav, name='uploadav'), url(r'^(?P<comment_id>[0-9]+)/like/$', views.like, name='like'), url(r'^(?P<rcomment_id>[0-9]+)/likereply/$', views.likereply, name='likereply'), ] -
How to PATCH Django Test Server with cURL
In my API, I have the following dynamics: POST a processing request to the API. Do some processing in the background. When the processing is done, a computer will PATCH the API's original request status field with cURL. These steps do work when I test them with a normal server, i.e., python manage.py runserver. However, when I try to automate tests within Django, I get: curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused Port 80 is what is specified under the django.test.client module with 'SERVER_PORT': '80', so I really don't get why that wouldn't work. -
Django form modelmultiplechoicefield
I filtered and listed matches but when I try to select and add matches, the matches I have selected are not added. views.py def creategame(request,tournamentslug): form=GameForm(request.POST or None) tournament = get_object_or_404(Tournament, slug=tournamentslug) form.fields["match"]=forms.ModelMultipleChoiceField(widget=forms.SelectMultiple(attrs={'class':'matchc'}),required=False,queryset=Match.objects.filter(name__icontains=tournament.name)) html <div class="form-item"> <label for="id_match" class="rl-label" style="margin-bottom: 10px;">Match:</label> {{ form.match }} </div> -
ListView unrelated model lookup
I'm looking for a way to bring data from one model into a view of another model for a ListView. Basically, when the user opens up the listview of the vocabulary model, I need to look up and pull out the associated pinyin field from the dictionary model by using the vocab field. There is some example code at the bottom of the codeview that would be how I would match up a Vocabulary.vocab with a Dictionary.pinyin. ############### Models class Vocabulary(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) vocab = models.CharField(max_length=255, blank=False, null=False) translation = models.CharField(max_length=255, blank=False, null=False) level = models.PositiveSmallIntegerField(blank=True, null=True, choices=LEVELS, default=0) audio = models.URLField(blank=True, null=True) objects = RandomManager() class Meta: constraints = [ models.UniqueConstraint(fields=['created_by', 'vocab'], name='User Vocab Duplicate Check') ] verbose_name = "Chinese Vocabulary" verbose_name_plural = verbose_name # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.vocab class Dictionary(models.Model): traditional = models.CharField(max_length=20) simplified = models.CharField(max_length=20) pinyin = models.CharField(max_length=255) simplified_radical = models.CharField(max_length=20) hsk_level = models.PositiveSmallIntegerField(blank=True, null=True, choices=LEVELS, default=0) frequency_rank = models.PositiveIntegerField(blank=True, null=True) phrase_url = models.CharField(max_length=200) radical_url = models.CharField(max_length=200) definition = models.TextField() objects = RandomManager() class Meta: verbose_name = "Dictionary" verbose_name_plural = "Dictionary" … -
Change button depending on if photo is liked in django
I am adding a functionality in my website, where users can like posts. I have successfully done this, however I am having trouble adding one functionality. This is text within a button depending on whether a post is liked or not. Right now the button stays the same no matter if the post is liked or not. models.py class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, through='Like', related_name='likes') def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] @property def total_likes(self): return self.likes.count() class Like(models.Model): status = models.BooleanField() post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py def likepost(request, post_id): if request.method == 'POST': post = get_object_or_404(Post, pk=post_id) user = request.user if post.likes.filter(id=user.id).exists(): post.likes.remove(user) return redirect('home') else: like = Like() like.post = post like.user = user like.status = True like.save() post.likes.add(user) return redirect('home') my template: {% if post.likes.status == True %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a> {% else %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }} </button></a> {% endif %} -
django assigns incorrect media url
I am (locally) creating a (dockerized) production setup for my django project. I am using django with gunicorn and nginx. Nginx handles static and media files, which work fine, as I can access them by manually entering the correct url. While django does correctly link to static files, the urls to media files are wrong. For media files it skips the port in the url, while for static files it does not. I tried to remove trailing '/', tried to set MEDIA_URL = 'localhost:1337/media/', among other things. I don't understand why the static urls are correct and the media urls are not as I set them up in the exact same way: settings.py: DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = 'path/to/static' MEDIA_URL = '/media/' MEDIA_ROOT = 'path/to/media' example of (correct) django link to static file: 'http://localhost:1337/static/path/to/file example of django link to uploaded media file: 'http://localhost/media/path/to/file' actual location of media file: http://localhost:1337/media/path/to/file -
How to learn Django Rest API and implement
What are the ways I can master in REST API and build some good projects in REST API? -
Inheritance model update to its parent model
I need extend a model from another model. Case: core/models.py class City(Master): zipcode = models.IntegerField() Master is a abstract model. custom/models.py from core.models import City class City(City) newfield = models.CharField(max_length=20) I have tried with proxy model but it is not what I need, since proxy model adds a new table. https://docs.djangoproject.com/en/2.2/topics/db/models/#proxy-models I need is that when I migrate add the new field to City. -
Is it possible to create a custom table view in django-admin?
Is it possible to create a custom page in the admin with a custom queryset which is going to populate a table. The data which is going to be populated in the table is complex, it needs to contain 3 different models with some certain relationship (I already have that but I am exporting it to xls instead.),so far I am thinking about just extending the urls.py (the admin urls) with some custom url + the view, but that would change my consistent look of the admin. What would be the best approach for this?