Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/cart/">": "Order.cart" must be a "Cart" instance
Cannot assign "<HttpResponseRedirect status_code=302, "text/Html; charset=utf-8", url="/cart/">": "Order.cart" must be a "Cart" instance. What does this error mean new in Django please help. I follow some tutorial to but I don't understand what this error means so Kindly please help me to solve this problem views.py class CheckoutView(FormMixin, DetailView): model = Cart template_name = "carts/checkout_view.html" form_class = GuestCheckoutForm def get_order(self, *args, **kwargs): cart = self.get_object() new_order_id = self.request.session.get("order_id") if new_order_id is None: new_order = Order.objects.create(cart=cart) self.request.session["order_id"] = new_order.id else: new_order = Order.objects.get(id=new_order_id) return new_order def get_object(self, *args, **kwargs): cart_id = self.request.session.get("cart_id") if cart_id == None: return redirect("cart") cart = Cart.objects.get(id=cart_id) return cart def get_context_data(self, *args, **kwargs): context = super(CheckoutView, self).get_context_data(*args, **kwargs) user_can_continue = False user_check_id = self.request.session.get("user_checkout_id") if not self.request.user.is_authenticated or user_check_id == None:# or if request.user.is_guest: context["login_form"] = AuthenticationForm() context["next_url"] = self.request.build_absolute_uri() elif self.request.user.is_authenticated or user_check_id != None: user_can_continue = True #return redirect "address select view" else: pass if self.request.user.is_authenticated: user_checkout, created = UserCheckout.objects.get_or_create(email=self.request.user.email) user_checkout.user = self.request.user user_checkout.save() self.request.session["user_checkout_id"] = user_checkout.id context["user_can_continue"] = user_can_continue context["form"] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): email = form.cleaned_data.get("email") user_checkout, created = UserCheckout.objects.get_or_create(email=email) request.session["user_checkout_id"] = user_checkout.id return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): … -
Storing unix timestamp as an IntegerField
Is it a bad idea to store a unix time stamp as an integer and simply convert it to datetime when needed in Django ? I found the UnixDateTimeField field from the django-unixdatetimefield package, but I don't see the benefit. You can also override the pre_save method on the DateTimeField but it adds unecssary complexity. the above mentioned methods are found at this link: django - make datetimefield accept unix timestamp -
Patch method not working for id in nested model serializer
I have two models , and I want to update them. When I update a field except ID ,it works fine. However, I can not update ID field of matrix cell object shown below.Also, I see ID field in get method. class DecisionMatrixSerializer(serializers.ModelSerializer): matrix_cell = DecisionMatrixCellSerializer(many=True) class Meta: model = DecisionMatrix fields = ["id", ......, "matrix_cell"] def update(self): for mc in matrix_cells: mc.get("id") #this return None mc.get("name") #but this works class DecisionMatrixCellSerializer(serializers.ModelSerializer): class Meta: model = DecisionMatrixCell fields = "__all__" -
Django function not functioning correctly
In my Order model, I have two field Diagnosis_note and Internal_memo, if one of the fields is blank, I want to display a red button and a green button if both are blank. However, currently in my function, if Diagnosis_note or both fields are blank, it displays a green button and if Internal_memo field is blank is displays a red button. It should display a red button if either one of it is blank or not blank and green if both are blank. Something is wrong with my is_complete function, but I can't figure out what. class Order(models.Model): Diagnosis_note = models.CharField(max_length=30, blank=True) Internal_memo = models.CharField(max_length=100, blank=True) def is_complete(self): fields_list = [self.Diagnosis_note, self.Internal_memo] if self.Diagnosis_note or self.Internal_memo is None: return True else: return False html {% if Order.is_complete %} <td><a href="{% url 'accounts:special-notes' Order.id %}" class="btn btn-danger" role="button"><i class="fas fa-check-circle"></i></a></td> {% else %} <td><a class="btn btn-success" role="button"><i class="far fa-circle"></i> </a></td> {% endif %} -
How to do connection or migrations between different MySQL databases and Different Django App's?
I am new to Django, your help would be greatly appreciated. please let me know what mistakes i am making. can someone give me an example with at least 2 apps and 2 Databases. I have 3 apps cherry, apple and mango in my Django project. For every app there is "models_cherry.py, models_apple.py and models_mango.py". I have created 3 databases in MySQL workbench DBtable1, DBtable2 and DBtable3. When i fires following queries on windows PowerShell for migrations, it should create tables in the databases. migrations should be done on databases. python manage.py makemigrations 2) python manage.py migrate The above commands create tables for only one model for one database. My Question is, i want to create tables for all the models for all respective databases. i.e. For classes in file models_cherry.py into database DBtable1, for classes in file models_apple.py into DBtable2 and for classes in models_mango.py into DBtable3? Here is a code for settings.py and routers files: #Settings.py DATABASE_ROUTERS =['apple.Routers.core_router.core_router', #Path to router file 'mango.Routers.man_router.man_router'] DATABASE_APPS_MAPPING = {'core':'core', 'man':'man'} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'PORT': '3306', 'NAME': 'DBtable1', 'USER': 'root', 'PASSWORD': 'root', 'OPTIONS': { 'autocommit': True, }, }, 'core': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'PORT': '3306', … -
Django Following Table
How can i alter my code so that the user logged is not able to follow themselves. I tried unique_together but could not get it to work I will be using a button on other users profile pages to add the user to the logged in users following list in this table. class FollowList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) following = models.ManyToManyField(User, related_name='followers') -
Error: TemplateDoesNotExist at /app/index.html
I'm stucking with this error message for hours, tried different solutions from here, but nothing helps. When I run the server I get this error message: TemplateDoesNotExist at /app/index.html My app structure settings.py in contactform: I add these 2 lines in 'DIRS', but didn't help INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'app', 'templates', 'app'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
HOw to connect Haystack with Elastic 5
I am having a Django Project and try to implement Elasticsearch using Django But I am facing one issue ..... My Elasticsearch version is 5.6 and django-haystack==2.8.1 In this Haystack documentation it mention that we need to create an Engine in our settings.py https://django-haystack.readthedocs.io/en/master/tutorial.html#elasticsearch This is my settings But this is the Default Version HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.1.1.1:9200/', 'INDEX_NAME': 'haystack', }, } I am unable to integrate version 5 Engine with my project It throws Internal Server Error Any idea regarding this -
RelatedObjectDoesNotExist at / CustomUser has no customer
Hlw,I am working on a Djang0 2.2.15 project,I used allauth to set up my user account,I used a function called def cartData(request): in utils.py that I called in views.py function, def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems':cartItems ,'order':order, 'items':items} In models.py the class which I used onetoone relationship with user is, from django.db import models from django.conf import settings from django.urls import reverse from django.contrib.auth import get_user_model class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name But i whenever I run my project I found this error on console, users.models.CustomUser.customer.RelatedObjectDoesNotExist: CustomUser has no customer. the screenshot for error message in the browser is given below, Browser error message Browser error message -
On makemigrations Auto-generated field 'objectjourney_ptr' clashes with declared field of the same name
#parent class class ObjectJourney(Base): journey_type = models.ForeignKey('Journey.JourneyType') entry_time = models.DateTimeField(auto_now_add=True) exit_time = models.DateTimeField(null=True,blank=True) #child class class BookingJourney(ObjectJourney): journey_object = models.ForeignKey('RequestBooking.Booking') journey_entity = models.ForeignKey( 'UserManagement.C24customer', related_name='journeys') Migrations file contains migrations.CreateModel( name='BookingJourney', fields=[ ('objectjourney_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='Journey.ObjectJourney')), ], options={ 'abstract': False, }, bases=('Journey.objectjourney',), ), #Following are the error trails visible in terminal File "/home/jagdamba/testenv/lib/python3.6/site-packages/django/db/migrations/state.py", line 308, in render_multiple model.render(self) File "/home/jagdamba/testenv/lib/python3.6/site-packages/django/db/migrations/state.py", line 579, in render return type(self.name, bases, body) File "/home/jagdamba/testenv/lib/python3.6/site-packages/django/db/models/base.py", line 253, in __new__ base.__name__, django.core.exceptions.FieldError: Auto-generated field 'objectjourney_ptr' in class 'BookingJourney' for parent_link to base class 'ObjectJourney' clashes with declared field of the same name. My attempts to solve this error -Deleted migrations and created new migration. -ALso followed steps of this article... https://www.kidstrythisathome.com/2016/10/wtf-django-moving-models-part1.html -
AcceptHeaderVersioning for Django Rest Framework
I'm having challenges trying to implement versioning for a REST API I am working on. There are several solutions such as this. However, they seem outdated and don't work when i try to apply them to my project. As much as the solution doesn't work for me, i would like to use a similar approach. I started by changing my folder structure from ./api ├── CustomTokenModifications.py ├── __init__.py ├── __pycache__ │ ├── CustomTokenModifications.cpython-38.pyc │ ├── __init__.cpython-38.pyc │ ├── metadata.cpython-38.pyc │ ├── permissions.cpython-38.pyc │ ├── serializers.cpython-38.pyc │ ├── tasks_api.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── views.cpython-38.pyc ├── apps.py ├── metadata.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ └── __init__.cpython-38.pyc ├── permissions.py ├── serializers.py ├── tasks_api.py ├── tests.py ├── urls.py └── views.py to this | apps.py | CustomTokenModifications.py | metadata.py | middleware.py | permissions.py | serializers.py | tasks_api.py | tests.py | urls.py | views.py | __init__.py | +---migrations | | __init__.py | | | \---__pycache__ | __init__.cpython-38.pyc | +---v1 | | admin.py | | apps.py | | CustomTokenModifications.py | | metadata.py | | permissions.py | | serializers.py | | tasks_api.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | __init__.py | | … -
Load static files in Django in a HTML page
How can i load static files such as CSS, JS or images etc., in HTML associated with Django? I couldn't get even by reading the docs. So, I want a solution not a django docs link Thanks in advance... -
How to avoid long list of data in Django view's render function?
I am new to Django and am trying to build my first Django website. The content of my website requires a lot of data retrieved from my database(i.e. bar charts of latest data) and currently my solution to this is using the render(request, 'index.html', data) function to pass data to index.html template and use something like var salesValue = {{salesValue|safe}} to use the values. This solution works (though I'm not sure it's a good practice) but it didn't take long before the data dictionary gets so long that it's hard to keep track of everything, plus the code gets very clumsy as well. Is there a more efficient/elegant way to send lots of data to template? Maybe Switch to model base view instead of function based view? Use AJAX calls? Or maybe I should not be doing this in Django? Any suggestions are welcome! Thanks in advance and I apologize if this question seems like an open-ended question, but really it is a very specific problem that's troubling me:) -
Celery not processing few records (randomly skipping) in a list
I am using Celery with Django and it starts skipping records when I am processing them in a loop. for idx,record in enumerate(list): logger.info('Processing line :%s, record: %s', idx, record) In the logs I see: Aug 19 06:33:54 ip-192-168-255-190 api_celery-worker_1[1047]: [2020-08-19 06:33:54,792: INFO/ForkPoolWorker-7] project.tasks.process_list[91de938c-31bb-47e4-9e39-8c1931323643]: Processing line: 7144, 'record data 7144' Aug 19 06:33:54 ip-192-168-255-190 api_celery-worker_1[1047]: [2020-08-19 06:33:54,790: INFO/ForkPoolWorker-7] project.tasks.process_list[91de938c-31bb-47e4-9e39-8c1931323643]: Processing line: 7143, 'record data 7143' Aug 19 06:33:54 ip-192-168-255-190 api_celery-worker_1[1047]: [2020-08-19 06:33:54,788: INFO/ForkPoolWorker-7] project.tasks.process_list[91de938c-31bb-47e4-9e39-8c1931323643]: Processing line: 7142, 'record data 7142' Aug 19 06:33:54 ip-192-168-255-190 api_celery-worker_1[1047]: [2020-08-19 06:33:54,233: INFO/ForkPoolWorker-7] project.tasks.process_list[91de938c-31bb-47e4-9e39-8c1931323643]: Processing line: 464, 'record data 464' Aug 19 06:33:54 ip-192-168-255-190 api_celery-worker_1[1047]: [2020-08-19 06:33:54,231: INFO/ForkPoolWorker-7] project.tasks.process_list[91de938c-31bb-47e4-9e39-8c1931323643]: Processing line: 463, 'record data 463' Initially I thought may be logging is not done but I was inserting records in a database in the loop and the skipped records are not inserted in database also. So I am sure it's not processing those records. I don't understand what could cause this. Any debugging pointers would also help. -
Error on pip install mysqlclient in django
when i gave command pip manage.py migrate at the end it gave an error django.core.exceptions.ImproperlyConfigured: Error loadiing MYSQLdb module. Did you install mysqlclient? later i gave the following command and it gave me this error i also pip installed wheel wheel was successfully installed i did the following with ** ** to highlight i also later installed build tools and it gave the error at the end **(.env) PS C:\Users\ADMIN\ritu_ws> pip install mysqlclient** Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Building wheels for collected packages: mysqlclient **Building wheel for mysqlclient (setup.py) ... error** ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\.env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ADMIN\\AppData\\Local\\Temp\\pip-install-58z5dzou\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\ADMIN\\AppData\\Local\\Temp\\pip-install-58z5dzou\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\ADMIN\AppData\Local\Temp\pip-wheel-84_ujyvq' cwd: C:\Users\ADMIN\AppData\Local\Temp\pip-install-58z5dzou\mysqlclient\ Complete output (23 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension **error: Microsoft … -
Django: relating many-to-many relationships between two pairs of one-to-one related fields
I've created two models in Django extending the default user and group models by using OneToOne relations. The GroupExtended and UserExtended are related through a ManyToMany relation: from django.contrib.auth.models import Group, User class GroupExtended(models.Model): group = models.OneToOneField( to = Group, on_delete = models.CASCADE ) [other fields...] class UserExtended(models.Model): user = models.OneToOneField( User, on_delete = models.CASCADE ) group = models.ManyToManyField( GroupExtended, ) [other fields...] What I would like to obtain is that, when I assign an extended group to the extended user, the associated user also change the group, if possible. Maybe this chart helps to explain myself: chart In other words: Is it possible to relate two many to many relationships in such a way that when I relate two fields, the corresponding one to one related fields are also associated? -
Testing for Signup with already existing email is not working on the test database in django manage.py test command
I am having test case to test my signup API where it will respond back if the email is already taken, or it will return same email id if successfully created. tests.py class SignupTestCase(APITestCase): url = reverse('todos:signup') @classmethod def setUpTestData(self): self.random_num = random.randint(100, 999) self.username = f'Testing{self.random_num}' self.email = f'Testing{self.random_num}@gmail.com' self.password = f'Testing{self.random_num}' def test_signup_pass(self): payload = { 'username': self.username, 'email': self.email, 'password': self.password, } response = self.client.post(self.url, payload) res_data = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(res_data.get('email'), self.email) self.assertEqual(res_data.get('error'), None) def test_signup_fail(self): payload = { 'username': self.username, 'email': self.email, 'password': self.password, } response = self.client.post(self.url, payload) res_data = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(res_data.get('email'), None) self.assertEqual(res_data.get('error'), 'Email is taken') In here, the second test, test_signup_fail has to pass because I am using same email which I have used in test_signup_pass, so it should raise IntegrityError in django signup method and should return an error message as 'Email is taken'. views.py from django.http import JsonResponse from django.contrib.auth.models import User from rest_framework.views import APIView from django.db import IntegrityError # Create your views here. class signup(APIView): def post(self, request): data = request.data email = data.get('email') password = data.get('password') username = data.get('username') user = User() user.email = email user.password = password user.username = username try: user.save() except IntegrityError: … -
How to declare New or Hot tag in E-Commerce product and after 15 days these tags will remove automatically
I am learning Django and creating an e-commerce site. I want to add a tag as ** new ** to my newly arrived products. This tag will be removed automatically after 5/7/15 or 30 days. Also if any product has a big amount of discounts such as 30%, 40%, or more, these products will have a HOT tag automatically. The tag will be automatically removed when the offer expires. Please let me know, how can I do these. Thank you. -
ModuleNotFoundError: No module named 'mysite' when running django app online in heroku
This is my log file: 2020-08-18T18:58:09.804835+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-08-18T18:58:09.804836+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-08-18T18:58:09.804836+00:00 app[web.1]: self.callable = self.load() 2020-08-18T18:58:09.804837+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-08-18T18:58:09.804837+00:00 app[web.1]: return self.load_wsgiapp() 2020-08-18T18:58:09.804838+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-08-18T18:58:09.804838+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-08-18T18:58:09.804838+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-08-18T18:58:09.804839+00:00 app[web.1]: mod = importlib.import_module(module) 2020-08-18T18:58:09.804839+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-08-18T18:58:09.804840+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-08-18T18:58:09.804840+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-08-18T18:58:09.804841+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-08-18T18:58:09.804841+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked 2020-08-18T18:58:09.804842+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-08-18T18:58:09.804842+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-08-18T18:58:09.804843+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-08-18T18:58:09.804843+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked 2020-08-18T18:58:09.806459+00:00 app[web.1]: ModuleNotFoundError: No module named 'mysite' 2020-08-18T18:58:09.806808+00:00 app[web.1]: [2020-08-18 18:58:09 +0000] [11] [INFO] Worker exiting (pid: 11) 2020-08-18T18:58:09.930908+00:00 app[web.1]: [2020-08-18 18:58:09 +0000] [4] [INFO] Shutting down: Master 2020-08-18T18:58:09.931038+00:00 app[web.1]: [2020-08-18 18:58:09 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-08-18T18:58:10.070982+00:00 heroku[web.1]: Process exited with status 3 2020-08-18T18:58:10.123047+00:00 heroku[web.1]: State changed from starting to crashed 2020-08-19T00:31:43.504526+00:00 heroku[web.1]: State changed from crashed to starting … -
Redirect a user to previous page django
Let's say we have a simple django app with a blog model. There are only 3 pages: Home page Blog index Blog post detail The blog posts are listed in 3 locations: In a slider on the home page In the blog index (of course) At the bottom of a blog post There are 2 main ways of using breadcrumbs I've seen on a site: Home / Blog / Blog Post < Back I want to be able to have the "< Back" button go back to whichever the original source came from. I'm aware this could be done with JavaScript. But with Django, I've heard people say on another post that "you shouldn't redirect in template, you should do it in view", but to me that makes no sense as how is the view supposed to know which page to go back to automatically? Anyways, I'm trying to see is: How would you link back to the source page you arrived at a blog post from (i.e., another post, the home page, or the blog index) using django views or in the django template? -
i am able to generate unique slugs in admin but cant figure out how to display them in urls
i want my urls to show slug instead of id, after following a youtube video i reached to a stage where admin is automatically creating slugs when i save my products.. but still i can not figure out how to show slug in url of detailsview ..please help i created a utils.py in my project folder which is named as myawesomecart import string from django.utils.text import slugify def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug my models.py file is as under from django.db import models from django.db.models.signals import pre_save #2 slug from myawesomecart.utils import unique_slug_generator # Create your models here. class product(models.Model): title = models.CharField(max_length=50) slug= models.SlugField(max_length = 250, null = True, blank = True) category = models.CharField(max_length=50, default="your category here") subcategory = models.CharField(max_length=50, default= "your subcategory here") price = models.IntegerField(null=True) desc = models.CharField(max_length=500) pub_date = models.DateField() … -
Why to use a url field in serializers in django rest framework?
Hello guys I am new to django rest framework, I have seen lots of posts about rest framework and have seen people adding url fields to the serializer even though it isn't there in the model. Can someone tell me why we should use this? I have a postserializer like this without url field and I am able to get the response in postman when I run the code. class PostSerializer(TaggitSerializer, serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') tags = TagListSerializerField() class Meta: model = Post fields = ['id','title', 'user', 'tags', 'image'] What advantage I get when I add a url field to this? Is it something related to connecting to frontend or a mobile application? Please do enlighten me about this. Thank you -
Implement OKTA login using PKCE Flow for a SPA using Django Backend
I am planing to implement authentication flow using OKTA for a SPA with already written Django Rest api. My idea is to use okta js sdk for handling authentication in front end and the same html will be pushed to locally hosted file in cordova. I have tried implementing oauth 2.0 flow using django-oAuth-toolkit in django. was not able to figure to how to connect both okta, js, and django Ive learnt that i need to use the OAuth 2.0 Authorization Code with PKCE Flow for better security. Im bit confused and stuck where and how to start. Appreciate your thoughts on the same Is there any library that i can use to easily integrate all of them. or put together bits and pieces of Django plugin to make it work? -
django template system returning same id for different posts
shown below is template of blog.when user likes a post,ajax will call a corresponding view function to do job.For every post,it will have a unique id which i use here for reference.Problem is if i like anypost,the like is going to recently uploaded post.I don't know much about ajax..Please help me.Thank you. {% load static %} <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <title>blog page</title> </head> <body> {% for post in posts %} <h1><a href='{% url "blog:blogpostdetails" post.id %}'>{{ post.post_title }}</h1> <p>loc: <a href='#'>{{ post.post_location }}</a></p> <p>{{ post.post_content|truncatewords:7 }}</p> <p>posted on {{ post.post_timestamp }}</p> <p>posted by <a href='{% url "index:userprofile" post.post_id.username %}'>{{ post.post_id }}</a></p> <form method='POST' id='something'> {% csrf_token %} <input type='hidden' id='postid' name='postid' data-id='{{post.id}}'> <input type='submit' value='like this post'> </form> <p>total like {{ post.likes }}</p> <p>-------------------------------------------------------------------</p> {% endfor %} <div class='tooltip'><h3><a href="{% url 'blog:blogpost' %}">new post</a></h3></div> </body> </html> <style type="text/css"> .tooltip { width: 200px; position: fixed; top:0px; right:0px; left:auto; } </style> {% block javascript %} <script type='text/javascript'> $(document).on('submit','#something',function(e){ e.preventDefault(); console.log($('#postid').attr('data-id')) $.ajax({ type:'POST', url:'{% url "blog:blogpostlike" %}', data:{ postid:$('#postid').attr('data-id'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert('you liked post'); } }); }); </script> {% endblock %} -
how to access individual data in for loop in django template
{ a { 0 { item:1, item2:1 }, 1 { item:1, item2:1 }, 2 { item3:1, item5:1 }, 3 { ite6:1, item7:1 } } } Now I wanna display all (item, item2) from 0,1,2,3 in a for loop. for display in a table. how to access individually.