Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import is failing with an ImportError stating that the force_text function cannot be found
"C:\Users\prash\desktop\gfg\authentication\views.py", line 11, in <module> from django.utils.encoding import force_bytes, force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\prash\desktop\gfg\venv\Lib\site-packages\django\utils\encoding.py) when i am trying to import the force_text function from the django.utils.encoding module, but the import is failing with an ImportError stating that the force_text function cannot be found. -
Call Django url namespace inside window.open
Good day, all. Currently, I want to try if the user clicks the update button on the web and then shows a popup window for updating their data. Before I have line code for updates like this: <a class = "btn btn-outline-primary" href="{% url 'help:update show.id %}">Delete</a> then I added the URL inside the window.open with an id parameter like this: onclick="window.open('update',show.id, 'newwindow', 'width=400, height=250'); return false;" the page is open but in the same tab not in the new window as I expected in the pop-up. Is there any way to do like I expected? Thank you :) -
Why the CSS of my Website is not appear by Django?
I created a Django backend Website then I designed a template for the frontend by HTML and CSS, but the CSS and Javascripts and some files like vendor of that dont not appear at final although I set address for CSS and Javascripts and vendor files for Login and Signup templates in settings.py and static and staticfiles. you can see my codes in below images enter image description here enter image description here enter image description here enter image description here enter image description here I expect that the signup and login templates coming up with CSS and JS files correctly. -
Django pic app code explanation, not sure why this works
so i was trying to follow along dr Chuck's Django course. In the pics app def post(self, request, pk=None): form = CreateForm(request.POST, request.FILES or None) pic = form.save(commit=False) def save(self, commit=True): instance = super(CreateForm, self).save(commit=False) # We only need to adjust picture if it is a freshly uploaded file f = instance.picture # Make a copy if isinstance(f, InMemoryUploadedFile): # Extract data from the form to the model bytearr = f.read() instance.content_type = f.content_type instance.picture = bytearr So my confusion is, instance is a model object and picture attribute in model is a binaryfiled, but in form its a FileField. So for new entry f = instance.picture, should always return null, as there is nothing in database yet. I get that 'subject' and 'text' will be retrieved when i call super as these are similar for both model and form, but instance should not have picture yet. And if it does, than this must always be true "if isinstance(f, InMemoryUploadedFile)". I know this code works perfectly, i just don't understand how. I appreciate any help. Form.py class CreateForm(forms.ModelForm): max_upload_limit = 2 * 1024 * 1024 max_upload_limit_text = naturalsize(max_upload_limit) # Call this 'picture' so it gets copied from the form to … -
django annotate with dynamic "then" value
So i have this dictionary of months below: MONTHS = { 1: "Janeiro", 2: "Fevereiro", 3: "Março", 4: "Abril", 5: "Maio", 6: "Junho", 7: "Julho", 8: "Agosto", 9: "Setembro", 10: "Outubro", 11: "Novembro", 12: "Dezembro", } And i want to annotate each of this value in a queryset, conditionally. I know i can use Case and When for that, and so am i, by doing: queryset = queryset.annotate( last_installment_month_as_string=Case( When(last_installment_month=1, then=Value(MONTHS[1])), When(last_installment_month=2, then=Value(MONTHS[2])), When(last_installment_month=3, then=Value(MONTHS[3])), When(last_installment_month=4, then=Value(MONTHS[4])), When(last_installment_month=5, then=Value(MONTHS[5])), When(last_installment_month=6, then=Value(MONTHS[6])), When(last_installment_month=7, then=Value(MONTHS[7])), When(last_installment_month=8, then=Value(MONTHS[8])), When(last_installment_month=9, then=Value(MONTHS[9])), When(last_installment_month=10, then=Value(MONTHS[10])), When(last_installment_month=11, then=Value(MONTHS[11])), When(last_installment_month=12, then=Value(MONTHS[12])), ) ) But can't i do it dynamically? Like in a for loop or something? I tried doing on a for loop, but no success whatsoever... Im looking to do something like: for key, value in MONTHS.items(): queryset = queryset.annotate( last_installment_month_as_string=Case( When(last_installment_month=key, then=Value(value)) ) ) But that doesn't work! -
Django DJFile encoding
I'm trying to save .txt files with utf-8 text inside. There are sometimes emojis or chars like "ü","ä","ö", etc. Opening the file like this: with file.open(mode='rb') as f: print(f.readlines()) newMessageObject.attachment = DJFile(f, name=file.name) sha256 = get_checksum(attachment, algorithm="SHA256") newMessageObject.media_sha256 = sha256 newMessageObject.save() logger.debug(f"[FILE][{messageId}] Added file to database") Readlines is binary, but the file that is created with DJFile is not utf-8 encoded. How can I do that? -
How to setup github actions for celery and django?
I have some celery tasks in situated in my django app, in my tests section of the project I have several celery task that does some database work using django orm. In my local environment, pytest works fine but in github actions the following error is shown. kombu.exception.OperationalError In my pytest conftest.py file I have used the following setup [ taken from celery docs ] @pytest.fixture(scope="session") def celery_config(): return {"broker_url": "amqp://", "result_backend": "redis://"} but still, the exception is thrown. So, How can I properly create a github workflow that can test celery tasks without the above exception? -
How to add pagination to Bootstrap grid html page getting data from pandas dataframe?
I have a web page which includes Crispy Filter and "table" created in Bootstrap grid by iteration from Pandas DataFrame. Is there some way how to add pagination to this Pandas DataFrame presented in Bootstrap Grid? -
Getting all users from a Group - Django
I am trying to get the list of all users from the group "Manager", the post request works @api_view(['GET','POST']) def managers(request): username = request.data['username'] if username: user = get_object_or_404(User, username=username) managers = Group.objects.get(name="Manager") if request.method == 'GET': managers.user_set.get(user) if request.method == 'POST': managers.user_set.add(user) elif request.method == 'DELETE': managers.user_set.remove(user) return Response({"message": "ok"}) return Response({"message": "error"}, status.HTTP_400_BAD_REQUEST) I got this error below. KeyError at /api/groups/manager/users 'username' Please, can I get a guide? -
Django mirror production mysql database into development environment
I have a Django project current running in production on a remote Linux server. The database I use is mySQL database. At the same time, I am developing new features on my local computer also using mySQL database (a different mySQL database). Is there a way that I can "mirror" or copy the database content from my production mySQL database onto my local development machine, so that I can access the same model objects? -
adding a message for the user in a custom django admin view
I have created a custom admin site and there is a view I'd like to be invoked with a custom button. This is my adminSite object: class MyAdminSite(admin.AdminSite): site_header = 'My admin site' def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path('appname/modelname/<int:pk>', self.admin_view(self.my_view), name='appname_modelname_view'), ] return urls def my_view(self, request, pk): #do something messages.info(request, 'some message') registering the model for which the view is invoked my_admin = MyAdminSite() class myModelAdmin(admin.ModelAdmin): change_form_template = 'admin/appname/change_form.html' my_admin.register(myModel, myModelAdmin) change_form.html: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% block object-tools-items %} <li> <a href="{% url opts|admin_urlname:'myview' original.pk %}" class="someclass">Invoke</a> </li> <li> <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a> </li> {% if has_absolute_url %} <li> <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a> </li> {% endif %} {% endblock %} When I click the "invoke" button, it should reload the the page and display the info message on top. However, the page simply reloads. How do I make sure that the … -
Django detail view not rendering static files
Hello my I have a Django project which works fine but the problem I usually get is from my Detail View, it does not render statics files. And when I check the output from my terminal I see that my Detail View url name is joined to my static/assets link. My static settings # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static/'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(CORE_DIR, 'media') # Default user model AUTH_USER_MODEL = 'accounts.CustomUser' # My urls.py file from django.urls import path from .views import * app_name = 'base' urlpatterns = [ path("", HomePage.as_view(), name="home"), path("jobs", Jobs.as_view(), name="jobs"), path('jobs-short', Jobs_List.as_view(), name="jobs-short-list"), path('job-detail/<int:pk>', Job_Detail.as_view(), name='job-detail'), path("company", Company.as_view(), name="companies"), path('candidate', Candidate.as_view(), name="candidates"), path('candidate-detail/<int:pk>', CandidateDetail.as_view(), name="candidate-detail"), path("about-us", about_us, name="about"), path("candidates", candidates, name="candidate"), ] [28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/plugins.css HTTP/1.1" 404 4068 Not Found: /job-detail/static/assets/css/style.css [28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/style.css HTTP/1.1" 404 4062 Not Found: /job-detail/static/assets/css/templete.css [28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/templete.css HTTP/1.1" 404 4071 Not Found: /job-detail/static/assets/css/skin/skin-1.css [28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/skin/skin-1.css HTTP/1.1" 404 4080 Not Found: /job-detail/static/assets/plugins/datepicker/css/bootstrap-datetimepicker.min.cs -
how i can use django context inside context
Well I know that what I'm doing is not very feasible, but I wanted to know if there's any way to do this.I want to create a portfolio blog to post some 3d renders, for that I want to have more control over the structure of the page. for this I created two models (one for the post and another to receive the images, linking them to the post through a foreign key) so that I could have an indefinite number of images, the problem came when I decided that I wanted to be able to choose the one positioning of the images according to my need/desire, for that I did the following: I used django summernote temporarily to be able to test the written posts, I knew that it would probably not be possible to do this because the content sent from the models is static. I have the following models: class Post(models.Model): titulo_post=models.CharField(max_length=255, verbose_name='Titulo') autor_post=models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='autor') data_post=models.DateTimeField(default=timezone.now, verbose_name='Data publicação') conteudo_post =models.TextField() publicado_post=models.BooleanField(default=False, verbose_name='Status publicação') def __str__(self) : return self.titulo_post and: class Estudo(models.Model): imagem=models.ImageField(upload_to='estd_img/%Y/%m/%d', blank=True, null=True) post=models.ForeignKey(Post, on_delete=models.CASCADE) I tried to put the following value in the field "conteudo_post" through the administrative area to see if it would … -
Is it possible to check the group affiliation in custom permissions (BasePermission)?
Let's say I want to fetch a user profile. I want to allow it to the profile owners or users belonging to the administrator group. I know how to do these two things separately. For owners: class IsOwner(BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, object): if request.user.is_authenticated: return object.name == request.user.name return False And for the admin group: from django.contrib.auth.mixins import PermissionRequiredMixin class MyView(PermissionRequiredMixin, View): permission_required = ('polls.can_open', 'polls.can_edit') But how to allow either of the above? Is it possible to check user groups and permissions inside the has_object_permission method, without additional database calls? -
tinymce is not working in django, because of static files
I'm trying to use tynimce in my django, but I get this error: "GET /static/js/tinymce/tinymce.min.js HTTP/1.1" 404 1834 Well, my section for statics in the settings.py is this: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static') # emulates live cdn after collecting the static files, I get this ad it is working for e.g. the admin portal : But the bastard is searching for static/js/.... I don't have such a directory and even I didn't told him to search there. Why is there a problem, if the statics are collected automatically and I didn't set an url for tinymce. -
Django: How to upload blank page and show data after filtering?
this is more general question. I have over a hundred thousand rows in database, I use Pandas Dataframe to create a table with required output and this output is presented in html template. And I use crispy filter to get e.g. data for particular project, for particular manager or time period. And as first all data are uploaded this page is slow. And I would like to upload blank page with filter and after filtering to present only required data. And my question is how to do it with filter, if is it possible? Or if I have to use forms in some way? -
CS50W - Lecture 4 - SQL, Models and Migrations
Not sure why I'm getting this traceback while following the lecture. As soon as I run python manage.py migrate, I get this traceback. I deleted the dbsqlite file from the Project folder and all the files from migrations folder as well. ` Traceback (most recent call last): File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: flights_airport The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\query.py", line 1790, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\models\sql\compiler.py", line 1660, in execute_sql cursor.execute(sql, params) File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\db\backends\utils.py", … -
Use input tag instead of CharField in form in django
I have django application with simple ModelForm: class VideoUploadForm(forms.ModelForm): class Meta: model = Video fields = ['title', 'description','file'] I pass it to context in my view and than load it in template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.title }} <br> {{ form.description }} <br> {{ form.file }} <br> <button type='submit'>Submit!</button> </form> Now I want to style my inputs, but I don't know how to do that. It should look something like: <input type="text" class="title_input"> Just with additional linking to {{ form.title }} field. -
Generating Error "errors": [ { "message": "There is no current event loop in thread 'Thread-5'." using graphql and django
this is the error I'm getting while fetching comments in graphql [ model I have created in django schema I have created is here]3 -
Stencil setup: resolve, rollup version
I have two problems, both related to setting up my project. The ultimate goal is to build some web components that communicate vis OSC using node-osc. My first attempt to set up the project and create a component that uses node-osc resulted in the following message: Bundling Warning UNRESOLVED_IMPORT 'node-osc' is imported by ./src/components/r-channel/r-channel.tsx, but could not be resolved – treating it as an external dependency This gave me a successful build, but my components don't render, so I assume it's not actually all that successful. After some reading, my guess is that I should at least try plugin-node-resolve. I've installed and added to my stencil.config.ts, and am now seeing: Rollup: Plugin Error Insufficient rollup version: "@rollup/plugin-node-resolve" requires at least rollup@2.78.0 but found rollup@2.42.3. (plugin: node-resolve, buildStart) ...although my package-lock.json seems to indicate that I've got rollup@2.79.1 installed. -
Django monolith: How to render front-end while still loading one function from backend
I have a django monolith project; however, one of the objects (a graph) that I pass to the template context to display in the html is slow to load. I'd like to have the rest of the page render first, while this function is still running/loading. That way, users can see the rest of the page while the graph is still loading. Thoughts on the best approach to this? I tried creating a custom tag to load the graph, but the browser still waited for the everything to load before showing anything on the page. I'm wondering if some type of javascript call would accomplish this. -
How to create SO like tags in django?
Given a form, I need it to have tags (preferably) or any form which enables multiple selection with simple search/autocomplete. Something similar to SO tags will do: -
Bootstrap 5.2 Modals not appearing when using docs example
Literally copy pasting documentation Example from https://getbootstrap.com/docs/5.2/components/modal/: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> I am using Django to develop a website with Python (which shouldn't matter here), I have an index.html with this headers: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="xxx" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="xxx" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js" integrity="xxx" crossorigin="anonymous" referrerpolicy="no-referrer"></script> The modal isn't working and I am not sure why, can someone assist? I am not using any javascript on top of that. Isn't it supposed to work already with the '''data-bs-''' tags? Much thanks. I tried taking all CDN's updated versions. I also checked the other StackOverflow posts but they either aren't updated or didn't solve my problem... bootstrap modal not working at all I even tried adding the jquery from here, without success: Bootstrap modal not working after clicking button Maybe I did something incorrect, as I don't have extense experience. -
what comes after begin a Django backend developer?
iam Django backend developer freelancer iam not looking for any kind of jobs idc about money I don't wanna be a normal programmer I have learnt all programming basics and programming logic I almost know every thing about rest api I have reached an advanced level on Django framework, Django restframework, signals, and react js, node js now I want something to focus on! something let me create more advanced and complicated projects like wix.com for example I already done a lot of advanced projects, even ideas from Google or freelance websites what should I start to learn? iam 17 years old I tried to search on YouTube, google but I didn't find what iam looking for I have read about GO programming language but idk what to do now -
Disable admin application for django
I am trying to run the django development server and its failed with below error. Exception in thread django-main-thread: Traceback (most recent call last): File "/my/virtual/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/my/virtual/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/my/virtual/environment/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/my/virtual/environment/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/my/virtual/environment/lib/python3.8/site-packages/django/core/management/base.py", line 469, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E403) A 'django.template.backends.django.DjangoTemplates' instance must be configured in TEMPLATES in order to use the admin application. this is django-rest-framework application and it has no admin application. How to say django runserver to not run admin application?