Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
About python environment
How can I install html and css formats in python environment when using Django framework? How would be in cmd? I used to pip freeze in environment, and there was a few installed things then out environment -
Django Permissions on WSL Ubuntu with Symlinked project folder
Hi I am fairly new to WSL and working in this environment. I am trying to run a Django project within a project folder that is Symlinked within Ubuntu. The location is on C:/projects. When I create a project I get the following error: Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/manage.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/urls.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/wsgi.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/settings.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/asgi.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/__init__.py. You're probably using an uncommon filesystem setup. No problem. Error Shown when creating a project or app Thanks I looked at trying to set permissions on the windows system to have full access. But I cannot resolve this error. -
Internal Server Error using apache django mod_wsgi or 500 internal server error mod_wsgi apache
wsgi.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gis_api.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd.conf ServerName 127.0.0.1:81 LoadFile "C:/Users/test/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/test/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/test/AppData/Local/Programs/Python/Python310" WSGIPythonPath "C:/Users/test/AppData/Local/Programs/Python/Python310/lib/site-packages/" <VirtualHost *:81> WSGIScriptAlias / "D:/django_project/gis_api/gis_api/gis_api/wsgi.py" <Directory "D:/django_project/gis_api/gis_api/gis_api/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "D:/django_project/gis_api/gis_api/static/" <Directory "D:/django_project/gis_api/gis_api/static/"> Require all granted </Directory> Alias /media "D:/django_project/gis_api/gis_api/media/" <Directory "D:/django_project/gis_api/gis_api/media/"> Require all granted </Directory> </VirtualHost> error.log mod_wsgi (pid=20212): Failed to exec Python script file 'D:/django_project/gis_api/gis_api/gis_api/wsgi.py'., referer: http://127.0.0.1:81/ mod_wsgi (pid=20212): Exception occurred processing WSGI script 'D:/django_project/gis_api/gis_api/gis_api/wsgi.py'., referer: http://127.0.0.1:81/ Traceback (most recent call last):\r, referer: http://127.0.0.1:81/ ModuleNotFoundError: No module named 'gis_api'\r, referer: http://127.0.0.1:81/ version : Django 4.1.1 mod-wsgi 4.9.4 os window 10 I have try to all solution. But getting error. I am beginner to deployment in django apache. Pl guide me best path of deployment. -
Firestore integration with Django
I have a Firebase Firestore database connected to a Flutter mobile application. I want to build a web application to manage the users' data and handle new users. I have decided to use Django for my web application, but I have two questions if anyone can help. First, is it actually reliable to use Django as the framework for this purpose? Second, I was trying to make a connection between Django and my existing DB to just try to call some values but I was getting this error: google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. Here is the code I am using for the connection db = firestore.Client() config={ "apiKey": "******************", "authDomain": "*******.firebaseapp.com", "projectId": "*******", "storageBucket": "*******.appspot.com", "messagingSenderId": "*******", "appId": "******************", "databaseURL": "https://***********.firebaseio.com", } firebase = pyrebase.initialize_app(config) auth = firebase.auth() database = firebase.database() def index(request): doc = db.collection('test').document('test1').stream() weight= doc['weight'] return render(request, 'index.html', { "weight":weight, }) -
How can we Integrate Nuxtjs and Django?
Hello I'm having a trouble Integrating Nuxtjs together with Django, can't find any related resources. -
Pass POST data in form with no action url Django
I have here a form with two buttons in it and when submitting, it doesn't pass the data on another page. <form method="post"> #some form inputs here... <a class="btn btn-success" href="{% #url_here %}">published</a> <a class="btn btn-secondary" href="{% #url_here %}">save as draft</a> </form> Does anyone know how to pass a post data in tag in Django, if the form tag has no action URL? thanks in advance! -
"Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". How to fix Error
I'm trying to submit post form data to an my api using react and I'm passing through JSON data like so. ` function AddSong() { const [title, setTitle] = useState(""); const [artist, setArtist] = useState(""); const [release_date, setReleaseDate] = useState(""); const [album, setAlbum] = useState(""); const [genre, setGenre] = useState(""); let handleSubmit = async (e) => { e.preventDefault(); try { let res = await fetch("http://127.0.0.1:8000/api/music_library/?format=json", { method: "POST", body: JSON.stringify({ title: title, artist: artist, album: album, release_date: release_date, genre: genre, }), }); let resJson = await res.json(); if (res.status === 200) { setTitle(""); setArtist(""); setReleaseDate(""); setAlbum(""); setGenre(""); } } catch (err) { console.log(err); } }; ` Here is my submit form. ` return ( <div className="App"> <form onSubmit={handleSubmit}> <input type="text" value={title} placeholder="Title" onChange={(e) => setTitle(e.target.value)} /> <input type="text" value={artist} placeholder="Artist" onChange={(e) => setArtist(e.target.value)} /> <input type="text" value={release_date} placeholder="Year" onChange={(e) => setReleaseDate(e.target.value)} /> <input type="text" value={album} placeholder="Album" onChange={(e) => setAlbum(e.target.value)} /> <input type="text" value={genre} placeholder="Genre" onChange={(e) => setGenre(e.target.value)} /> <button type="submit">Create</button> </form> </div> ); } export default AddSong; ` When I click submit on the form, Chrome gives me an error saying "Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". I know it has … -
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.