Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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... -
How to validate many to many field objects before insert into database in django model
I have model "cart" and it has a many to many field named "products". I wanna check if there is a product in products that is not active, prevent from creating the cart object class Product(models.Model): price = models.PositiveIntegerField(blank=True) active = models.BooleanField(default=True) objects = ProductQuerySet.as_manager() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="cart") products = models.ManyToManyField(Product, blank=True) subtotal = models.IntegerField(default=0, blank=True) objects = CartManager.as_manager() -
Update Post clicking on a button: Django
Hope someone can help me! I'm pretty sure that there's a little error I can't detect. In my website I've got a list of items with an update button. Once i click on the button I keep having this error about the url: Reverse for 'edit_info' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['search/(?P<slug>[-\\w]+)/edit/$'] Am I missing something maybe on the urls.py file? Here's the code, Thanks a lot! views.py def edit_info(request, slug): instance = get_object_or_404(Info, slug=slug) if request.method == 'POST': form = InfoForm(request.POST, instance=obj) if form.is_valid(): instance = form.save(commit=False) instance.utente = request.user instance.save() return render(request, 'search/user.html') else: form = InfoForm(instance=obj) template = 'search/option.html' context = {'form': form} return render (request, template, context) urls.py urlpatterns = [ path('', homeView.as_view(), name='home'), path('option/', views.AddInfo, name='option'), path('delete/<int:id>', views.DeleteInfo, name='delete'), re_path(r'^search/(?P<slug>[-\w]+)/edit/$', views.edit_info, name='edit_info'), path('signup/', core_views.signup, name='signup'), path('user/', userListView.as_view(), name='user'), path('searches/', searchesView.as_view(), name='searches'), ] template html: <div class="info_band"> <!-- insert table info --> <table> <tr><th><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr> <td> <a href="{% url 'edit_info' slug=instance.slug %}"><button type="button" class=" btn btn-default"> Update </button></a> </td> </tr> <tr> <td> <button>Delete</button> </td> </tr> </table> … -
For nginx, am I listening to port 443 or port 3000 for this url https://localhost:3000?
I am trying to navigate through the weeds of nginx and reverse proxy passing and one area that I am getting confused on is the port mappings. Here is an example nginx configuration file: server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name www.domain.com; passenger_enabled on; root /home/ubuntu/app/public; include snippets/self-signed.conf; include snippets/ssl-params.conf; } What I am specifying here is that my app should listen to port 443 because it has a self signed certificate on it. It won't accept port 80 http but only 443. Here is an example I found about proxy_passing to localhost. Which is what I want to do. Here is the example: server { listen 443; server_name localhost; ssl on; ssl_certificate server.crt; ssl_certificate_key server.key; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Client-Verify SUCCESS; proxy_set_header X-Client-DN $ssl_client_s_dn; proxy_set_header X-SSL-Subject $ssl_client_s_dn; proxy_set_header X-SSL-Issuer $ssl_client_i_dn; proxy_read_timeout 1800; proxy_connect_timeout 1800; } } Here is what I don't understand and could use some clarification. What port/url am I listening to in the second example? In the server block I see this: listen 443; server_name localhost; That means we are … -
Keeping track of non registered user in a django website
I'm making a django website and want to keep record of the people who didn't registered in my website like what all they searched in my website and all.For that what should I do to get all that information?? -
Dajngo: refreshing page resubmit last form
I have a view like: def some_view(request, page_url): form = UserTicketForm(request.POST) if request.method == 'POST': if form.is_valid(): first_name = request.POST.get('first_name') ticket_text = request.POST.get('ticket_text') data = dict( form=UserTicketForm, ) return render(request, 'front/some_page.html', data) and in HTML page it has: {% csrf_token %} {% bootstrap_form form %} {% block submit %} <div class="button_holder"> <button type="submit" name="register-submit" class="btn btn-primary" value="send"> submit </button> </div> {% endblock %} each time I refresh the page, it resubmits the last submitted form. how can fix this issue? -
Adding Items to cart
whenever am trying to add items to cart it is not showing in cart.No errors are there template also working fine but http://127.0.0.1:8000/admin/ecom/orderitem/ in this items are not showing. I am trying to solve this from three days but it is not working. This is views from django.shortcuts import render, get_object_or_404, redirect from .models import Item, Checkout, Order, Orderitem from django.urls import reverse_lazy from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView class CheckoutEditView( CreateView ) : model = Checkout template_name = 'checkedit.html' fields = '__all__' success_url = reverse_lazy('blank') def item_list(request): context = { 'items':Item.objects.all() } return render(request,'item_list.html',context) class CheckListView(ListView): model = Checkout template_name = 'blank.html' def check2(request): return render(request,'ckeck2.html') def front(request): return render(request,'front.html') def blank(request): return render(request,'blank.html') def product(request): return render(request,'product-page.html') def checkout(request): return render(request,'checkout-page.html') def home(request): return render(request,'home.html') class ArticleDetailView(DetailView): model = Item template_name = 'home.html' context_object_name = 'batman' def home_page(request): return render(request,'home-page.html') def add_to_cart(request,slug): item = get_object_or_404(Item,slug=slug) order_item = Orderitem.objects.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: order = Order.objects.create(user=request.user) order.items.add(order_item) return redirect("core:article_page",slug=slug) whenever am trying to add items to cart it is not showing in cart.No errors are there template also working fine but http://127.0.0.1:8000/admin/ecom/orderitem/ in this … -
Permission issue in custom user model in django
I am trying to create a custom user model in my Django application. In my app user_app i have added the below code in my models.py : from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class RestrauntManager(BaseUserManager): def create_user(self, username, email, phone, restraunt_name, is_staff=False, is_admin=False, is_active=True, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have a username') if not password: raise ValueError('User must have a password') if not phone: raise ValueError('User must have a phone number') if not restraunt_name: raise ValueError('User must have a restraunt name') user = self.model( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name ) user.set_password(password) user.staff = is_staff user.active = is_active user.admin = is_admin user.save(using=self._db) return user def create_staffuser(self, email, username, phone, restraunt_name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name, is_staff = True ) return user def create_superuser(self, email, username, phone, restraunt_name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name, password = password, is_staff = True, is_admin = True ) user.save(using=self._db) return user class Restraunt(PermissionsMixin, AbstractBaseUser): email = models.EmailField(verbose_name = 'email', max_length=60, unique=True) username …