Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Obtain DJango Authorization token using https only
I am not a web developer and hence my understanding of web development technology is limited. Hence please bear with me. I am trying to retrieve result from a Rest API using VBA. The rest API requires authentication using django framework. I initially tried to use HTTPRequest.Send "Get", URL, async, username, password I am getting {"detail":"Authentication credentials were not provided."} back. I gather that as the REST API I am working with uses django framework, I probably would need to authenticate using django. Hence my question is if I could submit username/password to django and retrieve authorisation token, by making https requests only - without having to reference various django objects (which would have entailed developing it outside VBA). Am I asking for the impossible? Thanks in advance -
What is the best way to separate two applications on a same Django Project?
I have two separate applications with different features but with the same back-end code base that runs on Django. These applications also have separate databases. But some Django apps (like custom user or an app for managing locations or custom authentication) are used in both projects; and developing, maintaining, and adding new features are getting harder beacause the project is growing large What is the best way to separate code bases for these projects? Should I migrate to microservices with Django (or something else)? Or is there a better way to -
How to compare in same model (Django) two specific fields
How to compare in same model (Django) two specific fields (which one is higher) and save result in third field(Boolean for example)? -
Weasyprint render_to_string <weasyprint.HTML object at 0x7f6f944df190> 2 extra bytes in post.stringData array problem
I have an html template and I want to print a pdf with weayprint for it. However, I am getting the error "<weasyprint.HTML object at 0x7f6f944df190> 2 extra bytes in post.stringData array problem" that I mentioned in the title. I am sharing my views.py file and some of my html template. views.py def export_pdf(id): print('export') edit_ambulanceCase = CallCenter.objects.all() html_string = render_to_string('forms/update_forms/pdf.html',{'PreCaseControl':edit_ambulanceCase}) print(html_string) html = HTML(string=html_string) print(html) return HttpResponse(html.write_pdf('deneme.pdf')) pdf.html <main> <div class="container-fluid px-4"> <div class="row justify-content-center"> <div class="col-lg-12"> <div class="card shadow-lg border-0 rounded-lg mt-5"> <div class="card-header"><h4 class="text-center font-weight-light my-4">Çağrı Merkezi Formu</h4></div> <div class="card-body"> <form action="" method="POST"> {% csrf_token%} <h3>Çağrıyı Yapan</h3> <div class="row"> <div class="mb-3 col"> <label for="institution_name" class="form-label">KURUM ADI</label> <input type="text" class="form-control" id="institution_name" name="institution_name" value="{{CallCenter.institution_name}}"> </div> <div class="mb-3 col"> <label for="caller_username" class="form-label">ADI SOYADI</label> <input type="text" class="form-control" id="caller_username" name="caller_username" value="{{CallCenter.caller_username}}"> </div> </div> <div class="row"> <div class="mb-3 col"> <label for="proximity" class="form-label">YAKINLIĞI</label> <input type="text" class="form-control" id="proximity" name="proximity" value="{{CallCenter.proximity}}"> </div> <div class="mb-3 col" data-type="control-phone"> <label for="caller_tel_no" class="form-label">TELEFON NUMARASI</label> <input type="tel" class="form-control" id="caller_tel_no" name="caller_tel_no" value="{{CallCenter.caller_tel_no}}" data-component="phone" inputmode="text" maskvalue="(###) ###-####" val> <label class="form-sub-label" style="min-height: 13px;" for="caller_tel_no_sub">Lütfen geçerli bir telefon numarası girin.</label> </div> </div> <h3>Hasta</h3> <div class="row"> <div class="mb-3 col"> <label for="patient_username" class="form-label">ADI SOYADI</label> <input type="text" class="form-control" id="patient_username" name="patient_username" value="{{CallCenter.patient_username}}"> <label for="patient_age" class="form-label">YAŞ</label> <input type="text" class="form-control" id="patient_age" … -
how can I display category name of selected wallpaper
models.py class Category(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class SubCategory(models.Model): sub = models.CharField(max_length=100) category = models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.sub class Wallpaper(models.Model): subcategory = models.ManyToManyField(SubCategory) this is my view.py def download(request, wallpaper_name): try: wallpaper = Wallpaper.objects.get(name=wallpaper_name) context = {'wallpaper': wallpaper} return render(request, 'Wallpaper/download.html', context) on my download page how can I show categorty name of that specific wallpaper -
What is wrong with this PostgreSQL connection?
Everything was working fine, until suddenly my docker-compose up & manage.py migrate & manage.py makemigrations all started failing. an example is below. C:\Users\tgmjack\Desktop\londonappdevelopersexample\my_ec2_ting\app>python manage.py makemigrations C:\Users\tgmjack\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? warnings.warn( No changes detected Since the error complained of inconsistent migration history, i deleted my migrations folder thinking i could just start again. That changed nothing, so then i decided to delete all my previous containers and images in docker too. The postgresql server is now running again after doing another docker build. but it still doesnt want to connect. below is the last bunch of lines from the logs of my postgresql server copied from inside docker desktop. I believe this shows that im doing things right (ie my server is running on 0.0.0.0:5432) 022-10-29 08:53:48.707 UTC [1] LOG: received fast shutdown request 2022-10-29 08:53:48.709 UTC [1] LOG: aborting any active transactions 2022-10-29 … -
migrate sqlite database data to postgres database on heroku
I've been working on a django project locally and used SQLITE as the database. I've now deployed the project to Heroku and used postgresql as the database. I've done the migrations and the database schemas migrated fine but the data from the tables has not migrated. How do i migrate the sqlite data to postgresql database? Here is my database code from settings.py DATABASES = { 'default': { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) -
How to get a target table without a table via a thought relation
I have models ` class G(models.Model): s = models.ManyToManyField("S", related_name="gg") class S(models.Model): b = models.BooleanField(blank=True, null=True) class SP(models.Model): s = models.ForeignKey("S", models.DO_NOTHING, related_name="sp1") p = models.ForeignKey("P", models.DO_NOTHING, related_name="sp1") class P(models.Model): q = models.IntegerField() ` How can I get prefetch related table E? I try to do A.objects.prefetch_related("s__sp1__q").all(), but I get the data of the intermediate table SP (s_id=1, p_id=1), but I want to get the data of table P immediately (q=2) -
django querySet union?
there is situation in which when user search a keyword, the result will be 3 queries a=model.objects.filter(icontains=keyword[0]) b= a.filter(icontains=keyword) c= a.filter(istartswith=keyword) And I want to return a result which combines a, b & c. But the condition is the order should be c,b,a and elements should not be repeated. I tried using union but the order is not correct. -
Foreign Key TestCase
I am trying to run tests on models and am having trouble with ones that have a foreign key. When I try to get the card made in setUp I am not able to. I am not understanding why. The value expected for the attribute category is an int. Either category, category.id, nor 'Test Category' work. Code: models.py class Category(models.Model): category_name = models.CharField(max_length=32) class Card(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) question = models.CharField(max_length=255) answer = models.TextField() slug = models.SlugField() test_models.py class CardTestCase(TestCase): def setUp(self) -> None: category = Category.objects.create(category_name='Test Category') Card.objects.create(category=category, question='Hello?', answer='Hello!', slug='slug' ) def test_card_exists(self): category = Category.objects.get(category_name='Test Category') L29 card = Card.objects.get(category=category.id, question='Hello?', answer='Hello!', slug='slug' ) Error: line 29, in test_card_exists card = Card.objects.get(category=category.id, django_cards.cards.models.Card.DoesNotExist: Card matching query does not exist. -
Calculate remaining days using javascript
I have this code I try to calculate remaining days using javascript in html I want to loop the function through all start date innerHTML First I get the start date in Html and calculate them all and display them any help would be greatly appreciated <td> <div id="start_date"> {{start_date|date:"m d Y"}} <!-- Here will by the start date 10/28/2022 --> </div> </td> In script <script> function func (){ var starDate = document.getElementById('start_date').innerHTML; console.log(starDate) var date = Math.abs((new Date().getTime() / 1000).toFixed(0)); var date2 = Math.abs((new Date().getTime(starDate) / 1000).toFixed(0)); var diff = date2 - date; document.getElementById('remaining-days').innerHTML = diff; console.log(diff) } func(); in display I got 0 just for first one -
AttributeError: 'WindowsPath' object has no attribute 'rpartition' when setting directory
After typing STATIC_ROOT = BASE_DIR / "staticfiles" in settings.py I get the error in the tittle. I tried with STATICDIR but it still doesn't work. I am pretty new to django so I don't really know other ways to fix it. -
Send message using Django Channels outside consumer class getting RuntimeError('Event loop is closed')
I am trying to send a message to the frontend outside of a consumer class in Django Channels. What I am trying to do is, the client will send a file via http, thus hitting a view class, and the view class will call the consumer class and send update to the client via websocket. This is my view class GroupListView(BaseListView): name = "Group list view" model = Group serializer = GroupSerializer def get(self, request: Request): if "bulk" in request.query_params and request.query_params["bulk"]: async_to_sync(get_channel_layer().group_send)("test_lobby", {"type": "chat.message"}) return self.send_response(False, "pending", {}) This is my consumer class TestConsumer(WebsocketConsumer): def connect(self): self.room_name = "lobby" self.room_group_name = "test_lobby" async_to_sync(self.channel_layer.group_add( self.room_group_name, self.channel_name )) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def chat_message(self, event): # Send message to WebSocket self.channel_layer.send(text_data=json.dumps({"message": 'hello world'})) I am following from the Django Channels documentation: https://channels.readthedocs.io/en/stable/topics/channel_layers.html#using-outside-of-consumers However, I am getting this error HTTP GET /api/v2/groups/?bulk=true 200 [0.05, 127.0.0.1:56152] Task exception was never retrieved future: <Task finished name='Task-28' coro=<Connection.disconnect() done, defined at /python3.9/site-packages/redis/asyncio/connection.py:819> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File "/python3.9/site-packages/redis/asyncio/connection.py", line 828, in disconnect self._writer.close() # type: ignore[union-attr] File "/python3.9/asyncio/streams.py", line 353, in close return self._transport.close() File "/python3.9/asyncio/selector_events.py", line 700, in close self._loop.call_soon(self._call_connection_lost, None) File "/python3.9/asyncio/base_events.py", line 746, … -
Django admin. How to redirect the link on the model class to open the first object?
I have model in django it is 'Slogan' model. I restricted it to only 1 object from admin: def has_add_permission(self, request): if len(Slogan.objects.all()) == 1: return False return True My view in home page will create the first object on page load if there is no object slogan in the database. What I want to do is when I open admin and click on the left side where Slogan is to open the first object of that class directly instead of seeing a list with objects on the right and select it from there. I tried get_url() method from admin but this seems to be for the specific objects. -
My list gets suddenly empty and I can't restore it
I'm newbie in django and I was trying to construct a site in which the user can take a quiz. In a simpler version of that, I wanted just the questions to be displayed in random order, one after another(when the user presses a button) and when all the questions have been displayed to return to the main page, where there is a link "take the test". I know that it certainly isn't the most efficient way to do it, but I want to know what is wrong with my code. urls.py: path('start',views.startquiz,name='start'), path('test/<int:pk>/<int:index>',views.TakeQuizView.as_view(),name='test'), views.py: def startquiz(request): questions=list(Question.objects.all()) question=random.choice(questions) pk=question.id return redirect(reverse('quiz:test',args=(pk,1))) class TakeQuizView(LoginRequiredMixin,View): questions=list(Question.objects.all()) n=len(questions) def get(self,request,pk,index): question=Question.objects.get(id=pk) self.questions.remove(question) ctx={'question':question,'index':index,'n':self.n} return render(request,'quiz/test.html',ctx,) def post(self,request,pk,index): if index<self.n: question=random.choice(self.questions) pk=question.id return redirect(reverse('quiz:test',args=(pk,index+1))) else: self.questions=list(Question.objects.all()) return redirect(reverse_lazy('quiz:main')) ` Whenever I take the quiz for the first time, all works fine, and after all questions have been displayed, it returns to the main page. However, if I want to take the test again, the questions list fails to be filled up again and I get an error: list.remove(x): x not in list from remove() I also tried to put in the get method the following code: ` if index==1: self.questions=list(Question.objects.all()) ` However it … -
pip command not working. I tried upgrading pip <pip install --upgrade pip> and < python -m pip install -U pip> but it's giving out a similar error
I tried installing django but it gave out the following error ERROR: Exception: Traceback (most recent call last): File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Program Files\Python310\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 94, in resolve It's a long one... Then I tried using pip for different packages and it turns out I'm getting a similar error in almost all of the so I tried to upgrade them python -m pip install -U p and pip install --upgrade pip but it's giving out a similar error Traceback (most recent call last): File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Program Files\Python310\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 94, in resolve result = self._result = resolver.resolve( File "C:\Program Files\Python310\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 472, in resolve -
How can i return json web token after creating user in djoser with dango rest framework
This is my serializer file for updating the default UserCreateSerializer of djoser. I saw this question but did'nt understand anything please help me to implement this. -
Celery KeyError: 'myproject.tasks.async_task'
When i'm trying to run celery background task then it giving me error: KeyError: 'myproject.tasks.async_task' I'm using python version: 3.8.10, django verion: 4.1.2 , celery version: 5.2.7 and rabbitmq version: 3.8.2 here below screenshot is my project structure: here below is my code for background task: settings.py: CELERY_BROKER_URL = 'amqp://localhost:5672' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' myproject/init.py: from __future__ import absolute_import, unicode_literals from myproject.celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import import os, sys from celery import Celery import django from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py: from __future__ import absolute_import from celery import shared_task from time import sleep import os @shared_task def sleepy(duration): sleep(duration) return None @shared_task def async_task(save_path, name_of_file): sleep(30) completeName = os.path.join(save_path, name_of_file+".html") file1 = open(completeName, "w") toFile = 'test data' file1.write(toFile) file1.close() return 'task complete' views.py def add_product(request): if request.method == 'POST': id_col_data = request.POST.getlist('services') target_col = request.POST.get('target_col') file_name = request.POST.get('file_name') amz_columns_dict = {'id_col': id_col_data, 'target_col': target_col, 'wt_col': None} import os.path save_path = '/home/satyajit/Desktop/' if os.path.exists(save_path): try: from myproject.tasks import async_task name_of_file = file_name status = async_task.delay(save_path, name_of_file) #celery task print('status---->', status) except Exception as e: print('task … -
How to find the index of a queryset after the database is sorted in Django
I am making a leaderboard for my quiz. I made this model: class LeaderBoard(models.Model): name = models.CharField(max_length=200) score = models.DecimalField(max_digits=4, decimal_places=2) This is my code for getting a queryset leaderboad_place = leaderboard.order_by("score").get(name=request.user.username) After I sort my code, I need the index at which my score stands out. I want the index, I mean the location of the queryset after the database is sorted, my code is not working. Please someone help. -
KeyError when I read environment variables while doing makemigrations in django
Context of the problem - I want to migrate from the SQLite database to Postgres. When I makemigrations with Postgres settings which are passed to the settings file with environment variables, I get KeyError; however, another variable from the same file does not cause any problems. My secrets file: SECRET_KEY='secret key value' DB_HOST='db host value' DB_NAME='db name value' DB_USER='db user value' DB_PASS='db pass value' DB_PORT='db port value' My dev.py settings: from app.settings.base import * import os from dotenv import load_dotenv import pprint load_dotenv(os.environ.get('ENV_CONFIG', '')) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS += [ ] MIDDLEWARE += [ ] env_var = os.environ print("User's Environment variable:") pprint.pprint(dict(env_var), width=1) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_HOST'], 'PORT': os.environ['DB_PORT'], } } As you see, I import all the content from my base settings file - app.settings.base, where I use my secret key (in the same way as I read my environment variables for database): SECRET_KEY = os.environ.get('SECRET_KEY', '') I use SQLite in my base.py settings and want to use Postgres in my dev.py. However, when I try to ./manage.py makemigrations --settings=app.settings.dev, I get the error: … -
Trouble Creating a webpage
I'm having trouble creating a view. Down below you can find my view. I keep getting template error. I'm not sure where I went wrong.. class PrivacyView(CreateView): model = Post template_name = 'privacy_policy.html' fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('post_list') def post_list(request, tag_slug=None): posts = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) query = request.GET.get("q") if query: posts = Post.published.filter(Q(title__icontains=query) | Q(tags__name__icontains=query)).distinct() paginator = Paginator(posts, 10) # 10 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'post_list.html', {'posts': posts, page: 'pages', 'tag': tag}) Not sure where I'm going wrong here. If you can provide any help, please do. -
Low Speed Connection for VS Code servers to download extensions
Two days ago, i'd installed Ubuntu and deleted windows, than i install VS Code from Snap Store, now i have a problem with VS Code servers to download extensions. I'm from Iran and we have low speed connection, because of it, I get error for low connection. Is there a way to install extensions for VS Code? any help will gratitude. I get the XHR timeout: undefinedms How can i install VS Code extensions due to low connection speed? -
Django Query "caches" until restarting Server
Django "caches" my query. I realized it after updating my Database. When i run the Function with the Query, it takes some old Data before the Update. When i restart the Server, it works fine again. Do anyone know, how i can solve this issue? I use Raw Queries with the connection-function. (connection.cursor(sql)). In the End of each Query, i close the cursor with cursor.close(). I debugged the Code and found out, that after Updating my Database it takes the old Data until i restart my Server. -
Bootstrap modal, django for loop and model | same value displaying error Fixed
Would you like the modal to display corresponding loop values or messages? When I tried to print the order message in modals, it showed the same message for every order, which led me to realize that every time we call the same modal ID, it shows the same message for every order, -
Django Advanced Filtering for a Queryset that can have many related foreign keys
I am trying to sort a query in django on a model that can have multiple foreign keys. I only want the filtering to apply to one of those keys and I am having a hard time getting it to work. models.py class Post(models.Model): content = models.TextField(max_length=1000) reaction_counts = GenericRelation(ReactionCount, related_query_name='post_reaction_counts') class ReactionType(models.TextChoices): LIKE = 'like', ('Like') DISLIKE = 'dislike', ('Dislike') STAR = 'star', ('Star') LOVE = 'love', ('Love') LAUGH = 'laugh', ('Laugh') class ReactionCount(models.Model): count = models.PositiveIntegerField(default=0) type = models.CharField( max_length=7, choices=ReactionType.choices, ) post = models.ForeignKey(Post, related_name="reaction_count", on_delete=models.CASCADE) In this above example the keyed element (Foreign Key Relation) is ReactionCount for Post. I want to sort the posts by the posts with the most likes, dislikes, stars, loves, laughs, etc. I am trying to do this by doing Post.objects.all().order_by('-reaction_count__type', '-reaction_count__count') This however does not work as there are multiple ReactionCount objects for each post causing the ordering to not work. What I need is for a way to specify that I want the ordering of count to only apply only to Posts with a ReactionCount foreign key of a specific type. Is there a way this can be done by changing how the ordering is done on object Posts? …