Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Offline Forms
I am looking to build a web-app that focuses on users submitting forms. Sometimes the users may be in a remote area with limited connection and I am looking for information on how the web app can hold the form submission until a network connection is established. What packages or resources are available for this use-case? -
how to return query in key value like formate, how to add multiple queries to return Response
class Movie(models.Model): production_house = models.CharField(max_length=50) title = models.CharField(max_length=100) genre = models.CharField(max_length=100) year = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) # When it was create updated_at = models.DateTimeField(auto_now=True) # When i was update creator = models.ForeignKey('auth.User', related_name='movies', on_delete=models.CASCADE) class ProductionHouse(models.Model): p_name = models.CharField(max_length=50) p_address = models.CharField(max_length=100) owner = models.CharField(max_length=50) i am working on an existing project, all the tables are flat, no foreign key. i have to return query from two tables. see the models, i need to return ProductionHouse as key and all the movies that are prouduced by this ProductionHouse will be value. for more clarity "ProductionHouse1":{ "title":"title1" "genere":"genere1" all the fields }, { "title":"title2" "genre":"genere3" all the fields } "ProductionHouse2":{ "title":"title1" "genre":"genere1" all the fields }, or simple "productionHouse1":{ movies queryset1 movies queryset2 movies queryset3 ... }, "productionHouse2":{ movies queryset1 ... }, and so on -
Count number of queries with DEBUG=False
In my Django application, I want to count the number of queries made by each endpoint. I want to run this in production, so I cannot rely on any of the techniques I found with regular Django SQL logging that is only enabled when DEBUG=True, like adding a SQL logger or relying on django.db.connection.queries. Is there a context manager that works similar to self.assertNumQueries() in test cases that can be run in production like this? def my_view(request): with count_sql_queries() as nr_queries: response = business_logic() logger.debug(f'There were {nr_queries} queries made') return response -
How do I safely delete a model field in Django?
I need to delete fields from an existing django model that already have a few object associated with it. Deleting the fields from models.py gives me an error (obviously as there are table columns still associated with them). The data in body2 and body3 are not necessary for my app. I have copied that data from those fields to the body field. How would I go about deleting these fields without dropping the table entirely and thereby losing all my data? class Post(models.Model): #some fields body =EditorJsField(editorjs_config=editorjs_config) body2 =EditorJsField(editorjs_config=editorjs_config) body3 =EditorJsField(editorjs_config=editorjs_config) I deleted body2 and body3 and ran migrations and when creating a new object, I get errors such as this. django.db.utils.IntegrityError: null value in column "body2" of relation "second_posts" violates not-null constraint DETAIL: Failing row contains (20, Wave | Deceptiveness, and unpredictability of nature, 2021-07-19 13:40:32.274815+00, 2021-07-19 13:40:32.274815+00, {"time":1626702023175,"blocks":[{"type":"paragraph","data":{"tex..., null, null, Just how unpredictable is nature? Nature is all around us, yet, ..., image/upload/v1626702035/dfaormaooiaa8felspqd.jpg, wave--deceptiveness-and-unpredictability-of-nature, #66c77c, l, 1, 1, 0). This is the code that I'm using to save the sanitized data(after I've deleted those fields of course.) post = Posts.objects.create( body=form.cleaned_data.get('body'), # ) -
error loading django module with Python 3.8.10 and conda
I'm completely new to Python, and I'm struggling with the following error: "There was an error loading django modules. Do you have django installed?" I've installed Anaconda correctly, and succesfully installed Python 3.8.10 (both on Mac OS 11.4). I've succesfully created the conda environment: $ conda env create -f my_env.yml and made sure django is installed within conda: conda install django Which gives: Collecting package metadata (current_repodata.json): done Solving environment: done # All requested packages already installed. pip install django also gives the following: (my_env) mycomputer:~ mycomputer$ pip install django Requirement already satisfied: django in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (3.2.5) Requirement already satisfied: asgiref<4,>=3.3.2 in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (from django) (3.4.1) Requirement already satisfied: pytz in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (from django) (2021.1) Requirement already satisfied: sqlparse>=0.2.2 in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (from django) (0.4.1) (my_env) mycomputer:~ mycomputer$ However, when I run the following: python3 manage.py migrate It still tells me there's an error and asks if django is installed. Where am I going wrong? I see django in conda: conda list | grep django Gives me django 3.2.5 pyhd3eb1b0_0 But I don't see the path in the Python.Framework: python3 import sys for p in sys.path: print(p) Returns only: /Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8 /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages Any suggestions greatly appreciated as I've spent hours … -
How do I create different users (eg 'author' and 'commenter') in Custom User?
Need help w some fundamentals related to Django's User--and CustomUser(s): Working on Mozilla Django Tutorial's mini blog challenge, I created a CustomUser in app "accounts" (using tips from this tutorial). CustomUser appears as two foreign-key items in model Post in the app "blog": author and commenter. How do I define permissions/privileges for author and commenter? In CustomUser? or in views.py? Or should I have two separate classes for them? The complete code is on GitHub # accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass # Should I create the author and commenter classes here? #settings.py AUTH_USER_MODEL = 'accounts.CustomUser' #blog/models.py class Post(models.Model): post = models.TextField(max_length=1000) author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="posts", on_delete=models.CASCADE ) -
TypeError: 'str' object is not callable , error while iterating 2 lists
I am implementing bulk create but while iterating using destructuring i am getting this error, my view job_skill_set = [] for job_skll, job_lvl in zip(job_skill_, job_skill_level): skil_set = Skillset.objects.get(skill_name=job_skll) job_skill_set.append(Job_Skillset( skill=skil_set, job_post=job_pst, skill_level=job_lvl)) Job_Skillset.objects.bulk_create(job_skill_set) return redirect('/users/dashboard') error TypeError: 'str' object is not callable trace Traceback (most recent call last): File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\atif\PycharmProjects\my_proj\mysite_jobportal\job_management\views.py", line 50, in create_job for job_skll, job_lvl in zip(job_skill_, job_skill_level): Exception Type: TypeError at /users/create_job/ Exception Value: 'str' object is not callable -
Django Rest : failed to update custom user model with Serializer
I'm trying to update custom user model and here's what I'm doing. class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="users", null=True, blank=True) birthday = models.DateField(blank=True, null=True,) gender = models.CharField(max_length=100, choices=Gender_Choices, blank=True, null=True,) class UserUpdateSerializer(serializers.ModelSerializer): user_profile = ProfileSerializer(source='user') class Meta: model = User fields = ('user_profile',) def update(self, instance, validated_data): user_profile_data = validated_data.pop('user_profile' ,None) if user_profile_data is not None: instance.user_profile.profile_pic = user_profile_data['profile_pic'] instance.user_profile.birthday = user_profile_data['birthday'] instance.user_profile.gender = user_profile_data['gender'] instance.user_profile.save() return super().update(instance, validated_data) class ProfileAPI(generics.UpdateAPIView): queryset = Profile.objects.all() serializer_class = UserUpdateSerializer permission_classes = (permissions.IsAuthenticated,) def get_object(self): queryset = self.filter_queryset(self.get_queryset()) # make sure to catch 404's below obj = queryset.get(pk=self.request.user.id) return obj after I did all this it now if I make a put request {"user_profile":["This field is required."] and when tried to make a patch request it doesn't update at all. can you please help me what i'm doing wrong. -
Django sow list of file paths created
I have a Django app that successfully receives photos as input and creates another output file i want to display the output file once created. in the code bellow I'm passing 2 lists, the photo files (input) and the output reports. currently the output_list is passed empty, i need it to get output report as the app creates the output files Views: from .models import Photo, Output_reports class DragAndDropUploadView(View): def get(self, request): photos_list = Photo.objects.all() output_list = Output_reports.objects.all() return render(self.request, 'photos/drag_and_drop_upload/index.html', {'photos': photos_list, 'outputs': output_list}) def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) -
why doesn't 'follow' button on Django work?
I have built user folloing functionality with Ajax, so a user can follow/unfollow another user. The problem is that when I click "follow" button nothing happens and the number of subscribers doesn't change. urls.py urlpatterns=[path('users/',user_list,name='user_list'), path('users/follow/',user_follow, name='user_follow'), path('users/<str:username>/',user_detail,name='user_detail'), path('',PostList.as_view(), name='index'), path('<str:username>/new/',News.as_view(), name='new'), path('<str:username>/', user_posts, name='profile'), path('<str:username>/<int:post_id>/', post_view, name='tak'), path('<str:username>/<int:post_id>/add_comment/', comment_add, name='add_comment'), path('<str:username>/<int:post_id>/edit/', Update.as_view(), name='edit'), views.py @login_required def user_list(request): users = User.objects.filter(is_active=True) return render(request,'user_list.html',{'section': 'people','users': users}) @login_required def user_detail(request, username): user = get_object_or_404(User,username=username,is_active=True) return render(request,'user_detail.html',{'section': 'people', 'user': user}) @ajax_required @require_POST @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user,user_to=user) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status':'ok'}) except User.DoesNotExist: return JsonResponse({'status':'error'}) return JsonResponse({'status':'error'}) user__detail.html {% extends "base.html" %} {% load thumbnail %} {% block title %}{{ user.get_full_name }}{% endblock %} {% block content %} <h1>{{ user.get_full_name }}</h1> </div> {% with total_followers=user.followers.count %} <span class="count"> <span class="total">{{ total_followers }}</span> follower{{ total_followers|pluralize }} </span> <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow"class="follow button"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> {% endwith %} {% endblock %} {% block domready %} $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), … -
save() prohibited to prevent data loss due to unsaved related object 'user'
i am trying to save data in a table when a user click the checkout button of add to cart but it is showing me the above mention error i am unable to understand and one more thing is happening when i logout my the cart which i saved also got erased is it shomehow related to that i don't know here is my views.py for checkout button class Checkout(View): def post (self, request,): user = request.session.get('user') ids = (list(request.session.get('cart').keys())) sections = Section.get_sections_by_id(ids) for section in sections: order = Order(user = User(id=user), section = section, price = section.price, ) order.save() my views.py for cart.html class Cart(View): def get (self, request): ids = (list(request.session.get('cart').keys())) sections = Section.get_sections_by_id(ids) print(sections) return render(request, 'cart.html', {'sections': sections}) my urls.py urlpatterns = [ path('cart/', Cart.as_view(),name='cart'), path('Check-Out/', Checkout.as_view(),name='checkout'), ] my cart.html {% extends 'base.html' %} {% load static %} {% load cart %} {% load custom %} {% block head %} <link rel="stylesheet" href="{% static 'css/cart.css' %}"> {% endblock %} {% block content %} <div class="container jumbotron"> <section> <h1>My cart</h1> <table class="table"> <thead> <tr> <th scope="col">S.no</th> <th scope="col">Subject</th> <th scope="col">Section</th> <th scope="col">Teacher</th> <th scope="col">Duration</th> <th scope="col">Price</th> </tr> </thead> {% for section in sections%} <tbody style="margin-bottom: 20px;"> <tr> … -
Django Storages for saving media to S3 - it is duplicating uploaded images locally
I am using django-storages to upload media files to S3. This works all fine, the issue is that its also making a copy in local folders, which is causing the server for the app fill up pretty fast. Django v3 Django-storages v1.11.1 custom-storages.py. This was based on web based tutorial. I can see (and assume its because of this) the cached storage, but i cannot see how or where it actually uses it to adjust it. from django.conf import settings from django.core.files.storage import get_storage_class from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION file_overwrite = False class CachedS3Boto3Storage(S3Boto3Storage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super(CachedS3Boto3Storage, self).__init__(*args, **kwargs) self.local_storage = get_storage_class( "compressor.storage.CompressorFileStorage")() def save(self, name, content): self.local_storage._save(name, content) super(CachedS3Boto3Storage, self).save(name, self.local_storage._open(name)) return name settings.py AWS_S3 = True if AWS_S3: AWS_DEFAULT_ACL = 'public-read' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_ACCESS_KEY_ID = ... AWS_SECRET_ACCESS_KEY = ... AWS_STORAGE_BUCKET_NAME = ... AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_HOST = 's3-eu-west-2.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_PRELOAD_METADATA = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'connect.custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' MEDIA_URL = … -
manage.py migrate not working properly it is migrating exisiting table
I am working in djongo and i created a new model and apply the migrations using. python manage.py makemigrations This gave me description related to the new model i have created but when i am doing python manage.py migrate It is giving me the error djongo.sql2mongo.SQLDecodeError: FAILED SQL: CREATE TABLE shareactivity Although that table has been migrated succesfully in my last migration.My latest migration file is 23 and inside it, It has dependenices on file 22 and in file 22 i have that shareactivity table migration -
How I can use Checkbox list widget in admin panel?
I want to use checkbox list in admin panel in django. How can i do that without using from django import forms? -
Why do I get 404 error when trying to GET image from heroku?
So I have deployed my Django project via heroku. I'm testing my api calls, but getting error when fetching images. On request, I was able to get this data : { "id": 1, "source": 2, "category": [ 1, 4 ], "key_line": "blabla", "footnote": "", "created_at": "2021-07-19", "image": "https://bookcake.herokuapp.com/api/cake/media/None/rlvdmseoghk.jpg", } Now the problem is the image field. All other data show up fine in the front-end, but the image doesn't. As well, nothing shows up when I click on that link. What could be the problem? Here's my settings.py file for your information, but I don't see any problem with it. ... MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
view images uploaded from admin on html in django
I am learning to write a Django app which will fetch all images from os.path.join(BASE_DIR, 'media_root', 'uploads') and show it on html page. But its not working like so. admin.py from .models import Experience # Register your models here. admin.site.register(Experience) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') MEDIA_URL = '/media/' models.py class Experience(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='uploads/', default='newbalance.jpg', height_field=None, width_field=None) studio_name = models.CharField(max_length=255) designation = models.CharField(max_length=255) duration = models.CharField(max_length=255) description_short = models.TextField() description_long = models.TextField() keywords = models.CharField(max_length=255) date = models.DateTimeField('DateAdded', auto_now=True, auto_now_add=False) class Meta: db_table = "experience" def __str__(self): return self.studio_name + ' ' + self.duration views.py class ExperienceList(generic.ListView): model = Experience template_name = 'resumesection.html' queryset = Experience.objects.all() urls.py urlpatterns = [ path('modelview/', views.ExperienceList.as_view(), name='experience_list'), ] In error log, 2021-07-19 04:15:40,528: Not Found: /resume_site/modelview/uploads/atomic_arts.png 2021-07-19 04:15:41,239: Not Found: /resume_site/modelview/uploads/futureworks.jpg I presume django should read image from 'MEDIA_ROOT/uploads' folder but it reads from '/resume_site/modelview/uploads/'. Which is not there. I come close to the answer in this post Django admin view uploaded photo, But cannot connect the dots between 'MEDIA_ROOT/uploads' and '/resume_site/modelview/uploads/' How does viewing image, uploaded from admin, work in django. ? -
python-docx and Django - identical method doesn't work in django
I started a Django project weeks ago. It fits into the keyword "customer relation management (CRM)". One of the tools is using a docx-template replacing keywords in a docx-template with python-docx and save it as a new document. All of it works like a charm in jupyter notebook. After developing my code, I transferred it into my Django project which I am developing with pycharm. Everything worked smoothly, but ... The created docx-file cannot be opened. "Pages could not read the file." And furthermore, in the destination directory, there is a mysterious file "~$[part-of-the-filename].docx", which also can not be opened. Can anyone help me with this? Could not find anything about it on the web. And I think it is not about writing permissions, since the file is created. Thanks in advance! Here is my code: def main(gutachtenid): # get data from db con = psycopg2.connect(database="postgres", user="user", password="password", host="127.0.0.1", port="5432") cur = con.cursor() cur.execute('SELECT COLUMNS from table;') last_case = cur.fetchall()[gutachtenid-1] template_file_path = '/template/MTXXXXX-file.docx' output_file_path1 = f'/template/MT{gutachtenid}//MT{gutachtenid}-file.docx' if os.path.exists(output_file_path1): variables = { "${keyword1}": last_case[3], "${keyword2}": last_case[1], "${keyword3}": last_case[2], } template_document = Document(template_file_path) for variable_key, variable_value in variables.items(): for paragraph in template_document.paragraphs: replace_text_in_paragraph(paragraph, variable_key, variable_value) for table in template_document.tables: for col in … -
How to get stock data and add it to a django model?
Hay, I am building a finance website where there is a stock model. I want the price to update automatically in a intfield when the website is running. -
Django-Rest-Framework: How to build Async Directory/Folder upload and Bulk File upload
So My team mates and I have been having a hard time with the efficiency of the synchronous file upload CRUD endpoints we've built and now we need to implement a bulk file upload(Directory upload) with either celery or asyncio(any other methods are kindly welcome). what I have working currently My Model: class CompanyFileUpload(SoftDeletionModel): name = models.CharField( max_length=100, null=True, unique=False, blank=True, default="file name" ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='company_file_uploads' ) timestamp = models.DateTimeField( auto_now_add=True ) data_file = models.FileField( upload_to=Utils.create_company_file_upload_path, blank=True, null=True, validators=[validate_file] ) comment = models.CharField( max_length=400, null=True, unique=False ) file_size = models.CharField( max_length=100, null=True, unique=False, blank=True, default="null" ) def save(self, *args, **kwargs): size = self.data_file.size power = 2**10 n = 0 power_labels = {0: '', 1: 'Kilo', 2: 'Mega', 3: 'Giga', 4: 'Tera'} while size > power: size /= power n += 1 self.file_size = f"{size:.2f} {power_labels[n]}bytes" self.name = self.data_file.name super(CompanyFileUpload, self).save(*args, **kwargs) def __str__(self): return f'{self.data_file}, {self.user}' @receiver(post_save, sender=CompanyFileUpload) def email_report_details_handler(sender, instance, **kwargs): ctx = { "firstname": instance.user.firstname, "timestamp": instance.timestamp, "fullname_and_email": f"{instance.user.firstname} {instance.user.othernames}", "subject": "File Upload", "recepient": instance.user.email, "email": instance.user.email, "url": instance.data_file.url, "comment": instance.comment } Utils.send_report_email(ctx) My serializer: class CompanyFileUploadSerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField( format="%d-%m-%Y %H:%M:%S", read_only=True) class Meta: model = CompanyFileUpload fields = ["id", "name", "user", "data_file", … -
Problem with redirecting in django html file
Hey so I am building a personal website and i am getting an error whenever I click on the the redirect link and i am quite puzzled how to proceed, I am also sending my url.py, views.py and navbar.html (html file where redirect code is) code views.py def product(request): return render(request = request, template_name = "main/categories.html", context ={"categories": ItemCategory.objects.all}) def homepage(request): return render(request = request, template_name = "main/categories.html", context ={"categories": ItemCategory.objects.all}) def about(request): return render(request = request, template_name = "main/about.html", context ={"categories": ItemCategory.objects.all}) def contact(request): return render(request = request, template_name = "main/contact.html", context ={"categories": ItemCategory.objects.all}) url.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = "main" urlpatterns = [ path("", views.homepage, name="homepage"), path("product/", views.product, name="product"), path("about/", views.about, name="about"), path("contact/", views.contact, name="contact"), path("register/", views.register, name = "register"), path("logout/", views.logout_request, name = "logout"), path("login/", views.login_request, name = "login"), path("<single_slug>", views.single_slug, name="single_slug"), ] urlpatterns += staticfiles_urlpatterns() navbar.html <nav> <div id="nav-wrapper"> <div> <ul class="center hide-on-med-and-down"> <li> <a href="{% url 'homepage' %}">Home</a> </li> <li> <a href="about/">About Us</a> </li> <li> <a href="product/">Products</a> </li> <li> <a href="services/">Services</a> </li> <li> <a href="contact/">Contact</a> </li> <li> <a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a> </li> </ul> </div> </div> </nav> … -
How to all Django Template in a new window from Vue.js?
I am using DRF for backend and Vue for frontend, and have encountered the following problem by calling Django templates in Vue. In Vue there is a button "Call Django Template" and it should be opened in a new window. However, it does not work and I cannot get why. When I press the button nothing happens, Django tries to render the template, however no new window is opened. [19/Jul/2021 14:47:11] "GET /home HTTP/1.1" 200 323 my Django template, some dummy url <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login PopUp</title> </head> <body> {% block content %} <script language="javascript" type="text/javascript"> window.open('https://www.google.com/','Test','height=200,width=150'); </script> {% endblock %} </body> </html> my views.py # just a dummy test view def home_view(request): test = 'a' if test == 'a': return render(request, 'connectors/registration/test-a.html') else: return render(request, 'connectors/registration/login-popup.html') my urls.py path('home', views.home_view, name="home"), my Vue function testHome: function() { fetch('http://localhost:8000/home'); } I cannot call the view in a new window from Vue cos it is not the full code. -
How to make two urls to the same app in Django?
It's my main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('account.urls')), ] And it's my urls.py of 'product' app: urlpatterns = [ path('<slug:slug>/', views.getProductPage), path('category/<slug:slug>/', views.getCategoryProducts), ] I would like to have such links: localhost/category/smartphones - shows all smartphones localhost/xiaomi-redmi-note-7 - shows a page of xiaomi redmi note 7 smartphone -
do signals such as post_delete get included in the initiating delete transaction
I have two models related by models.OneToOneField. I am using to post_delete signal to remove the related object. Are both these deletes included in the one transaction by default? If not how would I make sure they are. @receiver(post_delete, sender=Owner) def post_delete_owner(sender, instance, *args, **kwargs): if instance.address: instance.address.delete() -
Unable to redirect to __init__.py while uploading flask app on ubuntu server
I am very new to web development and I am following these two methods (both are same) to deploy flask app to ubuntu vps. https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps https://www.youtube.com/watch?v=YFBRVJPhDGY my folder structure is like this: |--------cwh |----------------cwh |-----------------------static |-----------------------templates |-----------------------venv |-----------------------__init__.py |----------------cwh.wsgi Below is my code of __init__.py: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello, I love my first website!" Below is my code of cwh.wsgi file: #!/usr/bin/python3 import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/cwh/") from cwh import app as application application.secret_key = 'Add-secret' Below is the code of cwh.conf file that i uploaded at /etc/apache2/sites-available <VirtualHost *:80> ServerName 143.198.190.148 ServerAlias www.saassusar.com ServerAdmin saassusar@gmail.com WSGIScriptAlias / /var/www/cwh/cwh.wsgi <Directory /var/www/cwh/cwh/> Order allow,deny Allow from all </Directory> Alias /static /var/www/cwh/cwh/static <Directory /var/www/cwh/cwh/static/> Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> The Problem is that after several attempts I am unable to display __init__.py message at my ipaddress. Instead default apache index file is being displayed. Even if there is no static folder, cwh.conf activation doesn't show any error. -
Showing specific model data in html - Django
I am creating a donation application that allows donors to donate stuff. I have a screen, called availablesupplies.html which renders out all of the donations from the database using a for loop. Each donation is displayed in a user-friendly way, and contains a button that allows them to see details about that specific donation. When the button is clicked, the user is redirected to a page, which I want to contain details about the donation that they clicked on My problem is that I can't figure out how to display a specific donation from my models, for example if my user clicked on an apple donation, I want to get the details for this donation and display it on another page My code: Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (this is where I want to render out the model data): {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div …