Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tag inside of another in Django HTML
I am trying to do this: {% block content %} {% with card_header='Войти на сайт' card_body="{% include 'includes/form.html' %}" %} {% include 'includes/card.html' %} {% endwith %} {% endblock %} But it seems like I can not add tag inside of tag, I tried other hints from other stack overflow post, but none of them worked for my case. This is what I tried: {% include 'includes/form.html' as card_body_url %} {% block content %} {% with card_header='Войти на сайт' card_body=card_body_url %} {% include 'includes/card.html' %} {% endwith %} {% endblock %} {% block card_body %} {% include 'includes/form.html' %} {% endblock card_body %} {% block content %} {% with card_header='Войти на сайт' %} {% include 'includes/card.html' %} {% endwith %} {% endblock %} -
Exception Value: Failed loading libasound.so.2: libasound.so.2: cannot open shared object file: No such file or directory (Django/heroku)
I made a drowsiness detector for driving using django. I tried deploying it on heroku and everything seems to be working fine except as soon as I try to open the camera, I get the error: Exception Value: Failed loading libasound.so.2: libasound.so.2: cannot open shared object file: No such file or directory All the other pages are working fine, you can try it out here. As soon as you click on Start Driving it throws this exception. The app is working fine in localhost. Please help! -
Django Migrations: How to resolve error of charfield to datetimefield
What im doing is i clone my prod database to sandbox. and I'm getting error while migrate Cause of previously I made charfield to datetime field. And then datetime field to Charfield after few migrations. So how do I solve below error: Error : python manage.py migrate System check identified some issues: WARNINGS: Operations to perform: Apply all migrations: admin, auth, contenttypes, pro_auth, service_list, sessions, token_blacklist Running migrations: Applying pro_auth.0002_alter_userorder_order_booking_time...Traceback (most recent call last): File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidDatetimeFormat: invalid input syntax for type timestamp with time zone: "2021-10-10 10.00" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/root/sandbox/sandbox_venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, … -
how can i solve this pipenv install error - django project on vscode
Hello_world! This is my first post - ever - on the internet so give me some credit haha...Im basically a noob programmer who had this crazy idea of giving a shot at Django so I can (hopefully) create a humble plataform website with login, CRUD etc, even though i just know very basic python and still have a long way to learn all the frontend + react... So, im basically doing a course from Mosh (kinda famous youtube instructor) and got really (really) stuck on [Part 1 of the Django class -> Django ORM -> 3-Resetting the Database] - and i have no idea how to fix and i don't know no programmer in the real world to help me smh On this class, Mosh wants to make sure that we are on the same page, so he tells us to drag and drop into VSCode a specific folder (that contains the django project) that he makes it available at the beginning of the course. I followed all the steps but, as soon as i tried to run "pipenv install" on my terminal (as he tells us to right after dropping that folder), i get the following (BIG) error message...here … -
How to convert to crispy forms simple and fast?
I have project that at the end I realised that I need to switch to crispy forms. I'll provide code, maybe you have simple and fast solution without doing it again. Form needs to have two buttons; browse and submit button. This is upload_document.html {% extends "base.html" %} {% load static %} {% block content %} <!-- Upload form. Note enctype attribute! --> <form action="{% url "upload_doc" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} This is forms.py class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') This is views.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'upload_document.html', { 'form': form, 'page_title':page_title }) -
How to limit number of entries from GeoDjango Postgis django-rest-framework query?
I've built basic Django mapping functionality through this tutorial but Python keeps blowing through 32GB of ram and/or the browser crashes, presumably because the query isn't limited to the first n results and the DB has millions of entries. My "vietsets.py": from rest_framework import viewsets from rest_framework_gis import filters from core.models import Tablename from core.serializers import MarkerSerializer class MarkerViewSet(viewsets.ReadOnlyModelViewSet): bbox_filter_field = "geom" filter_backends = (filters.InBBoxFilter,) queryset = Tablename.objects.all() serializer_class = MarkerSerializer I think InBBoxFilter needs to be elaborated upon but the docs don't seem to mention any further options. The docs say "if you are using other filters, you’ll want to include your other filter backend in your view" giving the example, filter_backends = (InBBoxFilter, DjangoFilterBackend,), but I only want to limit the number of results for the functionality InBBoxFilter already provides. Can I write some kind of DjangoFilterBackend to limit results? Or is this best addressed through django-rest-framework functionality? How can I tell it to limit the number of results, or otherwise improve performance when using big databases? -
how to get access to post data incoming inside a Django middleware?
I am writing a middleware due to which i need to access post data but none of the answers are solving my doubt, i am reading the data like this but this is working in postman but giving error in browser dict_str = request.body.decode("UTF-8") any help is highly appreciated -
Uploaded Media files are only served after I reload the django server
I'm quite new to django development, tired of searching for this particular case of mine. I have django app running on my windows 10 with debug = False. I am just about to deploy my app to digital ocean droplet. I am facing so many deployment and static + media file issues. I kind of figured out static files, they are fine, media files are also loaded. But, when I upload a new image, access it directly, it says the resource I'm looking for isn't found. But it's 100% uploaded to media/images folder, and I can see it. Today, I think I found the some solution, I can access the media files only after I reload the django server. I want to know why is that? My settings.py file # Application definition INSTALLED_APPS = [ 'livereload', 'mnotes.apps.MnotesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', ] DJANGORESIZED_DEFAULT_SIZE = [100, 100] DJANGORESIZED_DEFAULT_QUALITY = 75 DJANGORESIZED_DEFAULT_KEEP_META = True DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG' DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"} DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'livereload.middleware.LiveReloadScript', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'MarketingNotes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
How to cache the data pulled from BigQuery in Django?
I have a webapp that pulls data from BigQuery into my Django views, which then will be passed as a context to the frontend templates. However, this data pulling process will occur initially when I open the web, and will occur again everytime I refresh the page. Is there a way I can cache the data I have pulled? My views.py code looks similarly to this: def index(request): client = bigquery.Client() dataset_id = "project-id.dataset-id" tables = client.list_tables(dataset_id) tables_list = [table.table_id for table in tables] data_list = [] for table_id in tables_list: query_string = f""" SELECT * FROM `project-id.dataset-id.{table_id}` """ query_job = ( client.query(query_string) .result() ) records = [dict(row) for row in query_job] data_list.extend(records) df = pd.DataFrame(data_list) ... # Data manipulation syntax here using pandas dataframe ... data_json = df.to_json(orient="records") context = {'data_json': data_json} return render(request, 'template_name', context) I passed the data as a JSON to the context because I'm passing it to a React frontend. -
Django Crispy Formsets CSS
I am trying to utilize crispy forms & bootstrap with formsets but I can't seem to figure out the CSS styling. I need to style it in the backend as I want to allow the client to dynamically add more of the same form, and when you add an empty form into the HTML it does not keep the same styling. create.html <!--RECIPE INGREDIENTS--> {% if formset %} <h3>Ingredients</h3> {{ formset.management_form|crispy }} <div id='ingredient-form-list'> {% for ingredient in formset %} <div class='ingredient-form row'> {{ ingredient }} </div> {% endfor %} </div> forms.py class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['name', 'quantity', 'unit', 'description'] labels = { 'name': "Ingredient", "quantity:": "Ingredient Quantity", "unit": "Unit", "description:": "Ingredient Description"} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('name', css_class='form-group col-md-6 mb-0'), Column('quantity', css_class='form-group col-md-4 mb-0'), Column('unit', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), Row( Column('description', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), ) views.py def recipe_create_view(request): form = RecipeForm(request.POST or None) RecipeIngredientFormset = formset_factory(RecipeIngredientForm) formset = RecipeIngredientFormset(request.POST or None) context = { "form": form, "formset": formset, } if request.method == "POST": #print(request.POST) if form.is_valid() and formset.is_valid() and instructionFormset.is_valid(): parent = form.save(commit=False) parent.user = request.user parent.save() #recipe ingredients for form in … -
"NoModuleNamed" when using custom logging filters
Im trying to use different formatters for different log levels, for that I created a custom filter. This is the error I get: Traceback (most recent call last): File "...\Python\Python39\lib\logging\config.py", line 385, in resolve found = self.importer(used) ModuleNotFoundError: No module named 'logging_formatter' In my_django_project/logging_formatter/formatter_filter.py I have the filter named FilterLevels And the settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'info_formatter': { 'format': '{asctime}|{levelname}|{message} [in {funcName}]', 'datefmt': '%Y-%m-%d %H:%M:%S', 'style': '{', }, 'error_formatter': { 'format': '{asctime}|{levelname}|{message} [in {filename}:{funcName}:{lineno}]', 'datefmt': '%Y-%m-%d %H:%M:%S', 'style': '{', }, }, 'filters': { 'filter_info_level': { '()': 'logging_formatter.formatter_filter.FilterLevels', 'filter_levels' : [ "INFO" ] }, 'filter_error_level': { '()': 'logging_formatter.formatter_filter.FilterLevels', 'filter_levels' : [ "ERROR" ] }, 'filter_warning_level': { '()': 'logging_formatter.formatter_filter.FilterLevels', 'filter_levels' : [ "WARNING" ] } }, 'handlers': { 'app_info': { 'formatter': 'info_formatter', 'filters': ['filter_info_level'], 'class': 'logging.StreamHandler', 'filename': 'my_django_project/logs/app.log', }, 'app_error': { 'formatter': 'error_formatter', 'class': 'logging.StreamHandler', 'filename': 'my_django_project/logs/app.log', 'filters': ['filter_error_level'], }, }, 'loggers': { 'my_django_project.app': { 'handlers': ['app_info', 'app_error'], 'level': 'DEBUG', }, }, } -
Django many to many field not showing on admin - Legacy database
I want to show a many to many field that was created in nocodb on django admin panel. Therefore the database schema were created by nocodb. I want to also edit the db with django. The many to many tags field doesn't show in django admin. There is no error message. Can someone help? I used inspectdb to create the models and admin_generator to create the admin code for the nocodb fields. I tried adding an id column in the join table. I made it the primary key. That didn't seem to help. ================================================= The following pic shows that the tags are not shown on the page. ================================================= This is how it looks in nocodb. ================================================= These are the tables in mysql. You can see the note table, tag table, and the note-tag table. ================================================= This is a post tagg many to many I created in Django, and it works. ================================================= The models.py and admin.py follow: models.py # ================================================= class Tagg(models.Model): title = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return str(self.id) + " - " + self.title class Post(models.Model): # Fields created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) title = models.CharField(max_length=230) body = models.TextField(max_length=32100, default=None, blank=True, null=True) taggs = models.ManyToManyField(Tagg) … -
Heroku error H14 "no web processes running"
When I trying to open my app in Heroku, I receive this message: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail heroku logs --tail : 2021-11-25T18:34:03.593007+00:00 heroku[router]: at=error code=H14 desc="No web processed=GET path="/" host=football-players-stats-api.herokuapp.com request_id=a5af4869-7e84-46a69b fwd="186.58.9.173" dyno= connect= service= status=503 bytes= protocol=https 2021-11-25T18:34:12.174019+00:00 heroku[router]: at=error code=H14 desc="No web processed=GET path="/favicon.ico" host=football-players-stats-api.herokuapp.com request_id=e168a97-4c41a2513edb fwd="186.58.9.173" dyno= connect= service= status=503 bytes= protocol=ht This is my Procfile web: gunicorn app.wsgi --log-file - Comands heroku ps:scale web=1: Scaling dynos... ! ! Couldn't find that process type (web). heroku ps Free dyno hours quota remaining this month: 1000h 0m (100%) Free dyno usage for this app: 0h 0m (0%) For more information on dyno sleeping and how to upgrade, see: https://devcenter.heroku.com/articles/dyno-sleeping No dynos on ⬢ football-players-stats-api I did this but it still doesn't work. heroku buildpacks:clear heroku buildpacks:add heroku/python git commit --allow-empty -m "Adjust push heroku master" git push master I dont know where is the problem. Id really appreciate if you could help me. -
Django: How to load initial data for a foreignkey field
I'm trying to create some initial data with Django fixtures. Now my model has a field with ForeignKey to another model. How how can I handle this in the json file [ { "model":"src.Pricing", "pk": 1, "fields": { ... ... } }, { "model":"src.PricingFeature", "pk": 1, "fields": { ... "pricing": "", ... } } ] The second one has field called pricing, and the is supposed to be an instance of src.Pricing (the first dictionary in the list). How can I get the instance and pass it -
How can i add import export to a table and also order the columns in django
I want to add import export button and at the same time order the table columns but i cant pass 3 parameters on the functions list_display = ('id_etudiant','nom_etudiant','prenom_etudiant','Telephone','Adresse','Filiere') search_fields = ('nom_etudiant',)``` ```class userdat(ImportExportModelAdmin): pass``` ```admin.site.register(Etudiant,userdat,OrderEtudiant)``` here is the problem i can't pass pass three parameters to the function -
POST to view not updating database
I have a view that I want to be able to add an event to a project. There are 2 models, one for the Project and one for Event. Project Model class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) ckeditor_classic = models.TextField(blank=True) project_category = models.CharField(max_length=15, blank=True) project_type = models.CharField(max_length=10, blank=True) project_platform = models.CharField(max_length=25, blank=True) project_marketcap = models.IntegerField(blank=True, null=True) project_stage = models.CharField(max_length=25, blank=True) project_blockchain = models.CharField(max_length=25, blank=True) project_investors = models.ManyToManyField(Investor, blank=True) project_developers = models.ManyToManyField(Developer, blank=True) def __str__(self): return str(self.project_name) Event Model class Event(models.Model): project = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE) event_name = models.CharField(max_length=100) event_date = models.DateTimeField(blank=True) event_url = models.URLField(max_length=100, blank=True) def __str__(self): return str(self.event_name) The event has a ForeignKey to the Project. when I go to the project page for a specific project, I then click a button to enable me to create an event. The Project Name is pre-populated using this URL path('apps/add_event/<int:project_id>', view=AddEvent, name="add_event"), This creates a simple form that i can then assign a name and date for the event, but when i POST (Submit) the data doesn't get added to the database. I do get a POST in the logs [25/Nov/2021 21:37:11] "POST /apps/add_event/3 HTTP/1.1" 302 0 I can't work out why the … -
i am getting an error a bytes-like object is required, not 'str' and my code is as follows
'''the view is as follows and it brings the error at line password = password.split("b'")''' if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] cache.set('email',email) fact = User.objects.filter(email=email).values('username') username = fact[0]['username'] username = username.encode(encoding='UTF-8') password = password.encode(encoding='UTF-8') password = password.split("b'") print(username) print(str(password)) -
django-import-export does not update when unique
I have this unique field on my Profile model: email = models.EmailField(max_length=200, unique=True) and I have this ProfileResource: class ProfileResource(resources.ModelResource): # associated_issuer = fields.Field(attribute='add_associated_issuer', widget=ManyToManyWidget(Issuer, field='name'), column_name='Associated Issuer') email = fields.Field(attribute='email', widget=CharWidget(), column_name='email') class Meta: model = Profile clean_model_instances = True import_id_fields = ('id', 'email') def before_import_row(self, row, row_number=None, **kwargs): try: self.email = row["email"] except Exception as e: self.email = "" try: if row["id"] == '': row["id"] = None self.id = row["id"] except Exception as e: self.id = None try: self.firstname = row["firstname"] except Exception as e: self.firstname = "" try: self.lastname = row["lastname"] except Exception as e: self.lastname = "" Now when I try to do an import from a file, I receive this error: I need to be able to do an update_or_create method, but where do I add that code? I tried doing it on an after_import_instance but it did not work. I also tried on import_row like this: def import_row(self, row, instance_loader, using_transactions=True, dry_run=False, **kwargs): try: Profile.objects.update_or_create(email=self.email) except Exception as e: print(e, file=sys.stderr) but it produced this error: Exception Value: 'NoneType' object has no attribute 'import_type' Any insights on a fix would be appreciated. -
Unable to post data to foreign key table in Django
I am an absolute beginner to Django and I am trying to check the POST method by populating the value to the foreign key table. I have two tables. Please guide me on where I am wrong. Table for Category that has 2 entries, i.e., Coffee(PK = 1) and Desserts (PK = 2) Table for Items From models.py: class Category(models.Model): cId = models.AutoField(primary_key=True) categoryName = models.CharField(max_length=20, unique=True) def __str__(self): return self.categoryName # return[self.categoryName, self.cId] # return self.cId class Item(models.Model): Id = models.AutoField(primary_key=True) itemName = models.CharField(max_length=30,unique=True) cId = models.ForeignKey(Category,on_delete=CASCADE) From views.py: def main(request): return render(request, "index.html") def send(request): if request.method == "POST": a = request.POST.get("a"); b = request.POST.get("b"); obj = Item(itemName = a, cId =b); obj.save() return HttpResponse("sent") else: return HttpResponse("form submission failed") From urls.py(app): urlpatterns = [ path('', views.main, name="main"), path('send', views.send, name='send') ] From HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css.css' %}"> <title>CHECK-POST-METHOD</title> </head> <body> <div class = "container"> <form method = "post" action = "send" class = "form"> {% csrf_token %} <label for="a">Item Name</label> <input type="text" name="a" id="a" maxlength="30"> <label for="b">PASS FOREIGN KEY--CATEGORY ID</label> <input type="number" name="b" id="b" maxlength="5"> <button type="submit">SUBMIT</button> … -
request.user becomes anonymous upon refreshing page django rest framework
I am finishing up a django rest framework react website and need help. When I log in with a user and go to the author dashboard page, all the api calls work. If I leave the page and then use the link in the navbar all the api calls work. However, if I refresh the page, one of the api calls stops working and says that request.user is an anonymous user but all the other ones work. Here is the api view giving me trouble: @api_view(['GET']) def author(request): print(request.user) if request.user.is_authenticated: author = request.user serializer = AuthorAccessSerializer(author, many=False) return Response(serializer.data) else: return HttpResponse(status=400) And here is a view that works on the same refresh: @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def author_auth(request): if request.method == 'GET': print(request.user) requires_superuser = request.query_params['req-supuser'] if requires_superuser == "True": requires_superuser = True else: requires_superuser = False if request.user.is_authenticated: if requires_superuser == True: if request.user.is_superuser: return Response('Authenticated') return HttpResponse(status=401) return Response('Authenticated') return HttpResponse(status=401) -
How to use left join orm?
My model class Ad_company(models.Model): idx = models.AutoField(primary_key=True) subject = models.CharField(max_length=255) memo = models.CharField(max_length=255) content = models.TextField() is_display = models.CharField(max_length=1) writer = models.CharField(max_length=255) write_date = models.DateTimeField() update_date = models.DateTimeField() delete_date = models.DateTimeField() deadline_date = models.DateTimeField() reply = models.IntegerField(blank=True) hits = models.IntegerField(blank=True) ad_apply = models.IntegerField(blank=True) ad_category1 = models.CharField(max_length=255) ad_category2 = models.CharField(max_length=255) ad_place = models.CharField(max_length=255) ad_age = models.CharField(max_length=255) ad_sex = models.CharField(max_length=255) ad_budget = models.BigIntegerField() ad_length = models.CharField(max_length=255) is_done = models.CharField(max_length=1) is_pay = models.CharField(max_length=1) ad_service = models.CharField(max_length=255) ad_object = models.CharField(max_length=255) is_file = models.CharField(max_length=1) ad_require = models.CharField(max_length=255) class Meta: managed = False db_table = 'ad_write_company' class Ad_company_apply(models.Model): idx = models.AutoField(primary_key=True) parent_idx = models.IntegerField() username = models.CharField(max_length=255) content = models.TextField() date = models.DateTimeField(default=datetime.now, blank=True) budget = models.BigIntegerField() term = models.IntegerField() is_done = models.CharField(max_length=1) SELECT * FROM ad_write_company INNER JOIN ad_write_company_apply ON ad_write_company.idx = ad_write_company_apply.parent_idx where ad_write_company_apply.is_done = 1 and ad_write_company_apply.username = 'asdffdsa' This is my query. but I can not make join query with orm. Sorry for question is too short. And Is my query right? I not sure of that. Thanks for answer. or do you guys have other good idea? -
Combine Django and Bootstrap 5 Modal with Ajax
How to have button/link that can target object pk like a certain post with {{obj.pk}} then open a modal edit modal and delete modal. Then the modal can edit and delete successfully without refresh using AJAX (Fetch API or Jquery). I have the problem to target the modal to open the post with certain PK. I cannot use id="editPost{{obj.id}}" or id="deletePost{{obj.id}}" to target the modal because then I need to put the modal in forloop then the modal will be repeated for each post. Here a some of the code: {% for obj in page_obj %} <li> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#editPost" href="{% url 'post-update' obj.pk %}">Edit Post</a> </li> <li> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#deletePost" href="{% url 'post-delete' obj.pk %}">Delete Post</a> </li> <div id="post{{obj.id}}" class="box-content"> <p class="box-text mb-2">{{ obj.content }}</p> <span class="username">{{ obj.username }}</span> </div> {% endfor %} <div class="modal fade" id="deletePost" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete Post?</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>Are you sure you want to delete your post?</p> </div> <div class="modal-footer"> <button type="button" class="rvg-button-small" data-bs-dismiss="modal">Cancel</button> <button type="button" class="rvg-button-small">Delete</button> </div> </div> </div> </div> The way I achieve AJAX is using <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#editPost" onclick="EditPost('{{ obj.id }}')"> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#deletePost" … -
Django takes ubuntu username to connect database instead of db user from settings.py
I trying to run django website on aws ec2 machine (ubuntu). my postgresql database running on aws RDS when I run $python manage.py runserver, it throws this error: django.db.utils.OperationalError: connection to server at "xxxxx.xxxxx.us-east-2.rds.amazonaws.com" (xxx.xx.xx.xxx), port 5432 failed: FATAL: password authentication failed for user "ubuntu" basically django trying to connect database using ubuntu user instead of postgres user in settings.py my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('NAME'), 'USER': config('USER'), 'PASSWORD':config('PASSWORD'), 'HOST':config('HOST') #'HOST':'localhost' } } .env file: SECRET_KEY=xxxx DEBUG=True HOST=xxx.xxx.us-east-2.rds.amazonaws.com NAME=xxxx USER=postgres PASSWORD=xxxxxx my password has special special char '#' -
Gunicorn can't access lets encrypt files
(venv) ubuntu@ip-172-31-6-77:~/redrebelgames_python$ gunicorn redrebelgames_python.wsgi:application [2021-11-25 20:01:09 +0000] [3758] [INFO] Starting gunicorn 20.1.0 Traceback (most recent call last): File "/home/ubuntu/redrebelgames_python/venv/bin/gunicorn", line 8, in <module> sys.exit(run()) File "/home/ubuntu/redrebelgames_python/venv/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 67, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ubuntu/redrebelgames_python/venv/lib/python3.8/site-packages/gunicorn/app/base.py", line 231, in run super().run() File "/home/ubuntu/redrebelgames_python/venv/lib/python3.8/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/ubuntu/redrebelgames_python/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 198, in run self.start() File "/home/ubuntu/redrebelgames_python/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 155, in start self.LISTENERS = sock.create_sockets(self.cfg, self.log, fds) File "/home/ubuntu/redrebelgames_python/venv/lib/python3.8/site-packages/gunicorn/sock.py", line 162, in create_sockets raise ValueError('certfile "%s" does not exist' % conf.certfile) ValueError: certfile "/etc/letsencrypt/live/api.redrebelgames.com/cert.pem" does not exist How do I allow gunicorn to access these files? For some reason it's not working and simply changing the chmod permissions won't work because certbot will eventually change them back. -
Connect the username when sending a report in django
I am beginner to django and I am trying to create a site to send reports after creating a profile, but when I send the report, the username of the author of the report is not saved, Just (None). I searched a lot about it and did not find it models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, verbose_name=("user"), null=True, on_delete=models.CASCADE) identity_No = models.IntegerField( blank=True, null=True) mobile_No = models.IntegerField( blank=True, null=True) city = models.CharField( max_length=15,null=True) class Meta: verbose_name =("Profile") verbose_name_plural =("Profile") def __str__(self): return '%s' %(self.user) class Report(models.Model): user = models.ForeignKey(User, verbose_name=("user"), on_delete=models.CASCADE) Report_type =models.CharField( max_length=100, blank=True, null=True) Region =models.CharField( max_length=30, blank=True, null=True) city =models.CharField( max_length=30, blank=True, null=True) sector =models.CharField( max_length=30, blank=True, null=True) report =models.TextField( max_length=3000, blank=True, null=True) files =models.FileField( blank=True, null=True) class Meta: verbose_name =("Report") verbose_name_plural =("Report") def __str__(self): return '%s' %(self.user) form.py Shorten the time, attach only the report class ReportForm(forms.ModelForm): class Meta: model = Report fields = ['Report_type', 'Region', 'city','sector','report','files' ] view.py def report(requst): if requst.method == 'POST': report_form = ReportForm(requst.POST) if report_form.is_valid() : report_form.save() return redirect ('accounts:home') else: report_form = ReportForm() return render(requst, 'user/report.html', { 'report_form': report_form, enter image description here })