Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Chat Application using channels
I am trying to learn to setup a django chat using channels. I tried the Channels tutorial at https://channels.readthedocs.io/en/latest/index.html and got into some issues. My issue is as below. When 1st browser joins a room it works just fine. But the moment a new browser session joins the same room, the first session does not get the messages and 2 messages are sent to the latest browser session. If a third browser session joins the room, 1st and 2nd session don't get the messages and the third session gets all the 3 messages. I followed every step meticulously but not able to fix the issue. Can anyone guide me please. -
How to get a many to many field display in my select field form
FORM class Form_elegir_carrera(forms.Form): carrera_del_tutor= forms.ModelChoiceField(queryset=None,widget=forms.Select(attrs={'class': 'select is-normal'}),label='Tutor carrera',required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(Form_elegir_carrera,self).__init__(*args, **kwargs) if self.user: self.fields["carrera_del_tutor"].queryset = Tutor.objects.filter(user_id=self.user).get().carrera else: self.fields['carrera_del_tutor'].queryset = Tutor.objects.none() def clean(self): carrera_del_tutor = self.cleaned_data.get("carrera_del_tutor") VIEWS @login_required def elegir_carrera(request, tutor_id): context = { 'tutor_id':tutor_id } if request.method == 'POST': form = Form_elegir_carrera(data=request.POST or None) if form.is_valid(): descripcion = form.cleaned_data.get('carrera_del_tutor', None) context = { 'form': form,'tutor_id':tutor_id } return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: context = { 'form': form, 'tutor_id':tutor_id } return render(request, "elegir_carrera.html", context) else: form = Form_elegir_carrera(user = tutor_id) context = { 'form': form,'tutor_id':tutor_id} return render(request, "elegir_carrera.html", context) context = { 'form': form, 'tutor_id':tutor_id } return render(request, "elegir_carrera.html", context) MODEL class Tutor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) nombre = models.CharField(max_length=50, blank=False, null=True) apellido = models.CharField(max_length=50, blank=False, null=True) carrera = models.ManyToManyField(Carrera, blank=True) class Meta: verbose_name_plural = "Tutores" verbose_name = "Tutor" def __str__(self): return '%s %s' % (self.nombre, self.apellido) #return self.user.email I want to query all carreras that the user has, and display each of them in a dropdown to be selected. Until now it displays the carreras asociated to the user, but when I make a submit, it throws an error saying that is not one of the availables. -
Why is installing python-psycopg2 on my Docker image not preventing the subsequent "No module named 'psycopg2'" error?
I'm using docker-compose v 1.27.4 on Mac. I have this docker-compose.yml file -- two services, a PostGres DB and a Python/Django app ... services: postgres: image: postgres:10.5 ports: - 5105:5432 environment: POSTGRES_DB: directory_data POSTGRES_USER: chicommons POSTGRES_PASSWORD: password web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn directory.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - postgres This is the Dockerfile used to build the Python/Django container ... FROM python:3.8-slim RUN apt-get update && apt-get install RUN apt-get install -y dos2unix RUN apt-get install -y libpq-dev python-dev RUN apt-get install -y python-psycopg2 RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip WORKDIR /my-app/ COPY requirements.txt requirements.txt COPY entrypoint.sh entrypoint.sh RUN python -m pip install -r requirements.txt RUN dos2unix /my-app/entrypoint.sh ENTRYPOINT ["bash", "/my-app/entrypoint.sh"] However, when I start my application using "docker-compose up," I get the below errors web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> web_1 | import psycopg2 as Database web_1 | ModuleNotFoundError: No module named 'psycopg2' web_1 | web_1 … -
How to set upload_handlers on a per-request basis using Django Rest Framework
I have a DRF view where I need to ensure that uploaded files land on the filesystem and not just in memory. DRF respects Django's FILE_UPLOAD_HANDLERS setting, but I don't want to change it for my whole app, just this one view. I know that in a regular Django view I could set request.upload_handlers to my desired value, but that doesn't seem to work in DRF. I've tried doing it from .initialize_request() in my viewset, like so: def initialize_request(self, request, *args, **kwargs): request.upload_handlers = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"] return super().initialize_request(request, *args, **kwargs) but I'm getting: AttributeError: You cannot set the upload handlers after the upload has been processed. What is the correct way for me to set the upload handlers for a single DRF view (in particular, the create action of a generic viewset)? -
Source does not exist, Django templates
Although I set TEMPLATE_DIR and DIR in TEMPLATES in settings.py I can't receive my goal. www.rouznegasht.com Is my website. You can see the error now. the settings.py : TEMPLATE_DIRS = ( '/home2/rouznega/django-rn/staticsdir/', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ '/home2/rouznega/django-rn/staticsdir/' ], 'APP_DIRS': False, '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', ], }, }, ] this is my views.py : from django.shortcuts import render from django.http import HttpResponse def index(request): context={} return render(request,'index2.html',context=context) And I put my template in this folder. after that I call collectstatic in the shell. but I can't achieve the goal. The error : why the engine searchs here ? django.template.loaders.app_directories.Loader: /home2/rouznega/virtualenv/django-rn/3.7/lib/python3.7/site-packages/django/contrib/admin/templates/index2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home2/rouznega/virtualenv/django-rn/3.7/lib/python3.7/site-packages/django/contrib/auth/templates/index2.html (Source does not exist) if this details helps you to help me look the end of settings.py : STATIC_URL = '/static/' STATIC_ROOT = '/home2/rouznega/public_html/assets/' STATICFILES_DIRS = [ ('/home2/rouznega/django-rn/staticsdir/') ] Thank you -
Detecting the no. of colors of an uploaded image in a Django project
I am working on a colour detection project and I am trying to link it to my Django Project, but I don't know where to start. In my Django project, I have a Post CreateView where users can upload images. Here is the function that I am trying to link the colours in the image to Post.colors but I don't know how to make it generated directly once the image is uploaded Here is the models.py: class Post(models.Model): title = models.TextField(max_length=100) design = models.ImageField( blank=False, null=True, upload_to='new designs') date_posted = models.DateTimeField(default=timezone.now) colors= models.TextField(max_length=10,blank=True, null=True) def __str__(self): return self.title def imagecolors(self, *args, **kwargs): img = Image.open(self.design) size = w, h = img.size data = img.load() colors = [] for x in range(w): for y in range(h): color = data[x, y] hex_color_lower = ''.join([hex(c)[2:].rjust(2, '0') for c in color]) hex_color = hex_color_lower.upper() colors.append(hex_color) total = w * h color_hex = [] color_count = [] color_percent = [] df = pd.DataFrame() for color, count in Counter(colors).items(): percent = count / total * \ 100 # Do not make it int. Majority of colors are < 1%, unless you want >= 1% if percent > 1: color_hex.append(color) color_count.append(count) color_percent.append(percent) Post.colors=color_hex print(Post.colors) with the above … -
Password protected link gives 404 in Django and Nginx
I want to password-protect a single page of my Django website (I don't want to use Django's authentication system, which I'm using already for other parts of my website; this is an unrelated one-off) by adding this to my nginx.conf: location /myprivatepage { auth_basic "Private page"; auth_basic_user_file /etc/nginx/.htpasswd; } And putting user and password in /etc/nginx/.htpasswd. When I point my browser to /myprivatepage the browser asks indeed for user and password. Once successfully authenticated, I get a 404 error: 404 Not Found nginx/1.14.2 If I comment the lines above I can reach the page as guest correctly. What am I doing wrong? -
Django render_to_string() got multiple values for argument 'context'
I am trying to pass the following argument to render to response syntax in Django but I keep getting the following error: render_to_string() got multiple values for argument 'context' def genarate_pdf_notes(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=filter' + \ str(datetime.datetime.now())+'.pdf' response['Content-Transfer-Encoding'] = 'binary' context = {} filtered_yp = YP_Filter( request.GET, queryset=YP_General_Information.objects.all() ) context['filtered_yp'] = filtered_yp html_string = render_to_string(request, 'filter/homepage.html', context=context) html = HTML(string=html_string) result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) # output = open(output.name, 'rb') they using this on a live server response.write(output.read()) return response -
Django: ConnectionResetError: [Errno 54]
This logs, quite repeatedly, every time my app loads on my computer. Exception happened during processing of request from ('127.0.0.1', 53597) Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/usr/local/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/usr/local/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I realize that this has been posted on extensively over the years, but it seems to me that the consensus on the answer is that it could be one of a few things: (a) Using a .png instead of an .ico in a favicon (b) Misusing {% static %} (c) Misusing event.preventDefault() Unfortunately for me, none of those things have happened in the last few weeks in my teams commits. So I ask, are there other solutions I may be missing? This is a result of me recently merging with a master development branch. -
start download and redirect at the same time
I have a view that hands back a file for download, but also some messages about the status - which I do not see, because of no redirect after the download started: class DownloadView(TemplateView): template_name = "TEST/listview.html" def get(self, request, *args, **kwargs): filepath = GET_FILE() if os.path.exists(filepath): with open(filepath, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(filepath) messages.success(request, "download started ...") return response return redirect("index") except Exception as e: messages.error(request, e) return redirect("index") I do not necessarily need the redirect to index after the response, but I cannot see the messages until I reload the page - which is not nice if there was an error. How can I add a redirect after the download started? -
Expected json object in Django activity stream but show string in template
Here is settings.py configuration for the django-activity-stream. ACTSTREAM_SETTINGS = { 'MANAGER': 'actstream.managers.ActionManager', 'FETCH_RELATIONS': True, 'USE_PREFETCH': True, 'USE_JSONFIELD': True, 'GFK_FETCH_DEPTH': 1, } This is action. action.send(actor=actor, verb="Posted", target=target, data='some string') and template {% for action in stream %} <div>{{ action.data.data }}</div> {% endfor %} I expected that template will show some string, but not showing anything. If I change the tag like this {% for action in stream %} <div>{{ action.data }}</div> {% endfor %} It shows {"data": "some string"} -
Django Template Context in Flatpages
I'm using template inheritance with a base.html file that has a footer.html include: {% include 'footer.html' %} I've got context data in all pages (eg, index, DetailViews, ListViews, etc) except for the flatpages (of which there are many). All my templates inherit base.html, which includes footer.html (including my flatpages default.html). How can I get the context data (eg, from my other models) to show up in my flatpages? I suppose I can add context to a view if I could figure out how to override the Django flatpage view. The flatpage view in Django seems to only have the actual flatpage object as context. -
How to customize django admin panel
I am building an e-commerce website and I would like to customize my Django Admin Panel to look something like this: I would like to re-design the entire admin page and add graphs, tables images etc. the same way you would do on the front-end. I have been searching online for hours for a solution but I can't find anything useful. Does anyone have any solution to this problem? -
django-autocomplete-light Shows Some ModelSelect2 Fields but not Others
I have a form that looks like this (forms.py): class TaskForm(ModelForm): """ Form based on the Task model. """ class Meta: """ Meta class to define TaskForm with built-in Django variables. Assigns Task as the model and explicitly defines which fields from Task are included. Overrides default widgets for some fields to allow autocomplete inputs, larger text inputs, and custom date inputs. """ model = Task fields = [ 'name', 'description', 'project', 'request', 'category', ] widgets = { 'name': ModelSelect2(attrs={'data-minimum-results-for-search': -1}), 'request': ModelSelect2(attrs={'data-minimum-results-for-search': -1}), 'project': ModelSelect2(url='p-autocomplete',), 'category': ModelSelect2(url='cat-autocomplete',), } Two of the fields have autocomplete views behind them, two do not. The two that do not have autocomplete views behind them do not show up as ModelSelect2 fields (with proper formatting) in the browser. One of the fields that has an autocomplete view behind it DOES show up with the proper formatting, and the other does not (and does not populate any values when clicked). Both autocomplete views are successful when navigating to them directly. Why would django-autocomplete-light formatting only be applied to specific fields in a form? -
How can I do to get the entries in an array?
Hello I have this table : id country begin end 1 US 2020-10-07 15:30 2020-10-07 16:30 2 US 2020-10-07 16:30 2020-10-07 18:00 3 US 2020-10-07 19:00 2020-10-07 20:00 4 SP 2020-10-08 15:30 2020-10-08 17:30 5 SP 2020-10-08 17:30 2020-10-08 18:30 And using Django I would like to put in an array the data like this : [{'country':'US', 'begin':'2020-10-07 15:30'; 'end':'2020-10-07 18:00'}, {'country':'US', 'begin':'2020-10-07 19:00'; 'end':'2020-10-07 20:00'}, {'country':'SP', 'begin':'2020-10-08 15:30'; 'end':'2020-10-08 18:30'}] I get my table with the following query : myTable = Table.objects.all().order_by('begin') For the two first lines I don't know how to implement that... Basically I want if the country is the same and if one end 1 is equals to one begin 2 I want to put this in a same element in my array with begin 1 and end 2. The line 3 stay like that because the begin 2020-10-07 19:00 is not equals to 2020-10-07 18:00 nor 2020-10-07 16:30 and the end 2020-10-07 20:00 is not equals to 2020-10-07 15:30 nor 2020-10-07 16:30. For the fourth and fifth line we noticed the country are not US but SP. Then, the end of the fourth line is 2020-10-08 17:30 and the begin of the fifth line is … -
Django edit model page not displaying part of form
Having an issue where in the models admin part of Django, part of the edit form is not available to edit. For example the URL to access this edit is /admin/association/event/914/ 'association' is the app 'event' is the model '914' is the ID I would normally expect to see something like this (not the same model, but shows the ability to edit it): However, I am only seeing this, where it's only showing the inlines and not the primary model: This is the admin.py code used: class EventAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ['competition'] } list_display = ('id','event_date','competition','clubs','event_location','days','promote') exclude = ["old_comp_id", "old_club_id", "club"] inlines = [EventFilesInLine,EventSponsorsInLine,RaceMeetingDatesInLine] search_fields = ['id','competition','event_location','club__club_name'] date_hierarchy = 'event_date' list_filter = ('event_date','state','days','promote') ordering = ('-event_date',) actions = [training_ring_yes, training_ring_no] admin.site.register(Event, EventAdmin) -
write a custom redirection decorator in django
I am trying to write a variation of the following redirection decorator: def permanent_redirect(url): def outer(f): @wraps(f) def inner(request, *args, **kwargs): f(request, *args, **kwargs) return HttpResponseRedirect(url if not callable(url) else url()) return inner return outer although this redirect just fine, the issue with it is that it ignores rendered values, or generared files on the view it is placed. I am a bit of out of my game here honestly, how would I go about modifying this decorator so it takes what is outputed by the view into account? -
How Do I Get Django to Show Image Field From Model in Templates?
I am trying to get the uploaded image to show in the project template. Here is what my code looks like currently: projects.html {% extends "base.html" %} {% block content %} <h1>{{ project.title }} HELLO</h1> <div class="content-section"> <div class="media"> <img src="{{ project.image.url }}" alt="beach" width=250px height=250px /> </div> <div> <h5>About the project:</h5> <p>{{ project.description }}</p> <br> <h5>Technology used:</h5> <p>{{ project.tools }}</p> </div> </div> {% endblock content %} models.py class Project(models.Model): title = models.CharField(max_length=500, unique=True) description = models.TextField(max_length=500) tools = models.CharField(max_length=200) image = models.ImageField(default='default.jpg', upload_to="beach_photos", blank=True) def __str__(self): return f'{self.title}' views.py from django.shortcuts import render from django.http import HttpResponse from projects.models import Project def projects(request): project = { 'project':Project.objects.all() } return render(request, 'projects/projects.html', context = project) settings.py configuration (app is installed) STATIC_URL = 'static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' When I inspect the image element in the webpage, the source shows up as src="" None of the other calls to the model are appearing either. Any help would be appreciated. -
How to send a message to all consumers using Django Channels 3.0.0?
I am trying to develop an interface that contains a section that shows all active users. So, when a user connects to the WebSocket I want to send data to all connected consumers. Currently, I wrote a code that when the user connects it sends data to the connected user only. I want somehow to make the message be sent to all active users/consumers. This is the path to my WebSocket handler/view path('test_ws/', websocket.TestConsumer.as_asgi()), And here is the handler class NewsMentionConsumer(AsyncWebsocketConsumer): groups = ["newsmention1"] channel_name = 'news_mention' active_users = [] async def connect(self): await self.channel_layer.group_add(self.groups[0], self.channel_name) await self.channel_layer.group_send(self.groups[0], { 'type': 'send_updates', 'text': json.dumps({ 'id': self.scope['user'].id, 'username': self.scope['user'].username, 'active_users': self.active_users }) }) await self.accept() self.active_users.append(self.scope['user']) async def send_updates(self, event): # TODO: Make this send to all users/consumers await self.send(event["text"]) I am facing a problem understanding the examples in django.channels docs and tried using send_group function but it doesn't really work. Any suggestions? -
Django: Make a single DB call instead of iterating QuerySet
I have the following code that iterates the tags queryset, and for each item, creates a Department object and adds it to the departments list: departments: List[Department] = [] tags = Tag.objects.filter(id=some_id, type="department") for tag in tags: dept_id = tag.reference_id dept_name = tag.name parent_tag = Tag.objects.get(id=some_id, type="department", reference_id=tag.parent_reference_id) dept_parent_id = parent_tag.reference_id departments.append(Department(dept_id, dept_name, dept_parent_id)) However, as you can see, it is making multiple DB calls via Tag.objects.get(), which seems highly inefficient. Is there an efficient way to populate that departments list without making so many DB calls? TIA. -
Django Pagination Troubleshooting
views.py from django.shortcuts import render, get_object_or_404, redirect,HttpResponseRedirect from .models import Post, Comment from django.utils import timezone from .forms import PostForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.urls import reverse from django .core.paginator import Paginator, PageNotAnInteger, EmptyPage def post_index(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by("published_date") paginator = Paginator(posts, 4) page = request.GET.get('page') try: post_list = paginator.page(page) except PageNotAnInteger: post_list = paginator.page(1) except EmptyPage: post_list = paginator.page(paginator.num_pages) return render(request, "blog/post_index.html", {"posts": posts, "page": page, "post_list": post_list}) post_index.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class= "rounded-circle article-img" src="{{ post.author.profile.profile_pic.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'profile' %}">{{ post.author }}</a> <small class="text-muted">{{ post.published_date }}</small> </div> <h2><a class="article-title" href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.text }}</p> </div> </article> {% endfor %} <div class="pagination"> <div class="section-inner clearfix"> <p> {% if post_list.has_previous %} <a href="?page={{ post_list.previous_page_number }}">&lt; Prev</a> | {% endif %} {% if post_list.has_next %} <a href="?page={{ post_list.next_page_number }}">Next &gt;</a> {% endif %} <span>Page {{ post_list.number }} of {{ post_list.paginator.num_pages }}</span> </p> </div> </div> {% endblock %} Hi guys, i am trying to paginate my site but it doesn't work. The address bar shows that there are other … -
How can I edit a bootstrap modal id with a django model data
I have a django model called CrewMember that adds a user into a team/crew of other users. class CrewMember(models.Model): ROLE = ( ('Supervisor', 'Supervisor'), ('Operative', 'Operative'), ('Trainee', 'Trainee'), ) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) site_work = models.ForeignKey(SiteWork, null=True, on_delete=models.CASCADE) role = models.CharField(max_length=200, null=True, choices=ROLE) I have a modal on the front end that checks if the user is sure they want to Delete the user as a crew member. I also have a modal for editing the users role and also sending a message to the user but I will just show you the delete modal because they are pretty much the same and all have the same problem. {% for crewman in crew_members.all %} {% if user_is_admin %} <div class="modal fade" id="delUserModal" tabindex="-1" role="dialog" aria-labelledby="delUserModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="delUserModal">Please confirm</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to delete {{crewman.user}} from the crew members list? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close </button> <a class='btn btn-danger' href=" {% url 'delete_member' crewman.user.id crewman.site_work.id crewman.role%}"> Delete </a> </div> </div> </div> </div> {% endif %} {% endfor %} The modal is inside the for … -
How can I pass a model id from the url to a class based view?
I have a class-based view: class Create(View): note_id = None http_method_names = ['post', 'patch'] default_title = "You fool! This was left empty" default_body = "Why did you leave this blank :(" def dispatch(self, *args, **kwargs): method = self.request.POST.get('_method', '').lower() print('method = ', method) if method == 'patch': return self.patch(*args, **kwargs) elif method == 'post': self.post(*args, **kwargs) return super(Create, self).dispatch(*args, **kwargs) def post(self, note_id): date = datetime.date.today() title = self.request.POST.get('title', '') body = self.request.POST.get('note', '') # check for blank attributes if title == "": title = Create.default_title if body == "": body = Create.default_body note = Note(note_title=title, note_body=body, publish_date=date, edit_date=None) note.save() return HttpResponseRedirect(reverse('notes:note')) def patch(self, note_id): note = Note.objects.get(id=note_id) title = self.request.POST.get('title', '') body = self.request.POST.get('note', '') # if something changed if title != note.note_title or body != note.note_body: # check for blank attributes if title == "": title = Create.default_title if body == "": body = Create.default_body note.note_title = title note.note_body = body note.edit_date = datetime.date.today() note.save() return HttpResponseRedirect(reverse('notes:note')) and in url.py I have urlpatterns = [ path('<int:note_id>/create/', views.Create.as_view(), name='create'), path('<int:note_id>/edit/', views.Create.as_view(), name='edit') ] Previously, with function-based views the note_id would just be passed to the function automatically. I can not figure out the equivalent of this in class based … -
Django Channels - Chat Tutorial - Message received only on second tab
I have been following the official Django Channels tutorial on the Chat Room. ChatRoom - Synchronous Tutorial However, even following every steps and double checking, I keep on having the same issue: The tutorial mentions the fact that both users, accessing the same chat room (and thus same group name) should receive messages from each other in both browsers tabs opened. If I send a message from tab 1, I can't see my message in tab 1 and tab 2. If I send a message from tab 2, I can see the message duplicated on tab 2 nothing on tab 1. This issue arises on the synchronous tutorial and the asynchronous one as wel. Did anyone have the same issue? I can't see what I've done wrong while following the tutorial. I am using Django/Channels latest version 3.1.3 with Python 3.9 and the Redis version mentioned on the tutorial. Thank you. -
Django render json response html
I'm am trying to render a json response which returns a html page in the body after I send my parameters to the endpoint url but I haven't found any information of how to handle this in django. So far I was able to see the html in an empty template that I created using JsonResponse(response.text,safe=False) but it shows the html with the tags and all. I'm open to suggestions. Note: The json post is going to send all the parameters to the endpoint and in response I get an html page that I need to show the user for payment processing. headers = {'content-type': 'application/json'} url = 'https://paymentway.net/api.php' params ={ "ClientId": "", "FirstName": fname, "LastName": lname, "Email": email, "Amount": amount, "InvoiceNumber": InvoiceNum } response = requests.post(url, headers=headers, data= json.dumps(params))