Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't my Django root url-conf find my app module?
I'm wondering if someone can help me. I am looking to restructure a new django project, to represent the below: -repository/ -config/ -asgi.py -settings.py -urls.py -wsgi.py -__init__.py -project root/ -app_1/ -admin.py -apps.py -models.py -tests.py -urls.py -views.py -__init__.py -app_2/ -... -app_3/ -... -migrations/ -__init__.py -static/ -templates/ -docs/ -manage.py I have tried to implement this so far by appending the below lines to the settings.py file: # This is the <repository root> BASE_DIR = Path(__file__).resolve().parent.parent # This is the <project repository> PROJECT_ROOT = BASE_DIR / 'project' MEDIA_ROOT = PROJECT_ROOT / 'media' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = PROJECT_ROOT / 'static_root' STATIC_URL = PROJECT_ROOT / 'static' ROOT_URLCONF = 'config.urls' Templates = [{ ... 'DIRS': [PROJECT_ROOT / 'templates'], ... }] In the installed apps I have to specify '.app1' vs traditionally just 'app1'. I amended the manage.py,wsgi.py,asgi.py file etc to point to the settings file. However... When I try to include() an app specific urlconf in the config root urlconf using the below: from django.contrib import admin from django.urls import path, include import project.app1 urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls', namespace='app1')) ] it says "ModuleNotFoundError: No module named 'app1'" Please can someone advise if i am missing a step … -
DJANGO: mixins.DestroyModelMixin destroy - method not allowed
I have an API that returns list of all likes. Here is model for likes: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'post'], name='like_once') ] Here is my view: class likeList(mixins.CreateModelMixin, mixins.DestroyModelMixin, generics.ListAPIView): serializer_class = likeserializers def get_queryset(self): return Like.objects.all() def post(self, request, *args, **kwargs): try: return self.create(request, *args, **kwargs) except IntegrityError: content = {'error': 'IntegrityError'} return Response(content, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, *args, **kwargs): try: return self.destroy(request, *args, **kwargs) except IntegrityError: content = {'error': 'IntegrityError'} return Response(content, status=status.HTTP_400_BAD_REQUEST) I call the delete api with json body {"user":userid,"post":postid} however, I receive method Not Allowd (HTTP 405). Also I can see on the API page "Allow: GET, POST, HEAD, OPTIONS" What am I doing wrong? -
Supervisorctl FATAL when checking status
I want to deploy my Django app on DigitalOcean. Everything went smoothly, I am using Nginx, PostGres and Gunicorn. My app works over the internet with gunicorn pur_beurre.wsgi:application. Problem is now I want to set up Supervisor. Here is the .conf file: [program:PurBeurre-gunicorn] command=/home/pepeche/PurBeurre/venv/bin/gunicorn pur_beurre.wsgi:application user = pepeche directory = /home/pepeche/PurBeurre autostart = true autorestart = true environement = ENV="PRODUCTION",SECRET_KEY='....................' stderr_logfile=/home/pepeche/logs/gunicorn-error.log My errors log: [2020-05-16 07:57:55 +0000] [3184] [INFO] Starting gunicorn 20.0.4 [2020-05-16 07:57:55 +0000] [3184] [INFO] Listening at: http://127.0.0.1:8000 (3184) [2020-05-16 07:57:55 +0000] [3184] [INFO] Using worker: sync [2020-05-16 07:57:55 +0000] [3187] [INFO] Booting worker with pid: 3187 [2020-05-16 07:57:55 +0000] [3187] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/home/pepeche/PurBeurre/venv/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in … -
how to catch data in a custom format [django]
I've wrote a model with a manytomany field in django: class OCP(models.Model): tags = models.ManyToManyField(Tag) ... Now I need to get the name of tags a lot of times, so I decided to add a property to OCP model named tags_list which contains the list of the names of tags and it will be initialized as OCP objects are being fetched. how can I do that?! -
I am getting a TypeError after adding TemplateView to my views folder
from django.shortcuts import render from django.views.generic import TemplateView class HomeResponse(TemplateView): template_name = 'home.html' enter code here -
Django Ckeditor and Youtube plugin not working
9 in my blog app and i'm trying to configure Youtube plugin for this i've tried to use many different tutorials on YT and similar solutrions from here and nothing wokred maybe there is another way to paste YT movie into my blog post? settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'width': 'auto', 'toolbar_Custom': [ ['Bold','Italic','Underline','Link'] ], }, 'special': { 'toolbar': 'Special', 'width': 'auto', 'toolbar_Special': [ ['Image','CodeSnippet', 'Youtube'] ], 'extraPlugins': ','.join(['codesnippet','youtube']) } } STATIC_URL = '/static/' STATIC_ROOT = '/static/' models.py class Post(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(null=True) contentmedia = RichTextUploadingField(null=True, config_name='special', blank=True, external_plugin_resources= [('youtube', '/static/ckeditor/ckeditor/plugins/youtube/youtube/', 'plugin.js')], ) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) config.js CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.width = "auto"; config.display = "block"; config.extraPlugins = 'youtube'; }; -
How to save forms in django with foreign key
I'm making a to-do list app and I'm trying to make the create page for an Item. Most of it works except that I don't get it to save in what Todo List to go and therefor get this error. 'Cannot assign "'Home'": "Item.todolist" must be a "TodoList" instance.' This is my view: def create_todo(request): context = {"lists": TodoList.objects.filter(user=request.user)} if request.method == "POST": if request.POST.get("create"): title = request.POST.get("item_title") date_due = request.POST.get("item_date") text = request.POST.get("item_note") todolist = request.POST.get("todolist") t = Item( user=request.user, todolist=todolist, title=title, date_due=date_due, text=text, complete=False, ) t.save() redirect("all-todos-view") return render(request, "create_todo.html", context) Here is my models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class TodoList(models.Model): name = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse("all-todos-view") class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) todolist = models.ForeignKey(TodoList, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_due = models.DateTimeField( auto_now=False, auto_now_add=False, blank=True, null=True ) text = models.TextField(blank=True, null=True) complete = models.BooleanField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("all-todos-view") -
My context context dictionary not working
This is my view.py part with inbuilt Django views class SchoolListView(ListView): context_object_name = "schools" model = models.School #template_name = "advapp/school_list.htm" my context object name is not working but if I remove '#' then template_name works and give final result as required Below is my urls.py file with "schoollist" as my tag url(r'^school_list$',views.SchoolListView.as_view(),name = 'schoollist') Below is my html bootstrap for 'School' button with 'schoollist'. When button "School" is clicked it should take me to the above url then to view, where context dictionary is called and for loop is executed. <a class="nav-item nav-link active" href="{% url 'advapp:schoollist' %}">School<span class="sr-only">(current)</span></a> This is my school_list html {% for school in schools %} <h2><li><a href="{{school.id}}">`{{school.name}}`</a></li></h2> {% endfor %} Below is my 'models.py' name = models.CharField(max_length = 200) Principal = models.CharField(max_length = 200) Location = models.CharField(max_length = 200) def __str__(self): return self.name``` *If I remove '#' from template_name, I get ALL my required result and just to know using template_name is enough instead for tag.* Thank You -
Reading environment variables from .env file in pythonanywhere.com
I am trying to set environment variables using a .env file in pythonanywhere.com but I keep getting an error saying my SECRET_KEY is empty so my environment variables aren't being set. I'm following the article from pythonanywhere.com link: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ import os from dotenv import load_dotenv project_folder = os.path.expanduser('~/my-project-dir') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) I don't quite understand the 3rd line. In the terminal, I cd into the project folder and run the pwd command to get the path. I'm not sure what part I am supposed to include for the argument for os.path.expanduser('~/my-project-dir'). Any insight is greatly appreciated. Thanks for any help in advance. -
Reattempting of failed bulk inserts in pymongo
I am trying to do a bulk insert of documents into a MongoDB collection in Python, using pymongo. This is what the code looks like: collection_name.insert_many([ logs[i] for i in range (len(logs)) ]) where logs is a list of dictionaries of variable length. This works fine when there are no issues with any of the logs. However, if any one of the logs has some kind of issue and pymongo refuses to save it (say, the issue is something like the document fails to match the validation schema set for that collection), the entire bulk insert is rolled back and no documents are inserted in the database. Is there any way I can retry the bulk insert by ignoring only the defective log? -
When Adding (django_storages) AWS_ENDPOINT_URL in settings it creates a folder name with bucket_name in AWS-S3 while performing collectstatic
Here is my django_storages settings. # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Static Files collectstatic files STATICFILES_STORAGE = 'storage.CollectStaticStorage' # Custom AWS_ACCESS_KEY_ID = 'key' AWS_SECRET_ACCESS_KEY = 'key' AWS_STORAGE_BUCKET_NAME = 'my_bucket' AWS_S3_REGION_NAME = 'ap-southeast-1' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATIC_URL = f'{AWS_S3_ENDPOINT_URL}/{AWS_LOCATION}/' PUBLIC_MEDIA_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'storage.PublicMediaStorage' # Media files upload by user MEDIA_URL = f'https://{AWS_S3_ENDPOINT_URL}/{PUBLIC_MEDIA_LOCATION}/' AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}' This line is creating a folder inside my bucket with bucket name So When I run $ python manage.py collectstatic, it is creating "my_bucket" folder inside my bucket "my_bucket" automatically when I add AWS_S3_ENDPOINT_URL Thank you -
Crawler is not Running inside django views stopping after Spyder Opened
I am trying to run scrapy spider inside django views. It is not working. When I triggered the url, It get response Http 200 Ok. But Crawler is not fetching anything from the urls. If this is not the best practise please provide the details for running scrapy inside Django. this is my logs output: app_1 | 2020-05-16 06:17:52 [scrapy.extensions.telnet] INFO: Telnet console listening on app_1 | 2020-05-16 06:18:30 [scrapy.middleware] INFO: Enabled downloader middlewares: app_1 | ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', app_1 | 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', app_1 | 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', app_1 | 'scrapy_user_agents.middlewares.RandomUserAgentMiddleware', app_1 | 'scrapy.downloadermiddlewares.retry.RetryMiddleware', app_1 | 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', app_1 | 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', app_1 | 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', app_1 | 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', app_1 | 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', app_1 | 'scrapy.downloadermiddlewares.stats.DownloaderStats'] app_1 | 2020-05-16 06:18:30 [scrapy.middleware] INFO: Enabled spider middlewares: app_1 | ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', app_1 | 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', app_1 | 'scrapy.spidermiddlewares.referer.RefererMiddleware', app_1 | 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', app_1 | 'scrapy.spidermiddlewares.depth.DepthMiddleware'] app_1 | 2020-05-16 06:18:30 [scrapy.middleware] INFO: Enabled item pipelines: app_1 | ['covid19crawler.pipelines.Covid19CrawlerPipeline', app_1 | 'covid19crawler.pipelines.CSVPipeline'] app_1 | 2020-05-16 06:18:30 [scrapy.core.engine] INFO: Spider opened app_1 | 2020-05-16 06:18:30 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) app_1 | 2020-05-16 06:18:30 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6024 My Spider Code: class Covid19(scrapy.Spider): name = 'covid19' start_urls = [ 'https://www.worldometers.info/coronavirus/' ] custom_settings = { 'ITEM_PIPELINES': … -
Django 3 not saving image from request
I have an code snippet from django 2.2, to save image to django DB directly from url. I use this method mentioned below, just like before. def update_image(self, url): response = requests.get( url=url, stream=True ) img_temp = NamedTemporaryFile(delete=True) img_temp.write(response.content) img_temp.flush() img_filename = str(self.id).zfill(10) + ".png" self.static_map_file.file.save( "static_maps/" + img_filename, File(img_temp), save=True ) self.save() But now it raises exception now: File "~/project/core/models.py", line 627, in update_image save=True File "~/project/venv/lib/python3.6/site-packages/django/db/models/fields/files.py", line 87, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) File "~/project/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 52, in save return self._save(name, content) File "~/project/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 271, in _save for chunk in content.chunks(): File "~/project/venv/lib/python3.6/site-packages/django/core/files/base.py", line 60, in chunks data = self.read(chunk_size) File "~/project/venv/lib/python3.6/site-packages/django/core/files/utils.py", line 16, in <lambda> read = property(lambda self: self.file.read) AttributeError: 'File' object has no attribute 'read' I also changed my method with this answer, but nothing fixed. "Django save image from url and connect with ImageField " -
Stripe Subscription issue in django?
Having issues getting the Stripe subscription working in my Django application. right now I have this as my view: def subscribe(request): customer = stripe.Customer.create( description = 'This is the test customer', ) if request.method=='POST': stripe.Subscription.create( customer= customer.id, items = [{"Basic Plan": "prod_HHU1r1fphhhqLt"}] ) return render(request, 'landing/charge.html') Im getting the error: Request req_69L7P1bcp8iZ1e: Received unknown parameter: items[0][Basic Plan] which is confusing because the info is coming straight from my stripe plan so I know it exists (edit) here is the traceback if it helps: Traceback (most recent call last): File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/tobiasmuldoon/Dev/python/Environments/swapp/landing/views.py", line 79, in subscribe stripe.Subscription.create( File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/stripe/api_resources/abstract/createable_api_resource.py", line 22, in create response, api_key = requestor.request("post", url, params, headers) File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/stripe/api_requestor.py", line 122, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/stripe/api_requestor.py", line 373, in interpret_response self.handle_error_response(rbody, rcode, resp.data, rheaders) File "/Users/tobiasmuldoon/Dev/python/Environments/web1/lib/python3.8/site-packages/stripe/api_requestor.py", line 152, in handle_error_response raise err Exception Type: InvalidRequestError at /subscribe/ Exception Value: Request req_69L7P1bcp8iZ1e: Received unknown parameter: items[0][Basic Plan]``` Im pretty postitive its something simple but Im pretty new to django and cant seem to get it figured … -
Showing values from a foreign key in a template
I would like to show the values from a foreign key in my template but they appear in blank when trying to render it. The values i am trying to show are the ones coming from the Paciente attribute, which is connected to the Patient model in another app through a Foreign Key, i will show my attempt in achieving this but failing, can you please help me or tell me what i am doing wrong:( Views class AppointmentIndexView(ListView): model = Consults template_name = 'appointments_index.html' context_object_name = 'consults' ordering = ['Fecha'] def get_queryset(self): queryset = super().get_queryset() queryset.filter(Fecha=datetime.date.today()) return queryset Models class Consults(models.Model): #General Consult Info Paciente = models.ForeignKey(Patient,on_delete=models.CASCADE) Fecha = models.DateField() Motivo = models.CharField(max_length=500,null=True) Padecimiento = models.CharField(max_length=500,null=True) #Main Patient Info Presion = models.CharField(max_length=20,blank=True,null=True) Temperatura = models.FloatField(blank=True,null=True) Peso = models.FloatField(blank=True,null=True) Talla = models.FloatField(blank=True,null=True) #Any Exams done before Estudios = models.ImageField(upload_to='studies',blank=True) #Interrogatory by System Digestivo = models.CharField(max_length=500,blank=True,null=True) Endocrino = models.CharField(max_length=500,blank=True,null=True) Renal = models.CharField(max_length=500,blank=True,null=True) Linfativo = models.CharField(max_length=500,blank=True,null=True) Respiratorio = models.CharField(max_length=500,blank=True,null=True) #Physical Exploration Cabeza = models.CharField(max_length=500,blank=True,null=True) Torax = models.CharField(max_length=500,blank=True,null=True) #Diagnose CIE_10 = models.ForeignKey(CIE_10,on_delete=models.DO_NOTHING,blank=True,null=True) Detalle_de_Codigo = models.CharField(max_length=500,blank=True,null=True) Diagnostico = models.CharField(max_length=500,blank=True,null=True) Procedimiento = models.CharField(max_length=500,blank=True,null=True) Analisis = models.CharField(max_length=500,blank=True,null=True) #Treatment Medicamento = models.CharField(max_length=500,blank=True,null=True) Descripcion = models.CharField(max_length=500,blank=True,null=True) Uso = models.CharField(max_length=500,blank=True,null=True) Dosis = models.CharField(max_length=500,blank=True,null=True) Acciones = models.CharField(max_length=500,blank=True,null=True) Template {%extends 'base.html'%} … -
Field 'id' expected a number but got (<OrderItem: 1 of Dummy 1>, True)
TypeError: Field 'id' expected a number but got (OrderItem: 1 of Dummy 1>, True). I have to create a simple e-commerce site in Django and I am new to this so help to solve the problem guys. views.py def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create(item=item) order_qs = Order.objects.filter(user=request.user,ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("core:product", slug=slug) models.py This is my model view I struck with is error help me to find out what was that. from django.db import models from django.conf import settings from django.shortcuts import reverse # Create your models here. CATEGORY_CHOICES = ( ('S','Shirt'), ('SW','Sport Wear'), ('OW','Outwear') ) LABLE_CHOICES = ( ('P','primary'), ('S','secondary'), ('D','danger') ) class Item(models.Model): title = models.CharField(max_length= 100) price = models.FloatField() discount_price = models.FloatField(blank=True , null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABLE_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ "slug": self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ "slug": self.slug }) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete= models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) items = models.ManyToManyField(OrderItem) start_date … -
How to use OAuth access token safely in Django?
I just learned how to get Twitter access tokens using OAuth, but I have a question of how to use it safely in Django. When I send a POST request to https://api.twitter.com/oauth/access_token with appropriate parameters(oauth_consumer_key, oauth_token, oauth_verifier), I can get the response containing user's access token and access token secret. At this point, I had a question: How to save and use these tokens safely? I thought of saving the tokens in user models, but it doesn't seem to be a good idea because saving tokens without encryption seems so dangerous... -
Django foreign key value from template
I've looked through other answers to similar questions but I can't seem to get it to work. here is my model structure: models.py class Seller(models.Model): seller_full_name = models.CharField(max_length=50) seller_listing_name = models.CharField(max_length=50) <-- I want to display this in template email = models.EmailField(max_length=50) date_added = models.DateField(auto_now_add=True) def __str__(self): return self.seller_listing_name # Create your models here. class Product(models.Model): ... seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True) ... def __str__(self): return self.product_name In my view I get a query set of products views.py def store(request): products = Product.objects.values().order_by('?') # shuffle order args = {'products': products} return render(request, 'store/products-page.html', args) In the template I iterate through products and build cards that display item details. I want to also display the listing name of the seller for each product on each card. I cannot seem to get the foreign key statement correct in the view because it renders empty where the sellers name should be. products-page.html {% for product in products %} <div class="col-lg-3 col-md-6 mb-4"> ... <p> // {{ product.seller.seller_listing_name }} // <-- display sellers name here </p> <h4 class="card-title"> <a href="#">{{ product.product_name }}</a> </h4> <p>#{{ product.product_id }}</p> <p>{{ product.description }}</p> <h5>${{ product.price | floatformat:2 }}</h5> ... </div> {% endfor %} I've been messing with … -
Saving changes of very simple model in admin view fires several errors on GoogleComputeEngine, WHY?
I have an OpenLiteSpeed Django app in Google Cloud Compute Engine which connects a SQLite DB. I've created some models and views, in those views I can show lists and graphics of SQLite data. I am also able to list and search the data in admin views. However in admin view when I try to make some changes and save or delete mostly get 500 Internal Error, it works rarely. Model that I try to make changes: from django.db import models class Test(models.Model): aciklama = models.TextField(blank=True) I cannot debug on server, to see errors I check stderr.log file in project directory. Following errors occur when I get 500 Internal Error on admin view page: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdd in position 7: invalid continuation byte The above exception was the direct cause of the following exception: SystemError: <class 'lsapi_wsgi.Request'> returned a result with an error set Not Found: /favicon.ico 2020-05-16 06:31:45.902022 [ERROR] [1643] wsgiAppHandler failed to create req_obj. If there is a way to debug on compute engine please share with me. Btw on my local environment it works perfectly. -
Testing a model with a one-to-one relationship
Im testing my app and am really stuck on how to test my personalInformation form which has a one-to-one relationship with my user. I have tried a lot of things but here is the testing code boiled down to the stuff im pretty sure is correct and a few related classes. models.py class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) def __str__(self): return f'{self.user.username}' forms.py class PersonalInformationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PersonalInformationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'gender', 'dob'] widgets = { 'dob': DatePickerInput( options={ "format": "MM/DD/YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } unit test def test_user_information_updated_on_success(self): user = User.objects.create_superuser('username') self.client.force_login(user) form = PersonalInformationForm(data={ 'first_name': 'testuser', 'surname': 'testsurname', 'gender': 'M', 'dob': '1984-09-17 00:00:00'}) form.save() # form.save throws error error msg 1048, "Column 'user_id' cannot be null" As a bonus, how would I access the attributes in personalInformation please? This isnt correct as 'first_name' is an attribute of personalInformation, which has a one-to-one relationship with the user self.assertEqual(user.first_name, … -
How to create private pages on django using decorators?
I am creating a journal app on Django and I am having trouble creating individual private pages for users' journal entries using a decorator. When I tried to use login_required, I could input a different username and view other users' entries. With the current code, I get a 404 error. Here is my decorator code: def private_journal(function): def wrapper(request, *args, **kwargs): if Journal.user== request.user: return function(request, *args, **kwargs) else: raise Http404 return wrapper Models: User = get_user_model() class Journal(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) prompt = models.TextField() entry = models.TextField() entry_html = models.TextField(editable=False) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.prompt, self.entry def save(self,*args,**kwargs): self.entry_html = misaka.html(self.entry) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('sandbox:for_user',kwargs={'username':self.user.username}) class Meta: ordering = ['-created_at'] unique_together = ['user','entry',] Views: class UserEntries(LoginRequiredMixin,generic.ListView): model = models.Journal template_name = 'sand/user_post_list.html' def get_queryset(self): try: self.entry_user = User.objects.prefetch_related('entries').get(username__iexact=self.kwargs.get('username')) except User.DoesNotExist: raise Http404 else: return 'sandbox/index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['entry_user'] = self.entry_user return context @method_decorator(private_journal) def dispatch(self, request, *args, **kwargs): return super(CreateEntry, self).dispatch(self, request, *args, **kwargs) class EntryDetail(LoginRequiredMixin,SelectRelatedMixin,generic.DetailView): model = models.Journal select_related = ('user',) def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')) @method_decorator(private_journal) def dispatch(self, request, *args, **kwargs): return super(CreateEntry, self).dispatch(self, request, *args, **kwargs) class CreateEntry(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('entry',) model = models.Journal def form_valid(self,form): self.object = … -
Override deletion in django
I have model, I want once in administration admin deleting the model to delete the file associated with it locally. I tried below, but says post_delete not defined. file_location = models.FileField(upload_to='dsfdgf',bla....) @receiver(post_delete, sender=Model) def model_delete(sender, instance, **kwargs): # Do your on delete action here I want to delete file_location on my device , once model deleted in admin. Django 2.2.7. . -
Add to auth_user
I have this program that gets most of its data from the auth_user table one the django database. I don’t know how to add a new column to it and make it actually work since it doesn’t recognize it when I do. Does anybody know how you would add a column that can be used in auth_user table in the default django database. -
Add a friend systen on django
I have been trying to add friend system in which the user can add and remove friends (other users), after finishing with the code, I found an error that when the logedin user tries to add a friend from other user's profile, the add friend button redirects to the logedin user profile making it imposible to add a new friend, it can just add himself as a friend. I personally think the error is on the views.py profile view. views.py (profile shows user's profile and change_friend is the one that adds and removes frinds) def profile(request, username=None): friend = Friend.objects.filter(current_user=request.user).first() friends = [] if friend: friends = friend.users.all() if username: post_owner = get_object_or_404(User, username=username) user_posts=Post.objects.filter(user_id=post_owner) else: post_owner = request.user user_posts=Post.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'friends': friends, } return render(request, 'profile.html', args1) def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('profile') models.py class Friend(models.Model): users = models.ManyToManyField(User, default='users', blank=True, related_name='users') current_user = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE, null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) profile.html <div class="media"> <div class="media-body"> <h2 … -
How to display multiple video streams on webpage using django?
I'm trying to display the live stream from my phone (using IP Webcam) on a webpage using django. The code: def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video(request): return StreamingHttpResponse(gen(IPWebCam(camera_ip)),content_type='multipart/x-mixed-replace; boundary=frame') class IPWebCam(object): def __init__(self,camera_ip): self.url = "https://"+ camera_ip + "/shot.jpg" print(self.url) def __del__(self): cv2.destroyAllWindows() def get_frame(self): imgResp = urllib.request.urlopen(self.url,context=context) imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8) img = cv2.imdecode(imgNp, -1) # We are using Motion JPEG, but OpenCV defaults to capture raw images, # so we must encode it into JPEG in order to correctly display the # video stream gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) resize = cv2.resize(img, (270,250), interpolation=cv2.INTER_LINEAR) ret, jpeg = cv2.imencode('.jpg', resize) return jpeg.tobytes() So here video is the view to display the live stream. I'm using "{% url 'video' %}" to render the view on a template and also added the view in urlpatterns. The template where i'm displaying the stream has grid view. Where i would like to display cameras with different ip in each grid. Right now i'm able to display the same IP webcam stream in all the grids since there is only one view i.e video and im rendering the same view in the template. I …