Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass a list of dictionary in chartjs labels and data?
I'm trying to show my data into chart js graph, my data format is this: > {length: 3, objects: Array(3)} length: 3 objects: Array(3) 0: {counter: 1, date: '2022-06-01 00:00:00', income: '233.000', …} 1: {counter: 2, date: '2022-05-01 00:00:00', income: '1000.000', …} 2: {counter: 3, date: '2022-04-01 00:00:00', income: '89.000', …} length: 3 [[Prototype]]: Array(0) [[Prototype]]: Object here is what i tried in my js: function listChartMonOutcome(){ $.ajax({ type:'GET', url:'/listcharts/data/', success:function(data){ var totalMonthCanvas = $('#listChart').get(0).getContext('2d') var totalMonthData = { labels: [ data ], data:{ datasets:[{ data:[{ data }] }] } } var totalMonthOptions = { responsive : true, maintainAspectRatio : false, datasetFill : false, parsing: { xAxisKey: 'income', yAxisKey: 'date' } } var totalMonthChart = new Chart(totalMonthCanvas, { type: 'bar', data: totalMonthData, options: totalMonthOptions }) } }) } listChartMonOutcome() } <div class="card-body"> <div class="chart"> <canvas id="listChart" style="height:250px; min-height:250px"></canvas> </div> </div> but it shows nothing, in the console as well. and also tried this in the data : labels = [data.map(({datE}) => date) ] datasets: [ { data: [ data.map(({income}) => income) ], } ] but raise this error: Uncaught TypeError: data.map is not a function is there any solution for this problem please? Thank you for helping -
Directing to nested URL with react router from server
I am building an app with django3.2 and React 17 using react-router-dom. My react app is served at https://www.example.com/ And if I navigate within the app to https://www.example.com/auth/signup I get the form, however, if I input the url directly into the browser I am taken to a blank page. In my django.urls, I have a catch all that should send the path down to my react app, and in local development it works great. urlpatterns = [ ..., re_path(r'^(?:.*)/?$', homepage), ] PROBLEM: In production I am taken to a blank page. I suspect it has to do with relative paths in production. I've followed these questions: Django static file serving in conflict with React Router React router not loading dynamic url in production And so far have tried: Adding "homepage": "https://www.example.com/" to my package.json. Adding <base href="/" /> to index.html Adding "homepage": "." to package.json But so far nothing has worked, and I need this feature, particularly for email verification. Happy to clarify anything or share front end code. -
What to do if queryset is none
I have a News model, where each instance has a unique date. Which means that every day has exactly one News-instance related to it. I am redirecting to the detail-view of the News-instance from the navbar. To achieve this am I using a context_processor. The context_processor.py file looks like this: from news.models import TodayNews import datetime def todays_news(request): todays_news = TodayNews.objects.get(date=datetime.date.today()) return {'news': todays_news} This works completely fine as long as the News model has an instance on that particular date. Otherwise it returns the following error (which is very logical): TodayNews matching query does not exist. My question is, how can I do something different if the query is empty, for example if one particular date does not have a news-instance? What should I return instead of 'news': todays_news? -
Django python GET http://localhost:8000/topics 404 (Not Found)
I am learning Django using "Python Crash Course" by Eric Matthes ch.18- 20. I am trying to run the get request of my topics.html and I'm getting the error below... GET http://localhost:8000/topics 404 (Not Found) File urls.py /learning_log # from django.conf.urls import include, url OUT_OF_DATE from django.urls import include, re_path as url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('learning_logs.urls', namespace='learning_logs')), ] File urls.py /learning_logs """Defines URL patterns for Learning_logs.""" # from django.conf.urls import url from django.urls import re_path as url from learning_logs import views app_name = 'learning_log' urlpatterns = [ # Home Page url(r'^$', views.index, name='index'), # Show all topics. url(r'^$', views.topics, name='topics'), ] File views.py from django.shortcuts import render from learning_logs.models import Topic def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topic': topics} return render(request, 'learning_logs/topics.html', context) -
Nested Serializer for Foreign Keys
I have two models - Users and UserAccessLogs: class Users(AbstractUser): email = models.EmailField() name = models.Charfield() etc. class UserAccessLogs(AbstractUser): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) anotherField = models.Charfield() etc. with serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' def validate_email(self, value): # validations here def update(self, instance, validated_data): instance.email = validated_data['email'] etc. instance.save() return instance class UserAccessLogsSerializer(serializers.ModelSerializer): class Meta: model = UserAccessLogs fields ='__all__' In my views function I would like to retrieve the actual user class when fetching UserAccessLogs i.e. I would like: UserAccessLogs = { user : { email: myEmail, name: myName, etc. } } instead of UserAccessLogs = { user : 1 } in my views: access_logs = UserAccessLogs.objects.all() serializer = UserAccessLogsSerializer(access_logs, many = True) return Response(serializer.data, status.HTTP_200_OK) I tried adding user = UserSerializer() to UserAccessLogsSerializer class. It works, but then when I try and save a new instance of the UserAccessLogs I get errors related to User model from the validators. If I set read_only = True then it leaves user = null in the database. The below works in my views class but it doesn't seem efficient and needs to be repeated every time I want to get full UserAccessLogs. for data in … -
django to change the value of varible in template based on the number
there is a model books where i want to fetch all the objects and display it to user using django templates books=books.objects.all() and with django template tag im able to fetch the values in the model and display them but is there any way where django can change the variable values based on the number for example this part : {% for b in books %} <tr> <td>{{b.books_id}}</td> </tr> {% endfor %} this will display all the id's but is there any way to override this in django Lets say for instance ,if the b.books_id for any object is 1 then it should display something like "completed" if its 2 then it should display something like "no" is there any possibility to do that ?? using if or for loops in django template tags or through views -
Vertically centering text in a bootstrap card that is being used as a button
As the title says, im trying to vertically align text inside a bootstrap card. I can center it horizontally just fine, just not vertically. I've tried different ways. I would use a button but you can't store links in them I guess. Here is some code <div class="col-sm-4"> <a href="{% url 'manufacturing:view_sections' %}" class="btn btn-primary lift lift-sm h-100 w-100 text-center" style="width: 100vw;" role="button" aria-disabled="true"><h1 class="text-light"><strong>Primary link</strong></h1></a> </div> Here is what it looks like right now The whole card is being used as a button which when pressed it's sent to a different page. -
Is separating django frontend and backend with API viable?
I'm used to Django and already developed website with a whole Django or with Django API + React. For a side project, I'm thinking about creating a Django project with 2 apps: Django API 2) Django Front. I absolutely want to decouple front/back to be able to reuse the API in the future, and I like the view system from Django. Is my idea making sense? -
How i can make the number of page start display the number of page from the second page using wkhtml2pdf
on a django application, using the library wkhtml2pdf to generate a pdf , How i can make the number of page start display the number of page from the second page(2/ total number of pages). this is my parametres in settings.py: WKHTMLTOPDF_CMD = '/usr/local/bin/wkhtmltopdf' WKHTMLTOPDF_CMD_OPTIONS = { 'quiet': True, 'disable-smart-shrinking':True, 'enable-local-file-access':True, 'page-size': 'A4', 'margin-right': '0', 'margin-top': '15', 'margin-bottom': '10', 'margin-left': '3', 'encoding': "UTF-8", 'no-outline': None, "zoom":1, 'javascript-delay':1000, 'footer-center' :'[page]/[topage]', "no-stop-slow-scripts":True, } if is it possible how i can do that ? THANKS IN ADVANCE. -
How to use django-allauth username validation methods in a user update form
I'm using django-allauth system to register users and log them in. My app should allow users to change their usernames if needed. If I use a custom view or form to change a username, no allauth validation happens whatsoever (because default views and forms are not triggered). Thus users can easily set whatever username they wish, ignoring all restrictions specified in settings (like "preserve casing" or "minimum length restriction"). Is there any way to use default validations built in allauth outside signup/login forms? Right now I have to manually create a custom form and use its cleaning methods for validation, which seems to be repetitive and error-prone: def clean_username(self): username = self.cleaned_data.get('username') if username: username = username.lower() if len(username) < settings.ACCOUNT_USERNAME_MIN_LENGTH: raise ValidationError(_("Error text")) if username in settings.ACCOUNT_USERNAME_BLACKLIST: raise ValidationError(_("Error text")) # I need something that works like the code below and validates a username from allauth.account.adapter import DefaultAccountAdapter DefaultAccountAdapter.clean_username(username) return username -
In Django, whitenoise does not show static files
This is my first time using whitenoise. While DEBUG=FALSE, I can't see the images even after doing python manage.py collectstatic. All the static files are transferred to the directory specified in the STATIC_ROOT directory after collectstatic but it shows a Not Found error in the website. My settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = False INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'phonenumber_field', 'ramrobazar.account.apps.AccountConfig', 'ramrobazar.dashboard.apps.DashboardConfig', 'ramrobazar.inventory.apps.InventoryConfig', 'ramrobazar.drf.apps.DrfConfig', 'ramrobazar.demo.apps.DemoConfig', 'mptt', # 'django_elasticsearch_dsl', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt.token_blacklist', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = 'images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') My root urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('ramrobazar.drf.urls')), path('api-auth/', include('rest_framework.urls')), path('demo/', include('ramrobazar.demo.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) When I run 'collectstatic', all the static files are transferred to BASE_DIR/'staticfiles' as that is the path specified in STATIC_ROOT in settings.py. But when I run python manage.py runserver --nostatic and try to access the images in the website, it shows Not Found The requested resource was not … -
how can i create unit tests a view that returns data in json in django
I was wondering how I can create unit tests for a view like this. I have several of these in my project. def json_list_user(request): data = list(Us.objects.values()) return JsonResponse(data, safe=False) -
Django: Handle migrations created in site-packages for a custom Group field
I require a description field added to the django.contrib.auth.models.Group, so I used this solution (if there is a better way please let me know): from django.contrib.auth.models import Group Group.add_to_class('description', models.TextField(max_length=250, default="")) Unfortunately this creates a migration in: site-packages/django/contrib/auth/migrations/0013_group_description.py This is the migration: class Migration(migrations.Migration): dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.AddField( model_name='group', name='description', field=models.TextField(default='', max_length=250), ), ] This can't be checked into source code since it's in the python site-packages location. I managed to find the MIGRATION_MODULES setting, but unfortunately I don't wish to move all of the auth app's migration to a new dir (django comes with 12 migrations already for auth, and may ship more in the future. No idea how to solve this problem. It really makes deployment a nightmare. -
ModuleNotFoundError when starting celery in Django project
I have a Django project structure like this (not showing all the files/folders): myproj/ ├── __init__.py ├── config/ │ ├── __init__.py <-- imports `celery_app` as per docs │ ├── settings/ │ │ ├── __init__.py │ │ └── base.py │ ├── celery.py <-- defines `app = Celery("myproj")` │ └── wsgi.py ├── myapp1/ └── myapp2/ I have a docker-compose.yml that sets up web and worker services, and the worker service is something like: worker: build: context: "." target: "app" command: celery -A config worker -l info entrypoint: [] But whatever I try for the -A when starting celery I get ModuleNotFound. I've tried config, myproj.config and myproj. I've tried adding --workdir=/path/to/myproj, but no joy. -
difficulties in python and django integration
Traceback (most recent call last): File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mypackage' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lanje\PycharmProjects\newenv\connectivitty\manage.py", line 22, in <module> main() File "C:\Users\lanje\PycharmProjects\newenv\connectivitty\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\apps\config.py", line 304, in import_models self.models_module … -
using request.user shows the data that user is created in a application How can i show those data to others user's
I created q and a platform for university students and successfully implemented like functionality in it, and now i want to shows the number of like in the user profile, I also successfully added the number of likes to every user profile, but the problem was only the user that get likes from the answer model can see the number of likes in his profile, How can i allowed other's user's to see the number of likes in his profile, when someone likes his answer in a application, i knew using request.user shows only the content that user own in the application, but does'nt how to shows those likes to other. user profile template: <br> <br> <div class="container"> <div class="row justify-content-center"> <div class="col"> <div class="text-center"> <span class="badge bg-secondary">{{number_of_likes}}</span> <br> <br> <a href="" class="btn btn-primary"> Number Of Votes: </a> <br> </div> </div> </div> </div> my views: def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) number_of_likes = Like.objects.filter(post__user=request.user).count() context = { 'profile':profile, 'number_of_likes':number_of_likes } return render(request, 'public_profile.html', context) def like_answer(request, pk): answer = get_object_or_404(Answer, pk=pk) Like.objects.get_or_create(post=answer, user=request.user) return redirect('view-Question', answer.post.slug) my models: class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return … -
Why am I getting this error when using collectstatic?
settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'StaticFiles') ] STATIC_ROOT = os.path.join(BASE_DIR, 'Assets/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'Assets/res') ... When I run py manage.py collectstatic. I get the following message in the terminal:- You have requested to collect staticfiles files at the destination location as specified in your settings: C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite\staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: no CommandError: Collecting staticfiles files cancelled. (debsoc) C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite>py manage.py collectstatic You have requested to collect staticfiles files at the destination location as specified in your settings: C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite\staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: The message in the terminal just doesn't matches with my settings.py configuration of static files. What's the fix for it? -
Django Viewset ADD header to requests
I have two APIs that talk to each other. One API is on DRF, where it needs to take a one-time generated token and pass it with every request to the second API. I can find ways to add headers to the response, but I don't see anyway with a Viewset to pass a token into the header of ALL my requests. I can only find default_response_headers but default_request_headers doesn't exist. I'm also only finding how to respond with a token and take in a request with a token. To clarify, I do not need to get a request header, I need to add a request header with every request on my Django project. Django REST API ---- request w/ token ----> other system -
Python requests makes a lot of post requests, what should I do?
The project is written in Django. There is a function in views.py that should make a POST request to the API of one site. But for some reason the script does not work correctly, the update is very slow, and a ConnectionError is thrown. But the POST request is sent several times, and eventually creates several records in the database on the site. There don't seem to be any cycles. What's wrong? views.py: @login_required(login_url='login-main') def send_program_to_orchard(request, orchard_pk, pk, user_pk): services.send_program_to_orchard(orchard_pk, pk) return redirect(request.path) services.py: def make_json(program_id): program = Program.objects.get(id=program_id) program_substances = ProgramSubstance.objects.filter(program=program) response = { 'program_number': program.number, 'program_substances': [] } for each in program_substances: response['program_substances'].append({'date': each.date.isoformat(), 'substance': each.substance, 'dose': float(each.dose), 'measurement': each.measurement, 'comment': each.comment}) return json.dumps(response) def send_program_to_orchard(orchard_pk, program_pk): orchard = Orchard.objects.get(id=orchard_pk) headers = {'Authorization': f'Token {orchard.API_token}'} data = {'data': make_json(program_pk)} requests.post(orchard.program_API, headers=headers, data=data) -
logger.info() is not showing message in log file in Django project
I am learning django logging . log files are generating but I am not showing the required message i want to show in log file. here is my code the code in views.py file: ``from asyncio.log import logger from django.shortcuts import render from django.http import HttpResponse Create your views here. import logging, traceback logger = logging.getLogger('django') def home(request): logger.info('Some Message') return render(request, 'home.html')`` the code in setting is here: `` import os LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'INFO', 'class':'logging.FileHandler', 'filename':'./logs/debug3.log', 'formatter':'simple' } }, 'formatters':{ 'simple':{ 'format':'{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style':'{', } } } `` -
Postman works in form data but not in raw or on my server for that matter
So the first piece of code is the backend end point and second is the front end. It does not send the token to an email address on the server or using Postman raw data. But it does send a token using form-data. Any ideas I'm new to this. thanks class RegisterView(View): def post(self, request, *args, **kwargs): data = request.POST.get('email') check_if_email_exists = [] for email in Registration.objects.all().values_list('email', flat=True): check_if_email_exists.append(email) if data in check_if_email_exists: return JsonResponse('Email already provided', safe=False, status=200) else: new_user = Registration.objects.create(email=data) new_user.save() content = {'code': new_user.code} send_mail( "Thanks for Registering", f'Here is your signup Token:{content}', 'djangod192@gmail.com', [data], fail_silently=False, ) return JsonResponse(content, status=201) const SignUpStep1 = () => { const navigate = useNavigate(); const [email,setEmail] = useState(""); const dispatch = useDispatch(); const url = "https://motion.propulsion-learn.ch/app/api/auth/registration/"; const updateEmail = (event) => { setEmail(event.target.value); } const sendVerificationCode = (event) => { event.preventDefault(); if (email.length > 0) { const data = { email: email }; const fetchConfig = { method: 'POST', headers: new Headers({ "Content-Type": "application/json", }), body: JSON.stringify(data), }; fetch(url,fetchConfig) .then((response) => { return response.json(); }) const action = { type:"setEmail", payload:email }; dispatch(action) navigate("/SignUpStep2") }else{ alert("please enter email address"); } } -
How to save mapped values based on Foreign key (amount can vary)
I am programming a product listing tool and I need to map product attributes from my own products to for example Amazon's product attributes. Which attributes are required is defined through the product category. So I have my own Article which is mapped to the given Amazon product category and based on the category i need to create depending fields (choosable set of fields). Have a look add my models: from django.db import models from Article.models import Article class AmazonCategory(models.Model): category = models.CharField(max_length=255,unique=True) attribute = models.ManyToManyField(to='AmazonAttribute',through='AmazonCategoryToAmazonAttribute') class AmazonAttribute(models.Model): attribute = models.CharField(max_length=255) class AmazonAttributeValue(models.Model): attribute = models.ForeignKey(AmazonAttribute,on_delete=models.CASCADE) value = models.CharField(max_length=255) class AmazonCategoryToAmazonAttribute(models.Model): category = models.ForeignKey(AmazonCategory,on_delete=models.CASCADE) attribute = models.ForeignKey(AmazonAttribute,on_delete=models.CASCADE) required = models.BooleanField() class AmazonArticle(models.Model): article = models.ForeignKey(Article,on_delete=models.CASCADE) category = models.ForeignKey(AmazonCategory,on_delete=models.CASCADE) I will give a detailed example. I have a Product on my personal system called "Brush" and it is in the category "Art" which I have personally assigned. Now I created the categories and values for categories tables for Amazon (they are given AmazonCategory) already and I can map my article with the Amazon category "Toys | Toys and Babys | Toy". I have also stored the information in my database that the category "Toys | Toys and Babys | Toy" require … -
Datatables| Django, sorting, paging and searching with DRF
I have a Datatable that's working perfectly, and I wanted Server-side process to be true and not client-side. But when I enable server-side the sorting, paging and search became faulty. TestCase: https://codepen.io/TheNerdy97/pen/gOvNeeo?html-preprocessor=pug I'm using this module https://github.com/izimobil/django-rest-framework-datatables For seamless integration between Django REST framework and Datatables. I did as the doc said but it still won't work as expected. models.py from unittest.util import _MAX_LENGTH from django.db import models #from django.utils.translation import gettext as __ # Create your models here. class Fresh(models.Model): code = models.CharField(("code"), max_length=255) orbs = models.IntegerField(("orbs")) orbs_display = models.CharField(('orbs_display'), max_length=255) price = models.IntegerField(("price")) price_display = models.CharField(('price_display'), max_length=255) images = models.CharField(("images"), max_length=10000000) date = models.CharField(("date"), max_length=255) class Meta: ordering = ['code', 'orbs', 'price'] def __str__(self): return self.code views.py from django.shortcuts import render from accounts.models import Fresh, Orbs from rest_framework import viewsets from accounts.serializers import FreshSerializer from django.core import serializers # Create your views here. def index (request): return render(request, 'index.html') class FreshViewSet(viewsets.ModelViewSet): queryset = Fresh.objects.all().order_by('price') serializer_class = FreshSerializer urls.py import accounts from . import views from django.urls import path, include, re_path from rest_framework import routers from main import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'fresh', views.FreshViewSet) router.register(r'orbs', views.OrbsViewSet) urlpatterns = [ path('', views.index, name='index'), path('fresh', views.fresh, name='fresh'), … -
django-picklefield changes structure after upgrade
I'm migrating a Django app from 1.11.16 to 4.0.5 and django-picklefield will be migrated also from 2.0 to 3.1 . A django object has the following line: from picklefield.fields import PickledObjectField class A(models.Model): ... log_list = PickledObjectField(default=list) . Using the old code (1.11.16) and the new code (4.0.5) results a totally different result for the query: #old Obj.objects.get(id=4737).log_list [{u'date': datetime.datetime(2022, 6, 27, 12, 54, 50, 746392), u'message': u'Fetching trademark search started', u'typ': u'info'}, {u'date': datetime.datetime(2022, 6, 27, 12, 54, 53, 423384), u'message': u'Fetching trademark search finished', u'typ': u'info'}] #type == list #new Obj.objects.get(id=4737).log_list gAJdcQEofXECKFgEAAAAZGF0ZXEDY2RhdGV0aW1lCmRhdGV0aW1.... #so it results exactly what is stored in the db. #type == str With picklefield version 3.1 is there anything else I need to do / change to have the behaviour than with version == 2.0 ? What should I do with the new setup to get the list instead of the str? -
Page not found (404) Django after deleting object
After i delete an object of my table, with a delete button, I get the an 404 Page not found error. Here is my code: views.py: def deleteAction(request, i): y = get_object_or_404(Literatur, pk=i) y.delete() return HttpResponseRedirect(reverse('literatur:index')) urls.py urlpatterns=[ path('deleteAction/<int:i>/', views.deleteAction, name="deleteAction"), ] models.py class Literatur(models.Model): name = models.CharField(max_length=100) jahr = models.IntegerField() autor = models.CharField(max_length=100) auflage = models.IntegerField(default=1) verlag = models.CharField(max_length=100) ort = models.CharField(max_length=100) isbn = models.IntegerField() def __str__(self): return f"{self.name} {self.jahr} {self.autor} {self.auflage} {self.verlag} {self.ort} {self.isbn}"