Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django WAMP (Apache) mod_wsgi on Windows
Im new to Django and web development. I have completed a project in development environment and now we need to deploy it in production. I have been trying to go through the deployment process using wamp on a windows virtual machine. The details are as under: OS: Windows 10 Python: 3.7.6 Webserver: Wamp 3.2 with Apache 2.4.41 mod_wsgi ver 4.7.1 (this was downloaded pre-compiled from here Im using pycharm for the development and the default python interpreter path is of system i.e. C:\Users\User\AppData\Local\Programs\Python\Python37 which includes the installed/ extracted mod_wsgi packages in site-packages. The 'Django' package is installed however within venv at C:\Users\User\TryProject\venv\Lib\site-packages I configured my files as folows: httpd-vhosts.conf: <VirtualHost *:8080> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/User/TryProject/TryProject.error.log" CustomLog "C:/Users/User/TryProject/TryProject.access.log" combined #WSGIDaemonProcess TryProject python-home=C:/Users/User/TryProject/venv/Lib/site-packages #python-path=C:/Users/User/TryProject/venv/Lib/site-packages #venv/Lib/site-packages" #WSGIProcessGroup TryProject WSGIScriptAlias /mysite "C:/Users/User/TryProject/TryProject/wsgi.py" #process-group=TryProject #application-group=%{GLOBAL} WSGIApplicationGroup %{GLOBAL} <Directory "C:/Users/User/TryProject/TryProject"> <Files wsgi.py> Require all granted </Files> </Directory> httpd.conf: ... LoadFile "c:/users/user/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/user/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/user/appdata/local/programs/python/python37" ... and wsgi.py import sys from django.core.wsgi import get_wsgi_application #site.addsitedir("C:/Users/User/AppData/Local/Programs/Python/Python37/Lib/site-packages") site.addsitedir("C:/Users/User/TryProject/venv/Lib/site-packages") # Add the app's directory to the PYTHONPATH #sys.path.append('C:/Users/User/TryProject') sys.path.append('C:/Users/User/TryProject/TryProject') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TryProject.settings') application = get_wsgi_application() while the apache error log file shows this group of error on every request: [Tue Apr 07 20:18:44.672498 2020] [wsgi:error] [pid 12456:tid … -
How to post in bulk in Django-Rest-Framework with a different format
My Model : from django.db import models Create your models here. from rest_framework.exceptions import ValidationError class Results(models.Model): test_taker = models.ForeignKey('users.User', null=True, related_name='testtakerId', on_delete=models.CASCADE) question_detail = models.ForeignKey('questions_detail.Questions_detail', null=True, related_name='answersId', on_delete=models.CASCADE) test_id = models.IntegerField(null=True) answer = models.CharField(max_length=255, null=True) custom_answer = models.CharField(max_length=255, null=True) What i Want to post: { "test_taker": 1, "test_id": 1, "question": [ { "question_id": 1, "answer": 2, "custom_answer": "c1" }, { "question_id": 2, "answer": 3, "custom_answer": "c2" }, { "question_id": 3, "answer": 4, "custom_answer": "c3" }, { "question_id": 2, "answer": 1, "custom_answer": "c4" } ] } Cuurently what i am doing is: In my views.py : (I am using rest_framework_bulk) class AddResult(ListBulkCreateUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = ResultsSerializer def get_queryset(self): return Results.objects.all() def perform_create(self, serializer): test_taker = self.request.data['test_taker'] test_id = self.request.data['test_id'] serializer.save(test_taker=test_taker, test_id=test_id) My Serializer: class ResultsSerializer(BulkSerializerMixin,serializers.ModelSerializer): class Meta: model = Results fields = '__all__' list_serializer_class = BulkListSerializer What is happening is it just stores 1 result and that has test_taker = 1 and test_id = 1 which it takes from the outer part of the JSON. What i want is for it to store all the records in the format of [test_taker , test_id, question_id , answer, custom_answer] Thanks in advance for positive responses. -
python-social-auth redirect to the user profile in Django
I am using the wonderful python-social-authpackage, and more precisely the social-auth-app-django version since my project is using the Django Framework. Once the user is registered/logged in via any social backend, I'd like to redirect the user to their own very user profile. I know I can set a static URL in my settings.pysuch as: SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/logged-in/' But how can I dynamically redirect the user to their profile given that I know their username/slug? If I could set variables in the settings.py it'd be something like: SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/accounts/<slug:slug>/' But of course I can't do that. Is there any way I can achieve what I want? -
NameError: name 'LoginView' is not defined
I'm installing the Openstack Stein Horizon service (dashboard) following the tutorial on the site. I encounter an error due to the Django version and fix it using this explanation Switch from django string_concat to format_lazy. The next issue that appears was AttributeError: module 'django.contrib.auth.views' has no attribute 'login', which I googled and came again as a Django version incompatibility. I followed this explanation here: AttributeError: module Django.contrib.auth.views has no attribute openstack_auth/urls.py from django.conf.urls import url from django.views import generic from openstack_auth import utils from openstack_auth import views from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r"^login/$", LoginView.as_view(), name='login'), url(r"^logout/$", LogoutView.as_view(), name='logout'), url(r'^switch/(?P<tenant_id>[^/]+)/$', views.switch, name='switch_tenants'), url(r'^switch_services_region/(?P<region_name>[^/]+)/$', views.switch_region, name='switch_services_region'), url(r'^switch_keystone_provider/(?P<keystone_provider>[^/]+)/$', views.switch_keystone_provider, name='switch_keystone_provider') ] if utils.is_websso_enabled(): urlpatterns += [ url(r"^websso/$", views.websso, name='websso'), url(r"^error/$", generic.TemplateView.as_view(template_name="403.html")) ] apache2/error.log Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/usr/local/lib/python3.6/dist-packages/django/urls/resolvers.py", line 584, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 80, in … -
Localhost webpage created in django is showing wrong page source code
I am following corey schafer django course using sublime text 3. After i used bootstrap template, my home page was updated. But page named 'about' is not updated. When i use view page source, it is showing wrong source code. My html code for about page is- {% extends "blog/base.html" %} {% block content %} <h1>About Page</h1> {% endblock content %} but when i press view source code it is showing the old one- <!DOCTYPE html> <html> <head> <title>Django Blog-About</title> </head> </head> <body> <h1>About page</h1> </body> </html> My home webpage using the same template got updated, but not this one. My base html file is- <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% if title %} <title>Django Blog-{{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <div class="container"> {% block content %} {% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> -
Celery worker permission denied
To be quite honest I do not really know what I am doing ;) Recently I installed Mayan EDMS in a chroot on my NAS. So far I got it working ... at least I can login and so forth. But I cannot upload any files and I guess this has to do with celery (which I did not knew about before). Because I am in a chroot I cannot use supervisord for these celery workers and I started them from the command line. e.g. nice -n 19 /path/to/my/mayan-edms/bin/celery worker -A mayan -Ofair -l ERROR -Q statistics,tools,common_periodic,parsing,document_states,mailing,ocr -n mayan-worker-slow.@%h --concurrency=1 But this throws an error: -------------- mayan-worker-slow.@DiskStation213 v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Linux-3.2.40-armv7l-with-glibc2.17 2020-04-07 15:15:07 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mayan:0x41cc8d00 - ** ---------- .> transport: redis://:**@127.0.0.1:6379/0 - ** ---------- .> results: redis://:**@127.0.0.1:6379/1 - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> common_periodic exchange=common_periodic(direct) key=common_periodic .> document_states exchange=document_states(direct) key=document_states .> mailing exchange=mailing(direct) key=mailing .> ocr exchange=ocr(direct) key=ocr .> parsing exchange=parsing(direct) key=parsing .> statistics exchange=statistics(direct) key=statistics … -
how to use password field in serializers.py ..password2=serializers.Charfield(serializers.widget=PasswordInput()) doesnot work as it use
AttributeError: module 'rest_framework.serializers' has no attribute 'PasswordInput' serializer.py : from rest_framework import serializers from django.contrib.auth.models import User class SampleSerializer(serializers.ModelSerializer): password2 = serializers.CharField(widget=serializers.PasswordInput()) class Meta: model = User fields = ['username','email','password'] -
Is there any way to use tika library on pythonanywhere?
I'm working on a parsing problem and have used tika library in local system to read pdf documents. As now I'm deploying my parser on the web, I'm not allowed to use tika library on pythonanywhere server. File "/home/mubasharnazar/mysite/server.py", line 114, in read_pdf file_data = parser.from_file(file) File "/home/mubasharnazar/.virtualenvs/flaskk/lib/python3.7/site-packages/tika/parser.py", line 40, in from_file output = parse1(service, filename, serverEndpoint, headers=headers, config_path=config_path, requestOptions=requestOptions) File "/home/mubasharnazar/.virtualenvs/flaskk/lib/python3.7/site-packages/tika/tika.py", line 338, in parse1 rawResponse=rawResponse, requestOptions=requestOptions) Any solution? -
Django command running a shell script
I have an app that deletes files that have been uploaded more than one month ago. from django.core.management.base import BaseCommand, CommandError from blacklist_app.models import EntradaHistorial from datetime import datetime, timedelta import pytz, subprocess, os from blacklist.settings import BASE_DIR class Command(BaseCommand): help = "Procesa archivos en cola para ser movidos al servidor de destino acorde a la configuración" tmp = os.path.join(BASE_DIR, 'blacklist_app/tmp') excel = os.path.join(BASE_DIR, 'blacklist_app/uploaded_files/excel') json = os.path.join(BASE_DIR, 'blacklist_app/uploaded_files/json') mv = 'mv {}/{} {}' rm = 'rm {}/{}' def handle(self, *args, **options): max_date = datetime.now() + timedelta(weeks=-1) preg = "*_{}*".format(max_date.strftime('%Y%m')) #Se mueven los archivos que deben ser conservados a la carpeta temporal self.mv_and_rm(self.excel, preg) self.mv_and_rm(self.json, preg) max_date.replace(day=1, hour=0, minute=0, tzinfo=pytz.UTC) #Actualiza los valores de los archivos borrados EntradaHistorial.objects.filter(fecha__lt=max_date, archivo_borrado=False).update(archivo_borrado=True) # Mueve los archivos a la carpeta temporal, borra los archivos que deben ser borrados y # mueve de vuelta los archivos que deben ser conservados def mv_and_rm(self, dir, preg): move = self.mv.format(dir, preg, self.tmp) self.run_command(move) rm = self.rm.format(dir, '*') self.run_command(rm) move_back = self.mv.format(self.tmp, preg, dir) self.run_command(move_back) def run_command(self, command): sh = os.path.join(BASE_DIR,'blacklist_app/management/commands/run_command.sh') call = "sh {} '{}'".format(sh, command) print(subprocess.check_output(call)) In the same directory I have the script run_command.sh #!/bin/sh $1 This command should run in the crontab on the first … -
Django per-view based caching only for non-logged in users
I am working with per-view based caching that Django provides. However I want to disable cache when the user is logged in. What is the best approach to achieve this from urls.py ? https://docs.djangoproject.com/en/3.0/topics/cache/#the-per-view-cache from . import views from django.views.decorators.cache import cache_page urlpatterns = [ path('', cache_page(60 * 15)(views.HomeView)), ] -
how to get unit and price from selectable dropdown list
hi I am new in Django I am creating order app.in new order form i want to get price and unit from product table.when i select a product from dropdown list it will get price and unit from product table selected product.here is my my code model.py class Product(models.Model): product_name = models.CharField(max_length=200) unit = models.TextField() price = models.IntegerField() active = models.IntegerField(default='1') def __str__(self): return self.product_name class Order(models.Model): name = models.CharField(max_length=200) delivery_date = models.DateField(blank=True) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() unit = models.CharField(max_length=50) price = models.IntegerField() amount = models.IntegerField() view.py def new(request): if request.POST: form = OrderForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = OrderForm() return render(request, 'new.html', {'form': form}) form.py class OrderForm(ModelForm): product_id = forms.ModelChoiceField(queryset=Product.objects.filter(active='1'), empty_label='') delivery_date = forms.DateField(required=True) quantity = forms.IntegerField(initial=1) price = forms.IntegerField(initial=0) class Meta: model = Order fields = ['name', 'delivery_date', 'product_id', 'unit', 'quantity', 'price', 'amount'] class ProductForm(ModelForm): class Meta: model = Product fields = ['product_name', 'unit', 'price'] new.html <form class="form" role="form" action="" method="post"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <header>Customer Info</header> <div class="form-group floating-label"> {{ form.name | add_class:'form-control' … -
inputting algorithms to edit django model data
I have a Django project where users can input stings and images similar to a blog like twitter or reddit. The data will be stored in models.py. as such: class Post(models.Model): body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=True, blank=True) then in forms class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['body', 'image'] and in views: def view(request, slug): context = {} post = get_object_or_404(Post, slug=slug) context['post'] = post return render(request, 'post/post.html', context) I used Conda to write an algorithm that edits the input photos in a unique way (for example a watermark) but I'm not sure where in my Django project to try an incorporate the algorithm. Forms.py? Models.py? after the data manipulation I would want to create a second views.py so that I could have something like this: def view2(request, slug): context = {} post2 = get_object_or_404(Post2, slug=slug) context['post2'] = post2 return render(request, 'post2/post2.html', context) I was thinking I should create a form.py class roughly like the following: class EditPostForm(forms.ModelForm): class Meta: model = Post fields = ['body', 'image'] def edit(self, commit=True): post.body = self.cleaned_data['body'] post.image = self.cleaned_data['image'] #manipulate img data #output new img and then create a view.py class roughly like the following: def new_post_view(request, … -
Return ManyRelatedManager values in template
I'm new to programming so i'm sure there's an obvious simple solution to this. I have two models (in separate apps): class Order(models.Model): parts = models.ManyToManyField(Part, blank=True) class Part(models.Model): mwos = models.ManyToManyField('mtn.Order', blank=True) The problem is when i render Order in DetailView in template i can't get the queryset of associated values. If i just put {{ order.parts }} i get my_app.Part.None. And if i do this class OrderDetailView(LoginRequiredMixin, DetailView): model = Order def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['parts'] = Part.objects.filter(mwos=self.object.id) return context I get {{ parts }} rendered as empty queryset <QuerySet []>. -
Is there any way to fetch images with date specified and display according to date in django?
I am trying to create a e-newspaper app with django. I which i upload data in pdf format with date and convert the data to JPEG and save the to folder with the date specified format. I am trying to get the images for date specified only (images with particular date will be displayed on that date only ).But having no better luck with fetching the particular data. models.py class City(models.Model): cityid =models.AutoField(primary_key=True) name = models.CharField( max_length=50) class Meta: verbose_name = ("City") verbose_name_plural = ("Cities") def __str__(self): return self.name class DailyFeed(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) date =models.DateField(auto_now=False, auto_now_add=False) files = models.FileField(max_length=100) views.py def create_dailyfeed(request): folder='date/' image = 'images' if request.method == 'POST' : #Get All Files files = request.FILES.getlist('files') form = DailyFeedForm(request.POST, request.FILES) if form.is_valid(): inst = form.save(commit=False) # Add Date DAte date = inst.date #Add City DATA city = inst.city.name # Date Data date1 = date.strftime("%Y/%m/%d") folder1 = '{}/{}/{}'.format(folder,city,date1) fs = FileSystemStorage(location=folder1) media = '{}/{}/{}'.format(image,city,date1) fs1 = FileSystemStorage(location = media) for f in files: filename = fs.save(f.name, f) file_url = fs.url(filename) filename1 = fs1.save(f.name, f) file_url1 = fs1.url(filename) #media FIle DIrectory #COnvert to JPG pages = convert_from_path('{}/{}'.format(folder1,f.name), 200) for page in pages: page.save('{}/{}.jpg'.format(media,f.name[:-4]), 'JPEG') inst.save() return redirect('/', messages.success(request, 'Paper … -
Customizing Django's implicit ManyToManyField's "through" table?
I have two models which are joined through a ManyToManyField. I did not specify a through table manually, so Django created one implicitly. Can I now somehow customize that through table, specifically to alter its ___str___ function? Basically, I'm trying to override the "row title" a TabularInline admin class uses, like in these questions: Remove or edit object name in admin.TabularInline How to override the str method when rendering StackedInline field? https://groups.google.com/d/topic/django-users/d0QPIAklSug But I'd like to avoid customizing the template or creating a "relationship table" explicitly, as right now it's managed by Django. -
I cant add a django tag {% csrf_token %} to html created using format_html. The tag keeps returning as plain text
i have a table column as follows actioncolumn = tables.Column(verbose_name="action",orderable=False,empty_values=[]) def render_actioncolumn(self): edit_btn=''\ ' edit '\ '' delete_btn=''\ 'delete'\ '' return format_html('{{% csrf_token %}} ' + edit_btn +' '+ delete_btn + ' ') the tag {% csrf_token %} reurns as plain text. the extra curlies in {{% csrf_token %}} are to work around the special charcters used in strings -
Which filter is better and faster
I am relatively new to django and python, so i would really like to know which of these two implementation is the better or faster approach. I am currently using the filter, but i thought of it, and cos i really like list comprehension, i wrote the same code using list comprehension. Both codes do exactly the same thing, but I just want to know from developers with more experience which is better and why. Below are both codes. posts = Post.objects.filter(approved=True).order_by('-date_posted') posts = [post for post in Post.objects.all().order_by('-date_posted') if post.approved] -
How to add or remove quantity cart django and also in templates?
Views.py def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Expired product") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) request.session['cart_items'] = cart_obj.products.count() return redirect("cart:home") models.py class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True)enter code here products = models.ManyToManyField(CartItem, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=65, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=65, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through) def pre_save_cart_receiver(sender, instance, *args, **kwargs): if instance.subtotal > 0: instance.total = … -
Can I create a table user to make login in the web with differents attributes as the table user in admin in django?
I want to create a table called Professor for example, which could have attributes DNI, pets, parents, for example, and allow them to make the login to application. -
What is the best approach for installing python + django + postgis (geodjango) in docker?
I would appreciate if anyone could share their strategy and perhaps code for dockerfile and docker-compose to successfully create a container which will run django with postgis. More specifically: What image are you based on? What image did you use for postgres-postgis? What dependencies did you install as prerequisites for the various python packages and postgis? Specifically how did you install GDAL? What commands did you run in psql? Thanks in advance! -
Django: how to access all posts from a specific user
I am working on a project and I am a beginner in Django. I am trying to get all the product posts from specific user and then show them. What I want to do is the user which is logged in can see product posts created by himself. But my template syntax seem to have an error. This is the code I am using to get all the product posts. <section class="page-section bg-light mb-0"> <div class="container"> {% for product in products.all if product.creator.username == 'naveen' %} {% endfor %} </div> </section> For checking purposes I am using a user by 'naveen' but later on I will show it by user who is logged in. The error it is showing me is: TemplateSyntaxError at / 'for' statements should use the format 'for x in y': for product in products.all if product.creator.username == 'naveen' -
Got AttributeError when attempting to get a value for field `addrs` on serializer `EmployeeSerializer`
Can someone please help me to how to write this program? using pthon 3 and django 3 I'm getting this error The serializer field might be named incorrectly and not match any attribute or key on the Employee instance. Original exception text was: 'Employee' object has no attribute 'addrs'. This is my models.py file class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) salary = models.IntegerField() location = models.CharField(max_length=100) def __str__(self): return self.name class Address(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) place = models.CharField(max_length=50) city = models.CharField(max_length=50) dist = models.CharField(max_length=50) state = models.CharField(max_length=50) def __str__(self): return self.place This is my serializers.py file class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): addrs = AddressSerializer(required=True) class Meta: model = Employee fields = ['name', 'position', 'salary', 'location', 'addrs'] This is my views.py file class EmployeeView(APIView): def get(self, request): employee = Employee.objects.all() serializer = EmployeeSerializer(employee, many=True) return Response(serializer.data) def post(self, request): serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class EmployeeViewId(APIView): def get_object(self, id): try: return Employee.objects.get(id=id) except Employee.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, request, id): employee = self.get_object(id) serializer = EmployeeSerializer(employee) return Response(serializer.data) def put(self, request, id): employee = self.get_object(id) serializer = EmployeeSerializer(employee, data=request.data) if serializer.is_valid(): serializer.save() return … -
Django freeze when use Form
Django freeze when I try to render a form. This is my forms.py: from django.forms import ModelForm from .models import Evento class EventoForm(ModelForm): class Meta: model = Evento fields = ['codreserva','fecha','incidencia','descripcion'] And this is my model: class Evento(models.Model): codreserva = models.ForeignKey(Reserva, on_delete=models.CASCADE, verbose_name='Cod. Reserva') fecha = models.DateTimeField(verbose_name='Fecha') incidencia = models.ForeignKey(Incidencia, on_delete=models.CASCADE, verbose_name='Incidencia', null=True, blank=True) descripcion = models.TextField(null=True, blank=True) usuario = models.ForeignKey(User, on_delete=models.PROTECT) activo = models.BooleanField(default=True, verbose_name='Activo') fechacierre = models.DateTimeField(verbose_name='Fecha cierre', null=True, blank=True) Just doing this: e = EventoForm() e.as_table() Django freeze for minutes, and stop webbrowser Debugging, I can see it stop in boundfields.py. My Django version is 2.2.12 an Python 3.8 and I try with diferent browser. -
Using the django-embed-video to make blog posts
I am new to Python and am trying to make a music style blog where one can post YouTube videos, Soundclound links etc. using the Django admin page. I have tried using the URLfield model but it doesn't seem to work. I then found django-embed-video, but have only managed to get it to work as a separate model. models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from embed_video.fields import EmbedVideoField class Item(models.Model): video = EmbedVideoField() # same like models.URLField() def __str__(self): return self.video class Post(models.Model): title = models.CharField(max_length=100) url = models.URLField(max_length=500, default='') # same like models.URLField() content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post from embed_video.admin import AdminVideoMixin from .models import Item admin.site.register(Post) class ItemAdmin(AdminVideoMixin, admin.ModelAdmin): pass admin.site.register(Item, ItemAdmin) home.html template {% extends "blog/base.html" %} {% load embed_video_tags %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <iframe src="{{ post.url }}"></iframe> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} … -
Django Allauth Login with Amazon extra fields
I've added Allauth with Amazon provider to my Django website for better and fast login. I obtain similar information: { "user_id": "amznl.account.K2LI23KL2LK2", "email":"mhashimoto-04@plaxo.com", "name" :"Mork Hashimoto", } The library the "name" in fist_name and last_name with a workaround, and ok, but i need also more information as prefer/last/almost one shipping address and more.. what I can obtain it? Here there are some information to make it, but I haven't understood well (Amazon docs). I try to explicit in settings.py just for test : SOCIALACCOUNT_PROVIDERS = { 'amazon': { 'SCOPE': "profile" } } But if I try to make a Login I receive: GET /accounts/amazon/login/callback/?error_description=An+unknown+scope+was+requested&state=2uIPayVsbkFp&error=invalid_scope HTTP/1.1" 200 55965 Without SOCIALACCOUNT_PROVIDERS, work but I receive only three informations...