Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inherit bootstrap properties to a custom class
I want my custom class pm_btn to get all the properties that bootstrap's btn class has. One way is to use the actual source code of the btn class. But I believe that there has to be a better way. Therefore, I tried a bit of scss, where inheriting properties is quite easy and trivial using @extend as follows: .pm_btn{ @extends .btn; } But this throws error : Error: The target selector was not found. Use "@extend .btn !optional" to avoid this error. I am trying to achieve: apply bootstrap like classes to django-postman classes. Please suggest me how can I achieve this, if I am on the right track by choosing SCSS or should I think in some other directions. Thank you for your valuable time. -
URL is adding automatically - Django
I have got a problem while redirecting to the edit form. SO what I am doing is that whenever user clicks on edit button it redirects to "editadmin/{{admin.id}}" using form action = "editadmin/{{admin.id}}" in HTML. URL path is path("editadmin/<int:id>", views.editadmin, name="editadmin") path("update/<int:id>", views.updateadmin, name="updateadmin") Views.py @csrf_exempt def editadmin(request, id): admin = Admin.objects.get(id=id) return render(request, "editadmin.html", {"admin": admin}) @csrf_exempt def updateadmin(request, id): if request.method == "POST": admin_id = request.POST["admin_id"] admin_id = str(admin_id).strip().upper() name = request.POST["name"] name = str(name).strip() if db_name equals to name: messages.error(request, "Admin name already exists") return redirect("editadmin/" + str(id)) editadmin.html <form method="post" class="post-form" action="/update/{{admin.id}}"> <input type="hidden" name="id" id="id" required maxlength="20" value="{{ admin.id }}"/> {% csrf_token %} <div class="form-group row"> <label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Admin ID : </h4></label> <div class="col-sm-4"> <input type="text" name="admin_id" required style="margin-left:20px; height:38px; width:300px; border-radius: 5px" id="admin_id" value="{{ admin.admin_id }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Name : </h4></label> <div class="col-sm-4"> <input type="text" name="name" style="margin-left:20px; height:38px; border-radius: 5px; width:300px" required id="name" value="{{ admin.name }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <button type="submit" class="btn btn-success" style="margin-left:210px">Submit</button> </div> </div> So what I want is that Whenever user submits invalid name in editadmin.html (URL - editadmin/1 ), it should redirect to the same URL … -
Django: PosixPath object is not iterable
Before version 3.x of Django it was possible to define templates, static and media folder using os.path. Into settings.py I had this configuration: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . . . TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], . . . STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static-folder') MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media-folder') MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] Now the settings are changed and I need to use Path: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent I'm following this new way but I think something is not clear for me. My new settings.py configuration is: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates', ], . . . STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static-folder' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media-folder' STATICFILES_DIRS = BASE_DIR / 'static' But with that configuration I see this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/maxdragonheart/DEV_FOLDER/MIO/Miosito/WebApp/backend/.env/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File … -
django.db.utils.ProgrammingError: (1146, "Table 'online_examination_system.studentapp_courses' doesn't exist")
I tried makemigrations, migrate, and even many methods stated in stack overflow but nothing is happening. Please tell me the reason why this happens and how can i solve it? -
How to display dynamic page before task complete in Django
I have two pages in Django, I want to display a page while a task is being done and display second page after it complete how can I do: views.py render(request, 'loading_page.html') data_processing() return render(request, 'list.html') Page one (loading_page.html) I that want to display while I am processing data. After executing that data_processing function, I want to display list.html, How can I do that. -
Working on a Fastapi project. everything is fine but PUT method is throwing error. post and Get method is working fine
the error message is sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type. [SQL: UPDATE subjects SET url=subjects.url, title=subjects.title, name=subjects.name, "desc"=subjects."desc" WHERE subjects.id = ?] [parameters: (<class 'int'>,)] (Background on this error at: http://sqlalche.me/e/13/rvf5) schema is id : str = Field(..., example="Enter Your Id") title:str name :str desc:str models is class Subject(Base): __tablename__ = "subjects" id = Column(Integer, primary_key=True) created_date = Column(DateTime,default=datetime.datetime.utcnow) url = Column(URLType) title = Column(String) name = Column(String) desc = Column(String) crud.py is async def update_subject(db: Session,title:str,name:str,desc:str,url:str,id=int): query = models.Subject.__table__.update()\ .where(models.Subject.id== id)\ .values(title=models.Subject.title,desc=models.Subject.desc, name=models.Subject.name,url=models.Subject.url) return await db.execute(query) router.py is @router.put("/subject/{id}") async def update_subject( #user : schemas.SubjectUpdate, id: int, title:str,desc:str,name:str,file: UploadFile= File(...), db: Session = Depends(get_db) ): extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png") if not extension: return "Image must be jpg or png format!" # outputImage = Image.fromarray(sr_img) suffix = Path(file.filename).suffix filename = time.strftime( str(uuid.uuid4().hex) + "%Y%m%d-%H%M%S" + suffix ) with open("static/"+filename, "wb") as image: shutil.copyfileobj(file.file, image) #url = str("media/"+file.filename) url = os.path.join(images_path, filename) subject = crud.get_subject(db,id) if not subject: raise HTTPException(status_code=404, detail="comment not found") return await crud.update_subject(db=db,name=name,title=title,desc=desc,url=url) it is throwing 500 internal server error in swagger ui and the error mentioned above in IDE. All other methods are working fine. -
Django Simple History Module + How To Directly Migrate data to History Models
We have our own custom different tables which contain log data and where data looks similar as simple history models standard. Now i want to use SimpleHisory module for my django application. how can i directly move the existing data to new simple history models(I want to move log data alone into simple history tables) I want to move data through Django migration models, not with SQL I have changed my model as below, now history table is available with me. > from django.db import models from simple_history.models import > HistoricalRecords > > class Poll(models.Model): > question = models.CharField(max_length=200) > pub_date = models.DateTimeField('date sample') > history = HistoricalRecords() Please advise, how can save directly into history tables with some example. -
How to show only one user (user that is logged in) profile?
I'm trying to add a user profile page into my blog (in German) but when I run the server and go to user profile page, it shows profiles of all users that are in the database. I want to show only the profile of one user (the logged in one) Here is my views.py: ... class UserProfile(LoginRequiredMixin, ListView): model = Member template_name = "app/profile.html" context_object_name = "member_infos" ... And my profile.html template: ... {% for info in member_infos %} <div class="row"> <div class="col-md-3"> <div class="card card-body"> <h3 style="text-align:center;">Profil</h3> <hr /> {% if info.picture %} <img class="profile-pic" src="{{ info.picture.url }}" /> {% else %} <img class="profile-pic" src="{% static 'media/images/profile_pic/default_profile_pic.png' %}" /> {% endif %} </div> </div> <br /><br /> <div class="col-md-9"> <div class="card card-body"> <p class="card-text"> <strong>Vorname(n): </strong> {{ info.first_name }} </p> <hr /> <p class="card-text"> <strong>Nachname: </strong> {{ info.last_name }} </p> <hr /> <p class="card-text"> <strong>Telefonnummer: </strong> {{ info.contact }} </p> <hr /> <p class="card-text"> <strong>E-Mail-Adresse: </strong> {{ info.email }} </p> </div> <br /><br /> <a class="btn btn-warning ml-7" href="{% url 'edit-profile' %}"> Daten bearbeiten &rarr;</a> </div> </div> <br /><br /> {% endfor %} ... As I said, it shows up profiles of all users in my database. How to … -
Change Foreign Key name in django migration
I'm looking to change the name of a foreign key from uuid to uuid_erp. To do this i can run a migration as follows: migrations.RunSQL(''' ALTER TABLE result_suppliers RENAME COLUMN uuid TO uuid_erp; ''') By doing this i essentially want to do the migration for django, and that it does nothing when running makemigrations. However when i do run python manage.py makemigrations i see that django is trying to create the column uuid_erp (which has already been created). this gives the message: You are trying to add a non-nullable field 'uuid_erp' to resultsuppliers without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: From the makemigrations docs I see that django: Creates new migrations based on the changes detected to your models. This doesn't give a huge insight into how the changes are detected. My question is two fold: How does makemigrations decide that there is a migration to make? How can I perform this operation ? NB. … -
Question about recording, hosting, and viewing videos from a React web app, with a Django backend
I'm working on the backend of a React web app, developed in Django (and Django Rest Framework). For sake of abstraction, the application is more or less an exercise app, where a trainer can record a trainee's exercises on their phone for the trainee to review at a later time. I am just lost as to how I would accomplish this and was hoping for some recommendations of technologies or methods that I should start looking into. My main questions are: Is there a React library or toolkit that might help with the recording process? and what kind of storage should I use for the videos so they can be easily stored and streamed? Some people have suggested using YouTube, but I am wary of this as the videos will be of a personal nature, and having the videos played back to the trainee in a youtube player might make the trainees uncomfortable. Thank you all for your help! -
Django and APScheduler not running on IIS Server
We have a django app which we deployed using IIS Server. The app has been running smoothly and without any problem. However, we want to schedule a job that will run every night at 02:00. We are using APScheduler which is working perfectly fine on the django local server but it never runs on production. Here is the code I am using to run the jobs. myapp/scheduler.py def schedule(): scheduler = BackgroundScheduler() scheduler.add_job(daily_schedules, 'interval', minutes=5) # scheduler.add_job(daily_schedules, trigger='cron', hour='2') scheduler.start() def daily_schedules(): time_now = time.clock() parse_api() # my function # Keeping logs path = join(settings.FILES_DIR, 'schedulled/logs.csv') logs = pd.read_csv(path, encoding='utf-8') time_end = time.clock() - time_now logs.loc[len(logs)] = [ datetime.now().strftime('%Y-%m-%d %H:%M:%S'), time_end ] logs.to_csv(path, encoding='utf-8', index=False) print(logs) myapp/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'MyApp' def ready(self): from myapp import scheduler scheduler.schedule() Is there any particular reason why the job is not being run? Do I need to do something else or this method does not work with IIS? Since the server is being used by many developers at the same time, I would like to run the jobs as part of the django application and not run them outside in a separate server. P.S: I have read all … -
how to create two table with custom primary and Foreign key
class UserInfo(models.Model): userame=models.CharField(max_length=100,help_text='Enter user name that you want', unique=True, primary_key=True) **#want have userame as primary key** mobile_number=models.IntegerField() email=models.CharField(max_length=200) Fist_Name=models.CharField(max_length=500) Middle_name=models.CharField(max_length=500) Last_name=models.CharField(max_length=500) class Order(models.Model): username=models.OneToOneField(UserInfo,on_delete=models.CASCADE) **#user name of UserInfo table want to be foreign key in Order table** Prodduc_name=models.CharField(max_length=500) It's failing with django.db.utils.OperationalError: (1829, "Cannot drop column 'id': needed in a foreign key constraint 'woodshophome_passwor_username_id_35d147b1_fk_woodshoph' of table 'woodshophome_passwordtable'") woodshophoe is app name -
type NoneType doesn't define __round__ method
I've gone through similar questions but was not able to find a solution to my question. I have 4 cards(movie cards) and the first two are working well but the rest are not. The problem started appearing once I added some logic to views.py in order to show an average rating of each movie based on the reviews given. Here is the code in views.py def detail(request, id): movie = Movie.objects.get(id=id) reviews = Review.objects.filter(movie=id).order_by('-comment') average = reviews.aggregate(Avg('rating'))["rating__avg"] average = round(average, 1) # The problem is above(in round) but dunno how to fix it context = {'movie': movie, 'reviews': reviews, 'average': average} return render(request, 'detail.html', context) -
Is it possible to retrieve data from a database view to a model in django?
i have a view in my oracle database that joins two tables which a made vertical partitioning, now i want to retrieve the data from that view in django. Does anyone know how to make a model in django for a view? Thank You -
Leave out parent node in template
I have a MPTT category tree which I display this with {% load mptt_tags %} <ul> {% recursetree category %} <li> <a href="/.../{{ node.id }}/{{ node.slug }}">{{ node.title }}</a> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} And it looks like that country usa california france provence germany However, I would like to leave out 'country'. I tried { if not children == ancestor } and then the code When adding in the model the filter Category.objects.filter(children__isnull=True) ``` then I get only the child, so 'usa' would be left out too in this example. I hope someone can help. Thank you! -
how to prevent/ secure delete request method from any attacker in django
@method_decorator(login_required, name='dispatch') class CategoryDeleteView(DeleteView): model = Category template_name = 'board/delete.html' success_url = reverse_lazy('category-list') path('category/<int:pk>/delete', CategoryDeleteView.as_view(),name='category-delete') if a attacker runs the script from logged in user browser with random category id, how we will prevent from this kind of attacks in Django or Django rest framework -
Is there a free no-credit card postgres hosting service?
So i am trying to create a python-django app which needs the admin to upload photos, but when I host this website on heroku it deletes these files after sometime. I figured that it was what heroku does by default and I needed to host by database on another service. There is AWS and CloudSQL but they require me to put a credit card which I don't have nor do my parents, there is elephant SQL but I don't know how to use it, can someone help me with this. -
Is it possible to connect to databricks sqlanalytics service from a django app
My clients use databricks for data engineering workloads and are interested in using databricks sqlanalytics to service their BI requirements. I want to know if it is possible to connect to databricks sqlanalytics service from a django app (since most of the reports are django powered) and if so any link for the same would be really helpful. I have only worked with databricks connect before and this is fairly new to me so any help would be really appreciated. -
Dynamic filter addtion with icontains
I want to dynamically add the filter field conditionally if a search phrase exists in a custom action viewset. Is there a way to do it. I tried the following but i get SyntaxError: keyword can't be an expression field = req_serializer.validated_data['field'] search = req_serializer.validated_data['search'] qs = self.get_queryset() if search: qs.filter(field + '__icontains='=search) -
Is it possible to convert my PyQt5 GUI App into a webapp using django?
I am new to Python, i'm still learning but I have already done some first steps and I have created some GUI's with the QtDesigner tool, which looks like this: GUI 1 GUI 2 GUI 3 Number 2 is quite funcional already (at least for me :D), it has animated menu, it collects data from my sensors and draws charts (github). And now my question is: is there any way to apply this code/this GUIs into a webapplication using django? I mean, I would like to make this a webapp and I don't want to start designing from zero once again and I wonder if I could somehow use what I've already done. Thanks for any replies and help. Kind regards, Mateusz. -
Django Mysql Error no such table: auth_user
i add mysql to django. i install pymysql on venv and after i add this code to settings.py when i make migration everything goes on mysql database and even when i crate superuser it was created on plesk database server PHPmyadmin. but when i want login to admin which is created in mysql database. i'm getting error Exception Value: no such table: auth_user Exception Location: /var/www/vhosts/domain/httpdocs/python-app-venv/lib/python3.6/site- packages/django/db/backends/sqlite3/base.py, line 413, in execute import os from pathlib import Path import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '3306', } } -
django runserver command erro
OS: Windows 10 Now, for the project where the runserver command works I get this: Here is my project structure. i have install all the requirements for this project but still getting this error. I've found something where there were errors with the run server command, but none were satisfying. If this is a duplicate, I do apologies, but I'm pretty sure it isn't. If there's a need for other files and snippets of code, I'll put here everything. Thank you so much. D:. | main.py | | README.md | +---BLL | | asgi.py | | requirements.txt | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-37.pyc | settings.cpython-39.pyc | urls.cpython-37.pyc | urls.cpython-39.pyc | __init__.cpython-37.pyc | __init__.cpython-39.pyc | +---DAL | | db.sqlite3 | | __init__.py | | | +---account | | | admin.py | | | apps.py | | | forms.py | | | models.py | | | tests.py | | | views.py | | | __init__.py | | | | | +---migrations | | | | 0001_initial.py | | | | __init__.py | | | | | | | \---__pycache__ | | | 0001_initial.cpython-38.pyc | | | __init__.cpython-38.pyc | | | … -
Page not found (404) Request Method: GET ....... the current path, blog/blogpost, didn't match any of these
Hi i am trying to make blog website but while i fetch model with blogpost function in views.py its shows error that 404 page not found like ||Using the URLconf defined in mac.urls, Django tried these URL patterns, in this order: admin/ shop/ blog/ [name='BlogHome'] blog The current path, blog/blogpost, didn't match any of these. || -until i don't create model it works fine but after creating model and trying to fetch articles through post_id it throws error as page not found! -what am i missing? -Here is the codes i am using. code of blog/views.py -> enter image description here code of blog/urls.py -> enter image description here code of mac/views.py -> enter image description here code of blog/adminpy -> enter image description here code of blog/models.py -> enter image description here terminal error while loading blogpost page -> enter image description here -
Unable to understand the django-quickbook webco
I am working on a Django web application and I want to push data to Quickbook Desktop. So i was following this link. https://github.com/ricardosasilva/django-to-quickbooks-connector#readme I mean How to use it? there is no documentation -
Django ORM Need help speeding up query, connected to additional tables
Running Django 1.6.5 (very old i know but can't upgrade at the moment since this is production). I'm working on a view where I need to perform a query and get data from a couple other tables which have the same field on it (though on the other tables the ord_num key may exist multiple times, they are not foreign keys). When I attempt to render this queryset into the view, it takes a very long time. Any idea how i can speed this up? view queryset: qs = Outordhdr.objects.filter( status__in=[10, 81], ti_type='@' ).exclude( ord_num__in=Shipclosewq.objects.values('ord_num') ).filter( ord_num__in=Pickconhdr.objects.values_list('ord_num', flat=True) ).order_by( 'sch_shp_dt', 'wave_num', 'shp_dock_num' ) Models file: class Outordhdr(models.Model): ord_num = models.CharField(max_length=13, primary_key=True) def get_conts_loaded(self): return self.pickcons.filter(cont_dvrt_flg__in=['C', 'R']).aggregate( conts_loaded=models.Count('ord_num'), last_conts_loaded=models.Max('cont_scan_dt') ) @property def conts_left(self): return self.pickcons.exclude(cont_dvrt_flg__in=['C', 'R']).aggregate( conts_left=models.Count('ord_num')).values()[0] @property def last_conts_loaded(self): return self.get_conts_loaded().get('last_conts_loaded', 0) @property def conts_loaded(self): return self.get_conts_loaded().get('conts_loaded', 0) @property def tot_conts(self): return self.conts_loaded + self.conts_left @property def minutes_since_last_load(self): if self.last_conts_loaded: return round((get_db_current_datetime() - self.last_conts_loaded).total_seconds() / 60) class Meta: db_table = u'outordhdr' class Pickconhdr(models.Model): ord_num = models.ForeignKey(Outordhdr, db_column='ord_num', max_length=13, related_name='pickcons') cont_num = models.CharField(max_length=20, primary_key=True) class Meta: db_table = u'pickconhdr'