Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have a question regarding the below code
I have a doubt regarding the output of the code. d=({'country':'India','population':89},{'country':'USA','population':78}, {'country':'UK','population':65},{'country':'Canada','population':70}) for i in d: print(i) [list(i.values())[1] for i in d] I expect the output to be [89,78,65,70], but it's showing ['India', 'USA', 'UK', 'Canada'] -
Is there a different authorization logic when accessing backend via mobile (specifically iphone) browser versus desktop (chrome) browser?
When I try to access a certain page, my backend determines whether the logged in user is allowed to see the page or not. The backend I am using is django/django-rest, and for frontend I am using react (axios for http calls). This is an example of my api call. I want to get the inventory for a user. axios.get(this.url, this.config) .then(res => { this.setState({ products: res.data }) if (res.data.length > 0) { if (!res.data[0].is_owner) { this.setState({ inventory_owner: res.data[0].user_name, is_owner: res.data[0].is_owner }) } } }) .catch(res => { console.log("config2 what happened",this.config) }) this.url is the api url, and this.config is: config = { headers: { 'Authorization': 'Token ' + localStorage.getItem('token') } } I know localStorage is a bad practice but I just wanted to get it working first. The issue I am encountering is that when I make this call on my browser, everything works fine. When I try on my iphone and use chrome browser, I get this in the log: Unauthorized: /api/inventory/f11e72d5-ae28-406f-8cca-a4260a9e65a8/. I believe this message is auto generated by django-rest or django-rest-auth, so that means it doesn't even begin my ViewSet logic yet (there are slightly more rules for whether a person is allowed to see an … -
python / django, where is the root of the namespace?
coming from php, the namespaces are always well defined in php, typically using psr-4 from composer https://getcomposer.org/doc/04-schema.md#psr-4 e.g. you have a folder src/Foo/Bar/Baz you then define in the composer.json file that src/Foo is where the namespace Foo starts thereafter, all subfolders are by convention, a new sub namespace e.g. src/Foo/Bar/Baz/MyClass.php turns into Foo.Bar.Baz.MyClass Say I want to drop a utility python class into my django project, that I want to use in all django "apps" Where would I drop it, and how to properly define the namespace? what is the transparent way to understand namespaces in python? -
How to Notify User that Asynchronous Task is Completed?
I am using threading library for a long-running process in Django. When the process is completed, I want to keep updating progress status on the front-end. I am unable to post anything to the ajax.get() from my thread function. View.py def upload_handler(request, file_loc, filename): // do something with uploaded // I want to notify user that this process is complete via a post class Uploader(View): def get(self, request): file=UploadForm() return render(request,'template.html',{'form':file}) #,'files':files}) def post(self, request): file = UploadForm(data=request.POST, files=request.FILES) if file.is_valid(): x = request.FILES['file'] file.save() filename = str(request.FILES['file']) file_loc = os.path.join(BASE_DIR, 'media', 'images', filename) upload_thread = Thread(target=upload_handler, args=(request, file_loc, filename)) upload_thread.start() return HttpResponseRedirect(reverse('imageupload')) urls.py urlpatterns = [ path('', Uploader.as_view(), name='imageupload'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ajax call script { $.ajax({ type:"get", url:"/uploader", datatype:"json", success:function(data) { console.log(data); alert("Your file is processed now!"); } }); }, 1000); Assume that file uploaded page will remain open till the long process completes. -
How to process django url tags in context variables
I'm creating a django-based website where page content is stored in a model textfield with a detail view of the model displaying it. How can I put {% url %} tags in the content to link to other pages without hard coding links? Putting the tag into the textfield will just print the tag as plain text. (or if inside an href create a broken link) Other options are parsing the content manually inside the view and replacing the tags with the correct url using some django supplied string parser to create the links before sending to the template maybe there is a way to do it in the template with a filter or tag around the variable. I could probably do the manual way but I am hoping there is a django way that I am missing. class Page(models.Model): content = models.TextField(blank=True) class PageView(DetailView): model=Page context_object_name='page' {% extends "base.html" %} {% block content %} {{ page.content|safe }} {% endblock %} -
Integrity error in django foreign key field in django-rest-framework
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below class Site(models.Model): sitename=models.CharField(max_length=255) start_date=models.DateTimeField supervisor=models.ForeignKey(User,on_delete=models.PROTECT) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.sitename) The serializer for this is: class SiteSerializer(serializers.ModelSerializer): supervisor = serializers.ReadOnlyField(source='supervisor.username') class Meta: model = Site fields = ('sitename', 'start_date', 'supervisor') and the view is like: @csrf_exempt def site_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': sites = Site.objects.all() serializer = SiteSerializer(sites, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SiteSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Whenever I post data from postman, it says IntegrityError at /sites/ (1048, "Column 'supervisor_id' cannot be null") I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out. This might be a really little thing but I couldnt figure out where to make the nexessary adjustments. Please help. -
Export a specific data in an app in the django admin to a pdf
I've already set everything that is need to export a data to pdf format. Now, my problem is how can I do this use case to the django admin. Can I accomplish this by action whilst providing the class view then add that specific class view in the action to the modeladmin? Is that possible? How can I do this? This is my class view class PdfCarrier(View): def get(self, request, carrier_id): carrier = Carrier.objects.filter(id=carrier_id).first() params = { 'today': timezone.now(), 'carrier': carrier, 'request': request } response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = "inline; filename=Carrier-Report.pdf" html = render_to_string('carrier/carrier_pdf.html', params) css = [ base.BASE_DIR + '/src/css/bootstrap3/css/bootstrap.min.css' ] HTML(string=html).write_pdf(response, stylesheets=css) return response # return Render.render('carrier/carrier_print.html', params) my url providing it. path('<uuid:carrier_id>/carrier-report.pdf', views.PdfCarrier.as_view(), name="print_carrier"), -
How can we generate a conformation prompt before deleting a comment in Django?
I am trying to link java script and Django views, I have a comments delete view, where its functionality is good but, i need some conformation using javascript before deleting them. I don't have knowledge regarding the Mapping Javascript and Django views. Can any one help me in writing the code? @login_required def delete_my_comment(request, pk): comment = get_object_or_404(Comment, pk=pk) if comment.user == request.user.username: comment.delete() messages.success(request, f' Your comment is deleted') return redirect('post-detail', pk=comment.post.id) <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete Post</a> Can some help me in writing javascript logic for the delete conformation based on above code? Thank you all -
Dynamic and dependent multiple choice field in a Model Admin based on a foreign key choice
I have four models - Company, Employee, Office and Project. Company model is quite independent with no foreign keys. Employee has a foreign key to Company. Office has a foreign key to Company Project has foreign key to Company. It also has CharFields for for employees and offices but unless company is selected they are blank. So basically, I need multiple choice employees and offices related only to that company for which the project is happening. In a way I am able to do it by updating the self._meta.get_field('employees').choices but the problem is when I move to a new record, the choices don't go back to the original static entry. They stay the same as was selected in the previous record. It is as if choices are some kind of in-memory storage that carries through to a new Project record possibly at class level. This is what I am after: On Project Admin screen, we select a company from the foreign key field, Save and Edit and now the screen has two fields with multiple choices for that company's office and employees. We can then choose one or multiple offices and one or multiple employees of the company that will … -
select_related returns value None when querying
I'm trying to get the name field of my Model Category but it returns None. I can confirm that there is a value by running print(post.categories.values()) . which returns QuerySet [{'id': 3, 'name': 'Tasks'}]> Model: from django.db import models class Category(models.Model): name = models.CharField(max_length=30) class Post(models.Model): title = models.SlugField(max_length = 250, null = True, blank = True) body = models.TextField() created_on = models.DateTimeField(null=True) last_modified = models.DateTimeField(null=True) categories = models.ManyToManyField('Category', related_name='posts') class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) View: def blog_detail(request, pk): post = Post.objects.select_related().get(pk=pk) print(post.categories.name) # Returns None!! form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post ) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context) -
django postgresql tests.py RuntimeWarning error
I have a Django app that adds and displays stuff to my postgresql database online at elephantsql.com. My project file setup looks like this: website/ website/ music/ playlist/ __pycache__/ migrations/ static/ templates/ __init__.py admin.py apps.py models.py tests.py urls.py views.py .coverage db.sqlite3 manage.py My project works right now where when I run the server and go to /playlist/ it displays stuff correctly and connects to my postgresql database fine. My settings.py DATABASES object looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'kxvmghva', 'USER': 'kxvmghva', 'PASSWORD': '--an actual password---', 'HOST': 'raja.db.elephantsql.com', 'PORT': '5432', } } Now I'm trying to write test cases in my playlist/tests.py file, but when I try to run these tests I'm getting errors. my testing file I'm trying to run /playlist/tests.py from django.test import TestCase from .models import plays from django.utils import timezone class AnimalTestCase(TestCase): def setUp(self): print("setup") #Animal.objects.create(name="lion", sound="roar") #Animal.objects.create(name="cat", sound="meow") def test_animals_can_speak(self): """Animals that can speak are correctly identified""" print("test") #lion = Animal.objects.get(name="lion") #cat = Animal.objects.get(name="cat") #self.assertEqual(lion.speak(), 'The lion says "roar"') #self.assertEqual(cat.speak(), 'The cat says "meow"') When I run the command "python manage.py test playlist" I get these errors: C:\Users\marti\Documents\kexp\website>python manage.py test playlist Creating test database for alias 'default'... C:\Python36-32\lib\site-packages\django\db\backends\postgresql\base.py:267: RuntimeWarning: Normally Django … -
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array HTTP 200 OK Allow: GET, POST, PUT, DELETE, PATCH Content-Type: application/json Vary: Accept [ { "id": 1, "title": "Push Workout Bjarred", "description": "Kör Hårt!", "exercises": [ 3, 4, 5, 6, 9, 10 ], "cardio": [ 4 ] }, { "id": 2, "title": "Pull Workout Loddekopinge", "description": "", "exercises": [ 1, 2, 7, 8 ], "cardio": [] }, { "id": 3, "title": "CardioPass", "description": "", "exercises": [], "cardio": [ 2, 3, 4 ] } ] Serializer (So I want to display the title and not the name for every exercise) class WorkoutSerializer(serializers.ModelSerializer): class Meta: model = Workout fields = ('id', 'title', 'description', 'exercises', 'cardio') Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :) class Bodypart(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Exercise(models.Model): name = models.CharField(max_length=40) bodyparts = models.ManyToManyField(Bodypart, blank=True) def __str__(self): return self.name class Cardio(models.Model): name = models.CharField(max_length=40) time = models.IntegerField(default=10) def __str__(self): return self.name class Meta: verbose_name_plural = 'cardio' class Workout(models.Model): title = models.CharField(max_length=120) description = models.CharField(max_length=1000, blank=True) exercises = models.ManyToManyField(Exercise, … -
Why using parametrized url in drf giving TypeError?
I am trying to use parametrized url in django rest framework using following url pattern- url(r"^product/(?P<product_id>\d+)/sales/", APIProductSales.as_view()), I was using it this way in the past and it used to work fine. But after some code merge I am getting the below error- File "/home/user/workspace/venv/backend/lib/python3.5/site-packages/rest_framework/views.py", line 478, in dispatch self.initial(request, *args, **kwargs) File "/home/user/workspace/project/website/api_common.py", line 70, in initial % (request.__dict__, str(*args), str(**kwargs)) TypeError: 'product_id' is an invalid keyword argument for this function To debug the issue I print the kwargs before the self.initial function in rest_framework/views.py, the output was as follows - {'product_id': '191' } after this the initial function was throwing TypeError. my view is as follows- class APIProductSales(CustomAPI): @permission_classes((CustomAuthentication, )) def get(self, request,**kwargs): some code and I have also tried it this way but with no luck. class APIProductSales(CustomAPI): @permission_classes((CustomAuthentication, )) def get(self, request,product_id): some code What can be the issue with this? -
Containerizing Django application connected to sql server
Guidance required to containerize an existing django application which is connected to an existing docker image of sql server. I am not understanding how to write a docker-compose file which will have the database entries which will connect to an existing sql server database image. The sql_server image is running on port 1433 and access URL is localhost:1433. I can connect to the server and app works fine when I run from a virtual environment. version: '3' services: db: image: sql_server web: build: . command: python manage.py runserver 0.0.0.0:8003 volumes: - .:/code ports: - "8003:8003" depends_on: - db Also, the above snippet is from Docker docs, my working folder will be different, I guess the ./code reference should be replaced to the working folder. -
Django sending users to the wrong template location?
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error. I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory. learning_log\users\urls.py from django.contrib.auth import views as auth_views from . import views app_name = 'users' urlpatterns = [ # Login page. path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), ] learning_logs\urls.py """learning_logs URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ """Defines URL patterns for learning_logs.""" from django.urls import path from . import views … -
Django - how to write test for DRF ImageField
I have the following serializer: from rest_framework.serializers import Serializer, ImageField Class MySerializer(Serializer): avatar = ImageField() how can i write unit test for it? I used the django TestCase, but it raises error. from django.test import TestCase class MySerializerTest(TestCase): def setUp(self): self.data = {} ... def test_image(self): import tempfile self.data['avatar'] = tempfile.NamedTemporaryFile(suffix=".jpg").file r_data = json.dumps(self.data) j_data = json.loads(r_data) serializer = MySerializer(data=j_data) if not serializer.is_valid(): import pprint pprint.pprint(serializer.errors) self.assertEqual(serializer.is_valid(), True) but it raises following error: TypeError: Object of type 'BufferedRandom' is not JSON serializable what's my mistake? how can i write a test for image field? -
django-taggit not working when using UUID
I have gone through the customization documentation here https://django-taggit.readthedocs.io/en/latest/custom_tagging.html#genericuuidtaggeditembase I am using the following code, when I save the product through django admin, tables are getting populated properly but when I am reading a product, tags are coming as None class TaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class Product(ModelBase): supplier = models.ForeignKey(ApplicationUser, on_delete=models.DO_NOTHING) name = models.CharField(max_length=255) tags = TaggableManager(through=TaggedItem) def __str__(self): return "{0}".format(self.tags) class ModelBase(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True The code above create a new table 'catalog_taggeditem' in my django application called 'catalog'. There is also the default table from django-taggit called 'taggit_taggeditem'. Seems like while reading, it can't connect the dots. I am not sure, what am I missing, there are no errors. Thanks for your help. -
Where To Override Django CreateView?
I opened up a prior issue on SO regarding manytomany fields not being saved in Django Createview here. Django CreateView With ManyToManyField After troubleshooting most of today, I have found that this code actually works: def form_valid(self, form): instance = form.save(commit=False) instance.save() instance = form.save() if instance.access_level == "Custom": obj = NewAuthor.objects.get(secret=instance.name) obj.access.add(instance.created_by.id) print(instance.created_by.id) print(obj.access.all()) instance = form.save() obj.save() form.save_m2m() instance = form.save() When I issue the print(obj.access.all()) I can see in my console that the obj.access.add(instance.created_by.id) Line of code actually does exactly what I want it to do...to add the created_by_id to the access many to many field that I have defined in my model. However, when the record actually gets cut, only the objects that the user selected in the form are added to the access field, and the created_by never makes it to the database. Should I be overriding CreateView somewhere else in order for the created_by to take affect? It appears as if my initial update in form_valid is being overwritten is what I suspect. Actually I've proven it because my update is in fact in my console but not making it to the database. Thanks in advance for any thoughts on how best to solve. -
why i am not getting a followed_by(followers) entry showing up on my page
i am making a twitter like clone(just to learn how things works in django) so i am basically trying to set up a many_to_many relationship. i want to add the functionality of showing 'FOLLOWED_BY' and 'FOLLOWING' to a user profile but list of 'FOLLOWED_BY' is not showing on the page please someone help me! in the models.py i have define two relationship user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='profile', null=True, blank=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by', blank=True) and in the user_detail.html i have the code for how a profile should look like this is the models.py module: from django.conf import settings from django.db import models # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='profile', null=True, blank=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by', blank=True) def __str__(self): return str(self.following.all().count()) below is the code for user_detail.html file: {% extends "base.html" %} {% block content %} <div class="row"> <div class="col-sm-3 col-xs-12" style="background-color: yellow"> <h1>{{ object.username }}</h1> <p>Followers: {{ object.followed_by.count }}</p> </div> <div class="col-sm-9 col-xs-12"> <h1>Tweets</h1> {% for tweet in object.tweet_set.all %} {{ tweet }}<br/> {% endfor %} <hr/> <h1>Following</h1> {% for user in object.profile.following.all %} <a href='/{{ user.username }}'>{{ user.username }}</a><br/> {% empty %} <h4>Not following any users</h4> {% endfor %} <hr/> <h1>Followed By</h1> {% for … -
How to implement POST verb to an url with specific pk
im implementind a stock shoes manager with REST architecture using Django + Django rest. Currently my projetct looks like this: models.py class Shoe(models.Model): description = models.CharField(max_length=100, null=False, blank=False) provider = models.CharField(max_length=100, null=False, blank=False) type = models.CharField(max_length=2, choices=TIPO_CHOICES, null=False, blank=False) cost_price = models.DecimalField( max_digits=6, decimal_places=2, verbose_name = 'Preço de Custo', null=False, blank=False ) sale_price = models.DecimalField( max_digits=6, decimal_places=2, verbose_name = 'Preço de Venda', null=False, blank=False ) def total_amount(self): total = Stock.objects.filter(pk=self.pk).aggregate(models.Sum('amount')) return total['amount__sum'] or 0 class Stock(models.Model): shoe = models.ForeignKey( Shoe, on_delete = models.CASCADE, verbose_name = 'shoe', related_name = 'stock') size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False) amount = models.IntegerField(null=False, default=0) class Meta: verbose_name = 'Stock' unique_together = ('shoe', 'size') constraints = [ models.CheckConstraint(check=models.Q(amount__gte=0), name='amount_gte_18'), ] ordering = ['-amount'] serializers.py class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = ['size', 'amount'] class ShoeSerializer(serializers.ModelSerializer): stock = StockSerializer(many=True, read_only=True) class Meta: model = Shoe fields = ['description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock'] api/urls.py app_name = 'api' urlpatterns = [ path('', views.index, name='index'), path('', include(router.urls)) ] views.py class ShoeViewSet(viewsets.ModelViewSet): queryset = Shoe.objects.all() serializer_class = ShoeSerializer filter_class = ShoeFilter routers.py router = routers.DefaultRouter() router.register(r'resources', ShoeViewSet) The ShoeViewSet provides me two endpoints: resources/ with the verbsGET(returns the list of all shoes via list method) and POST (add a new … -
Create URL based on values from model
I want to create a blog page and it works perfectly but I want to change the URL for the specific blog post. Currently the URL to the specific blog post is myurl.com/blog/pk , but I want it to be myurl.com/blog/category/title instead. How can I do this? Also appreciate any kind of critique to the code, if you feel like it. Models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() created_on = models.DateTimeField(null=True) last_modified = models.DateTimeField(null=True) categories = models.ManyToManyField('Category', related_name='posts') class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) Views.py from django.shortcuts import render from .models import Post from .models import Comment from .forms import CommentForm from django.http import HttpResponse def blog_index(request): posts = Post.objects.all().order_by('-created_on') context = { "posts": posts, } return render(request, "blog_index.html", context) def blog_category(request, category): posts = Post.objects.filter( categories__name__contains=category ).order_by( '-created_on' ) if not posts: return HttpResponse(status=404) context = { "category": category, "posts": posts } return render(request, "blog_category.html", context) def blog_detail(request, pk): post = Post.objects.get(pk=pk) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post ) comment.save() comments = Comment.objects.filter(post=post) context = { "post": … -
How to redirect my user after posting a comment
So I just learned how to add comments on my blog. Now the problem is that I can't redirect my user to the concerned blog post. That's really frustrating because I see a lot of people on the Internet talking about get_absolute_url and it confuses me a lot. from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Annonce, Comments from django.shortcuts import get_object_or_404 from django.core.paginator import Paginator def annonceView(request, annonce_id): annonce = get_object_or_404(Annonce, pk=annonce_id) comments = Comments.objects.filter(auteur=annonce_id) if request.method == "POST": content = request.POST["add_comment"] if content: new_comment = Comments.objects.create(content=content, auteur=annonce) new_comment.save() return redirect(annonce) context = { "annonce": annonce, "comments": comments, } return render(request, "annonces/annonce.html", context) -
Django Datetime.strptime displays unwanted time
I am trying to inject a date into my django html template. I have the string "2019-05-26" and I am trying to convert it to datetime format for django to display as "May 26, 2019" on the webpage. The problem is that it displays "May 26, 2019 Midnight" instead of just "May 26 2019". It adds the "Midnight" because of a trailing 00:00 that is added on from the function, How do I remove the trailing "midnight"? timestamp = transaction["timestamp"] data = (timestamp[:10]) if len(timestamp) > 10 else timestamp print(data) data2 = datetime.strptime(data, '%Y-%m-%d') -
Django reverse referrential integrity
First, excuse the title, I have searched for hours but still can't find what the technical name is for this question. But, supposing you have a many-to-one relationship like books and chapters: class Book(models.Model): name=models.CharField(max_length=200) class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) name=models.CharField(max_length=200) Referrential integrity would require that every chapter points to a book that exists. I require also the opposite, that every book is pointed to by at least one Chapter. Two immediate implications are that: - Whenever a book is created, at least one chapter must simultaneously be created. - Whenever the last remaining chapter of a book is deleted, the book must be deleted automatically. My questions are: - What is actually the correct term to describe this constraint? - Is it possible in any RDBMS to enforce this constraint in the DB? Or does it have to be created at the application level. - In Django, how could I create this constraint? -
Error in removing product from cart in Django?
I am facing an error in removing products from cart. When i add product in cart by setting the quantity and click on remove an error is displayed. local variable 'product' referenced before assignment I have product in models.py file and referring it from their by importing the models and have tried by changing the name but still it gives an error. views.py def update_cart(request,slug): request.session.set_expiry(1200000) try: qty=request.GET.get('qty') update_qty=True except: qty=None update_qty=False try: the_id=request.session['cart_id'] except: new_cart=Cart() new_cart.save() request.session['cart_id']=new_cart.id the_id=new_cart.id cart = Cart.objects.get(id=the_id) try: product=Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product) if created: print("yeah") if update_qty and qty: if int(qty)<=0: cart_item.delete() else: cart_item.quantity=qty cart_item.save() else: pass return HttpResponseRedirect(reverse("carts:cart")) models.py class CartItem(models.Model): cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True) product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True) accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True) quantity=models.IntegerField(default=1) updated = models.DateTimeField(auto_now_add=True,auto_now=False) line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) objects = CartManager() def __unicode__(self): try: return str(self.cart.id) except: return self.product.title If anyone can please help it would be really appreciated? Note I have seen other link of stackoverflow but none helped.