Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't browse server files with Django Ckeditor
I build a django application. I use DigitalOcean space to store my media files. I use Django Ckeditor to allow admin to write content with nice textarea and to allow them to upload some images. Uploading image is working (in the folder : "modules_images" as you can see in my code). Problem happen's when admin want to click on the button "browse server". He get the following error : NoSuchKey at /ckeditor/browse/ An error occurred (NoSuchKey) when calling the ListObjects operation: Unknown I spent a lot of time looking for people who already meet this problem but no one had exactly the same (people who meet problems at browsing files generally meet problems at uploading files too) and no one of the answers helped me. Here is my urls.py : urlpatterns = [ ... path('admin/', admin.site.urls, name="admin"), path('chaining/', include('smart_selects.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my ckeditor configs in settings.py : CKEDITOR_UPLOAD_PATH = "modules_images/" CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': … -
Django admin queryset foreign key to user
I have an e-commerce development and I'm looking to send an email to the client from the admin site, I can´t the queryset correclty to do this. I have the following model: models.py class Orden(models.Model): cliente = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name='Usuario') productos = models.ManyToManyField(OrdenProducto) fecha_orden = models.DateTimeField(auto_now_add=True) completada = models.BooleanField(default=False, null=True, blank=True) id_transaccion = models.CharField(max_length=20, null=True) correo_enviado = models.BooleanField(default=False, null=True, blank=True) datos_pedido = models.ForeignKey( 'DatosPedido', on_delete=models.SET_NULL, blank=True, null=True) pago = models.ForeignKey( 'Pago', on_delete=models.SET_NULL, blank=True, null=True) cupon = models.ForeignKey( 'Cupon', on_delete=models.SET_NULL, blank=True, null=True) class Meta: verbose_name_plural = "Orden" def __str__(self): return self.cliente.username 'cliente' has a foreign key to the 'User' model and I want to get the email address, I have tried many ways but I just can´t get it admin.py class OrdenAdmin(admin.ModelAdmin): list_display = ('cliente', 'completada', 'correo_enviado') actions = ['enviar_correo'] def enviar_correo(self, request, queryset): queryset.update(correo_enviado=True) a = queryset.get(cliente=self.user.email) send_mail('test', 'test', 'xxxxxx@mail.com', ['a], fail_silently=True) -
How to add a pre-defined formlist and condition dict to a Sessionwizard (Django 2.2)?
I've implemented the accepted answer with make_condition_stuff function in this Stackoverflow post for repeating a Django SessionWizard step as long as the button 'add another' is pressed, or True, which works. I want to add this function for one wizard step, more specifically, wizard step 3. The make_condition_stuff function returns an own form list and a condition dict that I want to add to the wizard form list and condition dict for the other steps. I'm not sure how to add or update the condition dict and form list in the wizard with the external condition dict and form list from the function make_condition_stuff. How can I integrate the external form_list and condition dict from the function with the ordinary wizard form list and condition dict ? I've tried to define a condition dict and form_list in the wizard self init and passed it to the method get_form_list but it raises an error with the Ordered dict that the ordinary wizard form_list is based on whereas the returned form_list from the function is an ordinary list but a Type error is raised when I try to append the function form_list to the Ordered dict with the wizard form_list. I've found … -
How to do a multi-value filter in Django?
I have the following code: class PageListView(generics.ListAPIView): queryset = Page.objects.all() serializer_class = PageSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = ('category', 'calculated_hsk') pagination_class = LimitOffsetPagination ordering_fields = ['date'] My category value is an integer. I am calling my local API as such: http://127.0.0.1:8000/api/v1/pages/?category=1,6&calculated_hsk__in=4.00&limit=10&ordering=-date&offset=0 However this does not work I have also tried http://127.0.0.1:8000/api/v1/pages/?category__in=1,6&calculated_hsk__in=4.00&limit=10&ordering=-date&offset=0 Which likewise doesn't work. Is there a specific filter backend I need? I am trying to replicate this aspect of a query: WHERE category IN (value1, value2, ...) -
How do I combine my Django models so that I am not repeating myself?
I realize that the 3 models that I use right now have a ton of shared fields. I was wondering what the best way to condense these models would be. I've read some articles on metaclasses and model inheritance but wanted to see what the "best" way to do this would be. models.py class Car(models.Model): created = models.DateTimeField(auto_now_add=True) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)]) seats = models.PositiveSmallIntegerField() color = models.CharField(max_length=100) VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)]) current_mileage = models.PositiveSmallIntegerField() service_interval = models.CharField(max_length=50) next_service = models.CharField(max_length=50) class Truck(models.Model): created = models.DateTimeField(auto_now_add=True) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField(default=datetime.now().year, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)]) seats = models.PositiveSmallIntegerField() bed_length = models.CharField(max_length=100) color = models.CharField(max_length=100) VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)]) current_mileage = models.PositiveSmallIntegerField() service_interval = models.CharField(max_length=50) next_service = models.CharField(max_length=50) class Boat(models.Model): created = models.DateTimeField(auto_now_add=True) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.PositiveSmallIntegerField(default=datetime.now().year, validators=[MaxValueValidator(datetime.now().year)]) length = models.CharField(max_length=100) width = models.CharField(max_length=100) HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True) current_hours = models.PositiveSmallIntegerField() service_interval = models.CharField(max_length=50) next_service = models.CharField(max_length=50) -
ImportError: Couldn't import Django. Problem with deploying Django app to Heroku
I'm trying to deploy my Django app to Heroku but I keep having this error after successfully building the app. This is the log after a successful build: 2021-03-16T15:21:32.000000+00:00 app[api]: Build succeeded 2021-03-16T15:21:32.647557+00:00 heroku[web.1]: State changed from crashed to starting 2021-03-16T15:21:36.820238+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0.0.0:49625` 2021-03-16T15:21:39.146005+00:00 app[web.1]: Traceback (most recent call last): 2021-03-16T15:21:39.146029+00:00 app[web.1]: File "manage.py", line 11, in main 2021-03-16T15:21:39.146029+00:00 app[web.1]: from django.core.management import execute_from_command_line 2021-03-16T15:21:39.146030+00:00 app[web.1]: ModuleNotFoundError: No module named 'django' 2021-03-16T15:21:39.146030+00:00 app[web.1]: 2021-03-16T15:21:39.146031+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2021-03-16T15:21:39.146031+00:00 app[web.1]: 2021-03-16T15:21:39.146031+00:00 app[web.1]: Traceback (most recent call last): 2021-03-16T15:21:39.146032+00:00 app[web.1]: File "manage.py", line 22, in <module> 2021-03-16T15:21:39.146032+00:00 app[web.1]: main() 2021-03-16T15:21:39.146032+00:00 app[web.1]: File "manage.py", line 13, in main 2021-03-16T15:21:39.146033+00:00 app[web.1]: raise ImportError( 2021-03-16T15:21:39.146046+00:00 app[web.1]: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2021-03-16T15:21:39.193415+00:00 heroku[web.1]: Process exited with status 1 2021-03-16T15:21:39.280185+00:00 heroku[web.1]: State changed from starting to crashed 2021-03-16T15:22:38.622544+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=metamedapp.herokuapp.com request_id=1fccc50d-d117-4cab-862c-91d05b765c4d fwd="86.7.108.29" dyno= connect= service= status=503 bytes= protocol=https 2021-03-16T15:22:39.701300+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=metamedapp.herokuapp.com request_id=723d001f-0cf6-4291-b884-e5d7772d9d3c fwd="86.7.108.29" dyno= connect= service= status=503 bytes= protocol=https … -
What is the expected behaviour when a model has two foreign keys with different on_delete constraints?
Let's say I have this model: class UserBook(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) book = models.ForeignKey(Book, on_delete=models.PROTECT) Where the user is only allowed to borrow 1 book at a time. I want instances of this model to get deleted if the user gets deleted, but I don't want them to get deleted if a book gets deleted (by mistake, just a precaution). What is the expected behaviour when a user gets deleted using the above constraint? I'm getting: Cannot delete some instances of model 'UserBook' because they are referenced through a protected foreign key Is there a way to achieve what I want? I tried to delete UserBook on pre_save/post_save signals but neither worked. -
Is there Django form field or widget that appends Radio and CharField
I'm trying to create a Django form fields that has radio choices and "other" choice that is a text field. It should look like this I tried this but its from 2014 and it's not working. Can you give me an idea how to fix this code or how can I create a custom widget that will do the job. Thank you for your help! -
Python replace multiple substrings in a string
I have a text: "{name} likes {post}". I fetch data according to the values inside {} from db. Then I get values coming inside an Array, like ["John", "515335"] for one piece of data. I don't know how many variables I will get inside the string. Would be 1 or 3 too. ( But the count of content to be replaced and values will be same) So what would be the best way to replace the values in this string please? Expected output: "John likes 515335" -
Django and PostgreSQL - how to store time range?
I would like to store a time range (without dates) like "HH:MM-HH:MM". Can you give me a hint, how can I implement it most easily? Maybe there is a way to use DateRangeField for this aim or something else. Thanks for your spend time! -
Print a html page using django
I want to print a HTML page using django. I mean that if an user wants to print a webpage with printer when press print button 《print button is a HTML button with tag 》 server automatically print that webpage on a paper. Thanks. -
Django how to access a radio buttons selected value
I'm a little bit rusty on Django and require some basic assistance. I am creating a quiz application and I have correctly displayed all questions and answers of that question. I am using a radio button and upon the user clicking submit, I need to access the answer that was selected to calculate the result. I am having trouble accessing the answers submitted by the user. I think I need to create an HTML form to do that and access it in the views but as I have multiple questions in the same page I am confused. Here is a snippet of where I need the assistance: sampleConfirmation.html {% extends 'home.html' %} {% load crispy_forms_tags %} {% block content %} <div id="questionForm" class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend id="headerForm" class="border-bottom mb-4">Complete your sample quiz! This will generate your level!</legend> {{ form|crispy }} </fieldset> </form> <div id ="displayQuestions" class="question-section"> {% for q in questions %} <table> <tr> <td> {{q.question}}</td> </tr> <fieldset id = "group1"> {% for a in answers %} {% if a.answerForQuestion == q%} <tr> <td> <input type="radio" name = "{{q.id}}" value="{{q.id}}"> {{a.answer}}</td> {{q.id}} </tr> {% endif %} {% endfor %} </fieldset> </table> {% endfor %} </div> … -
Get current path in custom django search_form admin template
I have a custom search_form.html template for my AdminModel template, i want get current url path for make a conditional render of a button but {{ request.path }} dont return nothing, settings.py (TEMPLATES list): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], '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', ], }, }, ] directories structure: IMAGE search_form.html template: IMAGE result (BLANK): IMAGE -
django.db.utils.OperationalError: no such table: contacts_contact
I am trying to migrate to migrate my database using python manage.py makemigrations and manage.py migrate but always getting this error django.db.utils.OperationalError: no such table: here is the full traceback. python manage.py migrate Traceback (most recent call last): File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: contacts_contact The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, … -
Can't see modification of model fields in admin panel
Get this issue short time after deploy on server (engine x + g unicorn + django3.0 + sqlite3): Added some field in models file -> added this field in fields list Admin class (admin file) -> manage make migrations -> manage migrate, so i get the message of successful migration...but then i see no scheme changes in admin panel. Database is modified and i don't have this problem on local test server. models file: from django.db import models from django.utils import timezone class AdultCatCard(models.Model): name = models.CharField(max_length=20, verbose_name='Name') testfield = models.CharField(null=True, blank=True, max_length=50, verbose_name='testfield') admin file: from django.contrib import admin from .models import AdultCatCard from django.utils.safestring import mark_safe class CatCardAdmin(admin.ModelAdmin): fields = ['name', 'testfield'] admin.site.register(AdultCatCard, CatCardAdmin) -
I am having a problem with my like button, from question earlier. Noting is still happening to my page
I manage to put my like button on my user profile page. But when I click on it it doesn't return anything. It supposes to show count() - like butten. Which I add to my view.py file. models.py class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) ... def __str__(self): return self.username + ' | ' +self.last_name + ' | ' + self.first_name + ' | ' + str(self.phone_number) + ' | ' + self.user_type + ' | ' + self.email+ ' | ' + str(self.id) class LikeButton(models.Model): user = models.ForeignKey(CustomKorisnici, on_delete=models.CASCADE) likes = models.ManyToManyField(CustomKorisnici,related_name='profile_like') def total_likes(self): return self.likes.count() view.py def LikeProfile(request,pk): like = get_object_or_404(LikeButton, id=request.POST.get('majstori_id')) like.likes.add(request.user) return HttpResponseRedirect(reverse('majstori_profile', args=[str(pk)])) class LikeMajstoriProfile(DetailView): model = LikeButton context_object_name = 'like_button' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(LikeMajstoriProfile, self).get_context_data(*args, **kwargs) stuff= get_object_or_404(LikeButton, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return context class MajstoriProfile(DetailView): model = CustomKorisnici context_object_name = 'majstori' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(MajstoriProfile, self).get_context_data(*args, **kwargs) majstori= get_object_or_404(CustomKorisnici, id=self.kwargs['pk']) context['majstori'] = majstori return context urls.py path('ProfileMajstori/<int:pk>/', LikeMajstoriProfile.as_view(), name="majstori_like"), html.page <div> <div> <form action="{% url 'like_majstor' majstori.pk %}" method="post"> {% csrf_token %} <button … -
How to send a command like data from react front-end to back-end through websockets? (React-Django)
Hey I am trying to learn using websockets and currently stuck with certain problems. How can I send data from react to back-end django (django channels)? I need to send a command, say 'join' from the front-end to start and initiate the websocket connection and then a command 'message' if user sends a message. What I am planning is to send a onopen when the page renders and send a 'join' command, but that isn't working. I tried like this, chatSocket.onopen = () => { chatSocket.send(JSON.stringify('command': 'join')) ---> does not work with the back-end and to send the message, I have this.. (which works when the condition is checked with not None) const messageOnSubmit = (e) => { chatSocket.onopen = () => { chatSocket.send(JSON.stringify(message: e.target.value)) setInput('') } } and in the back-end, I have async def websocket_receive(self, event): # when a message is recieved from the websocket print("receive", event) command = event.get("text", None) print(command) if command== "join": 'do something' elif command == "message": 'do something' I would like to implement such a feature..like checking what command is comming from the front-end and then dispatching an action. how to do this? as of now, I am just checking the condition, like … -
Where do i run my code, which requires a intense usage of CPU?
I don't know if my question is weird, but i'm developing a SaaS for a company and using the following technologies: Python Docker Django Redis Celery I have initialized a EC2 instance, with only 1 CPU. My question is: I have to allow users to run features in a asynchronous way (Celery, Redis), but, It doesn't seem to me that run those tasks locally (with only 1 CPU) is right. I'm facing some troubles trying managing tasks/queues in my application, probably due to the unique CPU. Do i initialize a better instance (with 2 CPUs or greater) or i could possibly run those intense tasks in a serveless, like AWS Lambda or Iron.io (I don't know well those technologies, but if someone tell me that this is the best solution, i go deeper) Sorry if it looks confusing. Just for curiosity, one of those intense tasks is processing a lot of readable documents (pdf, txt, and so on), but it cannot stop other tasks. -
Django: ForeignKey vs related_name
I'd like to ask if there is an important distinction between below two ways of expressing a ForeignKey relation, or is it just a "style" difference? In my opinion it is intuitive to first define a "sub-model" and then refer to it in your "main model", as below. version_1 class Track_1(models.Model): order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Album_1(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) tracks = models.ForeignKey(Track_1, on_delete=models.CASCADE) Meanwhile it is less intuitive to express it as below, using related_name, as below. version_2 class Album_2(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track_2(models.Model): album = models.ForeignKey(Album_2, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() Furthermore, I have seen most examples around Django Rest Framwork uses "version_2" to create linked serializers. Is this a style difference by the author or would actually become important when using DRF? class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] -
'URLPattern' object is not iterable after adding channels to my installed apps
I get the error message File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 122, in __init__ for route in self.routes: TypeError: 'URLPattern' object is not iterable when i add channels to my installed apps in settings.py. without channels it the urls and templates work as inteded. Do i have to append the URLRouter or am I missing a element? heres my routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from tribe_chat.consumers import TribeChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( re_path('tribe_chat/<room_id>/', TribeChatConsumer), ) ) ), }) and heres my settings.py: INSTALLED_APPS = [ 'channels', 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'tribe_chat' ] ASGI_APPLICATION = 'MusicTribe.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } -
How to show all dictionary in template in Django?
I am working with IFC and I need to extract some data from a .ifc file to be displayed in the Django template. The template: {% extends 'base.html' %} {% block content %} <h2>upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Upload File</button> </form> <br> {{result}} {% endblock %} I've tried two methods: OpenIfcFile = ifcopenshell.open(filepath) #select the file BrowseIfcProducts = OpenIfcFile.by_type('IfcElement') #search for the attribute 'IfcElement' for eachproduct in BrowseIfcProducts: #add the .ifc searched data to dict 'context' with 'result' key context['result'] = [ eachproduct.is_a(), eachproduct.GlobalId, eachproduct.get_info()["type"], eachproduct.get_info().get("Name","error"), ] return render(request, 'upload.html', context) In this method, due the key 'result' doesn't change on each iteration, only the last item is stored and in my template i can't see all items. So, to fix this problem, I concatenate the result key to a iterator (i): i = 1 for eachproduct in BrowseIfcProducts: context['{} {}'.format('result', i)] = [ eachproduct.is_a(), eachproduct.GlobalId, eachproduct.get_info()["type"], eachproduct.get_info().get("Name","error"), ] i += 1 return render(request, 'upload.html', context) But, unfortunately, nothing is displayed in the template I'm stuck here, i don't know how can I show the data on template, can someone help me? -
How do I use proxy in Nextjs to send HttpOnly cookie to django on different domain?
I previously posted about not being able to send HttpOnly cookie from nextJS to django either from getServerSideProps or from useEffect here. I think the reason is that my django and Nextjs are running on different domains. So I need to have same domains for both back-end and front-end. Does it mean that requests from nextJS should go from 127.0.0.1:8000 instead of 127.0.0.1:3000? If yes, do I need to use proxy within Nextjs? Also, I have set-up django-cors-headers, does it still require proxy? -
How I can convert the `{'c_like': '99', 'count': 1}` to the colour like button and count the likes in Django
How I can convert this data to visible thing for example if I click on the like button increase the likes +1 and change the button to red if I hit it again thin decrease -1 and change the color my views def like_comment(request): id = request.POST.get('like_id') comment = Comment.objects.get(id=id) data = {} if request.POST.get('action') == 'add_like': account = request.user if comment.likes.filter(id=account.id).exists(): comment.likes.remove(account) c_like = False else: comment.likes.add(account) c_like = True data["c_like"] = id data["count"] = comment.likes.count() print(data) return JsonResponse(data) my template (Html) {% if not request.user in node.likes.all %} <button id="comlike" style="color: #aaaaaa;" onclick="addLikeToComment({{ node.id }})" class="remove-default-btn p-0 border-0 " type="submit" style="border: none; color: #aaaaaa;" > <svg width="0.9em" height="0.9em" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" > <path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/> <span class="ml-1" id="span_like">{{ node.likes.all.count }}</span></svg> </button> {% else %} <button id="comlike" style="color: red;" onclick="addLikeToComment({{ node.id }})" class="remove-default-btn btn btn-dinger p-0 border-0 " type="submit" class="remove-default-btn like-btn{{ request.path }}" style="border: none; color: #aaaaaa;"> <svg width="0.9em" height="0.9em" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" … -
Working with user type does not work in Django
I'm trying to create a user type in Django with that idea the user have the first type he will be redirected to a template if he is another he will be redirected to another one this is my models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False def is_reception(self): if self.type_of_user == 'reception': return True else: return False def is_temporary(self): if self.type_of_user == 'temporary': return True else: return False and this is my views.py @login_required def dashboard(request): if User.is_doctor: return render(request, 'user/dashboard.html', {'section': 'dashboard'}) else: return render(request, 'user/dashboard2.html', {'section': 'dashboard'}) but it always takes me to the dashboard .html only event if I change the user type -
Django proxy model with dynamic virtual fields
We store our data in a mixture of "real" model fields and fields which are defined and stored in a JSON-Structure. To simplify handling those structures with our model serializer and the DRF, we thought about implementing a proxy model which looks up the structure/data of the dynamic fields and adds those field to the proxy model class Classification(AbstractContent): """ classification model """ name = models.CharField( verbose_name=_('name'), max_length=255, null=False, blank=False, ) # for example we have like that in our structure #{'topEntry': {type:'bool',value:'false'}, 'addName': {type:'string, value: 'test} dynamic = models.JSONSchemaField(content_type=None, null=True) We now want to get a proxy model which consists of those real model fields (name in this example) + two additional fields 'topEntry' and 'addName'. It is no problem for us to add those fields in the proxy model with @property, but trying others ways the serializer would not recognize our fields.