Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save multiple model object instances using one single form in django?
I have the three following models: class AnswerItem(models.Model): item_name = models.CharField(max_length=320) item_number = models.PositiveIntegerField() class AnswerMenu(models.Model): menu_name = models.CharField(max_length=320) answer_item = models.ForeignKey(AnswerItem) class QuestionAnswer(models.Model): answer = models.ForeignKey(AnswerMenu) answer_item = models.ForeignKey(AnswerItem) Answer menus are currently displayed on a single page using a list view, with the following template: {% for answer_menu in answer_menus %} <div>{{ answer_menu.menu_name }}</div> {% for answer_item in answer_menu %} <p> <label> <input id="{{ answer_item.pk }}" name="{{ answer_menu.pk }}" type="radio"> </label> </p> Now, the trouble I have is I would like to create a single form to save all selected answers using the radio buttons on the page. Since there are multiple answer menus shown on the page, posting through this form would create several QuestionAnswer items. How would you approach this? -
Django user model override
I'm not advanced in Django and would like to know how and if it's possible to do it. I need to override Django's user model, and change the fields "username" to "sr_usuario" and "password" to "sr_password", but I would like to continue using all Django's default authentication scheme and permissions. I want not only to change the description in the database or a label, I want to change the name of the field in the model, for when for example I needed to make a query, I would use User.objects.filter(sr_usuario="user_name") and everything would work usually. It's possible? I couldn't find anything in the documentation or on forums I've searched. Thank you very much in advance! -
Hello! Help to make dependent <select> from a database
Help to make dependent from a database. enter image description here I don't know how to configure this dependency between database tables. if possible, tell me how, or show an example of how to implement it. the tables in the database are configured one-to-many, and so many dependencies need to be made. models.py class Car_mark(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Марка' verbose_name_plural = 'Марки' class Car_model(models.Model): model = models.ForeignKey(Car_mark, on_delete = models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Модель' verbose_name_plural = 'Модели' class Car_engin_type(models.Model): engin = models.ForeignKey(Car_model, on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Двигатель' verbose_name_plural = 'Двигатели' views.py class MarkList(ListView): model = Car_mark ordering = 'name' template_name = 'index.html' context_object_name = 'marka' class ModelList(ListView): model = Car_model ordering = 'name' template_name = 'index.html' context_object_name = 'model' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', MarkList.as_view()), path('', ModelList.as_view()), index.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <link rel="stylesheet" href="{% static 'Zayavky/css/stail.css' %}"> </head> <body> <h1>Выберите автомобиль:</h1> <label> <select class="select-css"> {% for el in marka %} <option>{{ el }}</option> {% endfor %} </select> </label><br> <label> <select class="select-css"> {% for el2 in model %} <option>{{ … -
Django - how to export and import user data for database migration?
I am moving my website to another cloud server for delpoying, so I have to export all the user information (account name, password, accounts.profile from the existing database, then import to the new website hosted by the new server. I have tried to export user data using default: python manage.py dumpdata > users.json the users.json looks like: [{"model": "accounts.profile", "pk": 1, "fields": {"user": 2, "telephone": "0755-25187181", "company_name": "watchtech"}}, {"model": "accounts.profile", "pk": 2, "fields": {"user": 3, "telephone": "18696511023", "company_name": "King's Machinery"}},....}}] I noticed there is no password information exported. when I use "python manage.py loaddata user.json", how to ensure it also loads the password of users, so that users can login the new website? -
FOREIGN KEY constraint failed Django Models
I'm creating a small-ish django application using AllAuth for the authetncation, which I have customised myself to include some additional fields. Part of the sites functionality requires me to refrence the logged in user through a Foreign Key multiple times and I'm approaching this through the custom model I created, called UserProfile; (I tried Django's User model & this also gave me errors) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') phone_number = models.CharField(max_length=30, null=False) postcode = models.CharField(max_length=500, null=True, blank=True) town_or_city = models.CharField(max_length=40, null=True, blank=True) street_address1 = models.CharField(max_length=80, null=True, blank=True) street_address2 = models.CharField(max_length=80, null=True, blank=True) county = models.CharField(max_length=80, null=True) I'm referencing the above model in the activity table: class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.CharField(max_length=32, null=False, editable=False) host = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() duration = models.DurationField(blank=True, null=True) location = models.CharField(max_length=40, null=False, blank=False) description = models.CharField(max_length=140, null=False, blank=False) available = models.BooleanField(default=True) Everything works smoothly, as I can use this to create one activity per user, however I want to make this a Many to One field, which required me to update from settings.AUTH_USER_MODEL to the Foreign Key. Unfortunately, I'm getting the following error: FOREIGN KEY constraint failed when … -
How to get information from option field in django?
I have django application with authentication and I have dropdown menu inside. Before I did it like: <select name="country" id="id_category" data="{{ data.country }}"> {% for each in living_countries_list %} <option name="country" value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> % endfor %} </select> And now I changed it to: <input list="brow" placeholder="Search for your country..." class="input_country"> <datalist id="brow"> {% for each in living_countries_list %} <option name="country" value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </datalist> <p class="country_text">Please select your living country</p> In my views.py file I passed context like: country = request.POST.get('country') professors = models.Professor.objects.all() living_countries_list = LIVING_COUNTRIES print(country) In models.py I have options like: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra'), ('ANGOLA', 'Angola')] class Professor(models.Model): country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default=FRESHMAN, blank=True, null=True) So I have few options which are displayed either way but in changed I can type in input and that's what I want to be able to do. If you want me to post anything else let me know in comments -
How to copy a "default" company and all related data to a new user? [closed]
Every time a user is created I must create a copy of a "default" company already existing in the database, to be assigned to this new user. The problem is that the company table is related to other tables, for example invoices, bills, etc. The idea would also be to copy these. Since a complete copy of this company should be made, so that the new user can work with it without affecting the original one that is being copied. One thing I had thought of was to make a script that does all this process, creating the tables with these "default" values but I think there must be a better approach to this problem out there. -
Django production pages where there images-media is very slow
I just deployed my small django app on a ubuntu server using Apache. The site work fine but the page where it show images from database is extremely slow and loading forever. (I can see the picture/image though) here is how I display the image {% for photo in photos %} <div class="col-sm-12 col-md-6 col-lg-6"> <img class="card-img-top" src="{{photo.image.url}}" alt="Card image cap"> {% endfor %} My images folder is placed like this mysite --> main --> static --> images --> settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIR = [ BASE_DIR / 'static', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'main/static/images') STATIC_ROOT = '/var/www/mysite/static/' I am not sure what causing this page to be slow. -
How to deploy Python Celery worker on EC2 (current error 111: Connection refused)?
Technologies: Python, Django, AWS, RabbitMQ on AWS, Celery I currently have my company's website deployed on an EC2 instance. Everything works well, my current tasks is to run a Celery worker but every time I attempt to do so I get the 111:Connection refused error. Celery runs, RabbitMQ is running but my assumption is that I can possibly not have the correct setup since I have everything within their correct VPCs and security groups. FILES: settings.py CELERY_BROKER_URL = 'amqps://<username>:<password>@<awspath>.mq.us-west-2.amazonaws.com:5671' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_TASK_DEFAULT_QUEUE = env("CELERY_TASK_DEFAULT_QUEUE", default="default") CELERY_BROKER_TRANSPORT_OPTIONS = { "region": env("AWS_REGION", default="us-west-2"), } CELERY_RESULT_BACKEND = None procfile celery: celery -A bsw_site worker -l INFO init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) error log 2022/10/20 20:57:13 [error] 4189#4189: *35 connect() failed (111: Connection refused) while connecting to upstream, client: 10.176.11.163, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "<company_website_link>", referrer: "<company_website_link>" nginx_conf.conf user nginx; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; worker_processes auto; worker_rlimit_nofile 200000; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; fastcgi_read_timeout 7200; proxy_read_timeout 7200; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; include conf.d/*.conf; map $http_upgrade $connection_upgrade { default … -
Can I use image hyperlink from the model content to show in my poster image in django templates?
OK so this might sound a bit weird. so im using ckeditor for my content field. So I want to for example run a loop in my template in my content instance. And find "<img" and if its found I wanna check if there is a "/>" so upon finding those I wanna grab the link from that image tag and add that link to my templates poster image in this line - <img src="{% static 'app/images/movie-poster.jpg' %}" width="100px" /> So basically when a user posts if that posts body contains any image then the first image will be added as the poster. So the default poster wont show. Is it possible to do that from template? Sorry im a noob and thats just some solution I thought of and looking for some code logic here. If its posssible then how can i do that ? I have a model which is this - class List(models.Model): title = models.CharField(max_length=120) genre = models.ManyToManyField('Genre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Movie") spoiler_choices = [(False, 'No'),(True, 'Yes')] spoiler = models.BooleanField(default=False,null=True, choices = spoiler_choices) slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return f'{self.title}|{self.creator}' def … -
Respond an array of json objects in Django view
I have this table or model: longitude latitude session 12 34 1 99 42 2 99 42 1 99 42 3 99 42 1 99 42 2 I need to make a query to get all data by session. So I get all the data from the table and apply 'distinct' to get the sessions: sessions= GPSData.objects.values('session_new_id').distinct() I get: <QuerySet [{'session': 1}, {'session': 2}, 'session': 3}]> Now, for each session I need to get longitude an latitude. Afterwards I need to send an HttpResponse with the data in a JSON. So I'm trying in my view: def get_all_gps(request): data=[] for session in sessions: y=GPSData.objects.filter(session=session['session']) y = serializers.serialize("json", y) data.append(y) return HttpResponse(data, content_type='application/json') I get an error in the template because I am passing an array not a json object: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 190986 of the JSON data In general what I need is to respond with an array of JSON objects. Something like this: [[{json from session 1}],[{json from session 2}],[{json from session 3}]] Can this be done? -
Sync PostgreSQL and Django project
I had a legacy database which I uploaded to PostgreSQL and connected it with Django. Then, I changed DB with running SQL scripts directly in the PostgreSQL (I deleted few columns), then manually deleted few columns in django models.py. Since then, I cannot make any migrations, whenever I try it, Django is trying to delete the column which I manually deleted, and gives the error below. How do I sync my DB and Django project so that I can make modifications to the project? django.db.utils.ProgrammingError: column "confidence" of relation "Location" does not exist -
Can I use a form's is_valid function for DRF submitted data?
I have a form (not a ModelForm) with custom validators that's working fine. Now need to add an API for submitting the same data. Is it possible to use the form's is_valid() function to validate the data? I tried populating a new form instance using initial, but the form is never valid. Tried in the shell with a simple form and saw the same thing. # ./manage.py shell Python 3.6.10 (default, Jan 17 2021, 19:51:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django import forms >>> class DogForm(forms.Form): ... name = forms.CharField(max_length=6) ... age = forms.IntegerField() ... >>> df = DogForm(initial={'name':'Rex','age':3}) >>> df.is_valid() False I'm missing a step somewhere... -
HTTP 405 Method Not Allowed ( rest framework )
i learn some django code with rest framework and i get a problem i try from model but i'm getting an error : HTTP 405 Method Not Allowed "GET /create-room HTTP/1.1" 405 12243 someone help me . my code : view.py from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response # Create your views here. class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) -
Security for Django api method accessed by frontend and backend
I have few api methods, they get accessed by a frontend application js code, since user is logged in, all requests will be passing a cookie. Same api also needs to be accessed via backend as well. In this case what should be the protection method ? -
Setting up a Postgres DB for Django with Fly.io
I'm a novice trying to spin up my first webapp with a combination of Fly.io, Django, and a postgres DB but I'm having some trouble and can't find an answer in walkthroughs or Q&A. I've set up a simple "Hello world" Django app (models.py is empty so far) and I'm trying to get all the components up and running before I build it out any further. I've successfully deployed my app on Fly.io with no errors I've created a postgres cluster on Fly.io using the instructions here: https://fly.io/docs/postgres/ I've attached the cluster to my app, which generates a DB and sets an environment variable with the appropriate details (username, password, port, host, dbname) I've updated my settings.py file: DATABASES = {} DATABASES["default"] = dj_database_url.config(conn_max_age=600, ssl_require=True) I've added to my fly.toml: [[services]] internal_port = 5432 # Postgres instance protocol = "tcp" # Open port 10000 for plaintext connections. [[services.ports]] handlers = [] port = 10000 I've confirmed I can get into the psql shell with flyctl postgres connect -a MYAPP-pg But unfortunately when I run python manage.py migrate to check that everything is working, I get the following error: File "<my_path>\venv\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "<my_path>\venv\lib\site-packages\django\utils\asyncio.py", line 26, in … -
How to make case insensetive searcn in Django with Postgres
I have a project with Django, Django REST Framework and PostgreSQL. And my goal to make a search with certain conditions: logical operators (AND, OR, NOT) case insensitive operator like * To search by prefixes. som* -> search for some, somali and so on My first attempt was to use Postgres full search with this type search_type='websearch' It's all good but don't have operator * So I switched to raw type search and my class for search looks like it now class DataSearch(generics.ListAPIView): serializer_class = DataSerializer def get_queryset(self): q = self.request.query_params.get('query') if q: vector = SearchVector('research', 'data', 'research__name') query = SearchQuery(q, search_type='raw') queryset = Data.objects.annotate(search=vector).filter(search=query) else: queryset = Data.objects.none() return queryset Logical operator works, search by prefixes works with :* but I don't know how to make it case insensitive. Is it possible to make this type of search case insensitive? Or maybe there are another option for it? -
comprehension list returns empty list with extracted text
I am using a Django application. And I have a function that returns some extracted text. So this is the method: def total_fruit_cost(self, file_name): self.extract_text_from_image(file_name) fruit_cost_found = [] single_fruit = [fruit for fruit in self.fruit_word] for fruit in single_fruit: if len(re.findall(self.regex_fruit_cost(fruit), file_name)) > 0: fruit_cost_found.append(re.findall( self.regex_fruit_cost(fruit), file_name)) return [item for sublist in fruit_cost_found for item in sublist] and the methhod self.extract_text_from_image(file_name) looks like this: def extract_text_from_image(self, filename): self.text_factuur_verdi = [] pdf_file = wi(filename=filename, resolution=300) all_images = pdf_file.convert('jpeg') for image in all_images.sequence: image = wi(image=image) image = image.make_blob('jpeg') image = Image.open(io.BytesIO(image)) text = pytesseract.image_to_string(image, lang='eng') self.text_factuur_verdi.append(text) return self.text_factuur_verdi the fruit_words: self.fruit_word = ['Appels', 'Ananas', 'Peen Waspeen', 'Tomaten Cherry', 'Sinaasappels', 'Watermeloenen', 'Rettich', 'Peren', 'Peen', 'Mandarijnen', 'Meloenen', 'Grapefruit', 'Rettich'] and the regex: regex_fruit_cost: def regex_fruit_cost(self, substr): return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n" and then I use it in the view like this: if uploadfile.image.path.endswith('.pdf'): content = extract_instance.total_fruit_cost( uploadfile.image.path) print(content) But the result is an empty list:[]. the result has to be: 3.488,16 137,50 500,00 1.000,00 2.000,00 1.000,00 381,25 123,20 2.772,00 46,20 577,50 69,30 I also calling three times: file_name in the method: total_fruit_cost That could be improved. But I am not sure how to do that. My question: So how can I improve … -
How to get required response from DRF
I have database which consists of configuration of application. Application can have various configuration keys and basically I don't have information about how much keys I have and name of keys are not known too. I need to have response as {key: value, }. But I have response {key_field: key, value_field: value}. What should I do basically in this case? Does using MongoDB instead of PostgreSQL or SQlite help me? Or any other ideas? Model looks like: class Service(models.Model): name = models.TextField() version = models.IntegerField() class ServiceKey(models.Model): service = models.ForeignKey( Service, on_delete=models.CASCADE ) service_key = models.TextField() service_value = models.TextField() views: @api_view(['GET', ]) def hello(request): name = request.query_params.get('service') try: service = Service.objects.get(name=name) service_key_instance = ServiceKey.objects.filter(service=service) serializer = KeySerializer(instance=service_key_instance, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) except: Response(data='record not found', status=status.HTTP_400_BAD_REQUEST) -
How to add new elements into my email template (django)
i'm doing a form that will send an e-mail after completing the fields. The email must contains all the information wrote in the form, but in the forms i did a button to add more items, and this will appeart two new fields of "select component" and "quantity". How can i get the data from these fields that will be created after clicking into "add component" and put into my email? my views.py def home(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): type = form.cleaned_data['type'] serialNumber = form.cleaned_data['serialNumber'] itemNumber = form.cleaned_data['itemNumber'] date = form.cleaned_data['date'] phase = form.cleaned_data['phase'] capacity = form.cleaned_data['capacity'] centerQuantity = form.cleaned_data['centerQuantity'] componentQuantity = form.cleaned_data['componentQuantity'] componentSelection = form.cleaned_data['componentSelection'] commentary = form.cleaned_data['commentary'] html = render_to_string('emails/email.html', { 'type': type, 'serialNumber': serialNumber, 'item': itemNumber, 'date': date, 'phase': phase, 'capacity': capacity, 'centerQuantity': centerQuantity, 'componentQuantity': componentQuantity, 'componentSelection': componentSelection, 'commentary': commentary, } ) send_mail('ATENÇÃO', 'Message', 'no-reply@xxx.net', ['test@xxx.net'], html_message=html, fail_silently=False) return redirect('home') else: form = Form() return render(request, 'template.html', { 'form': form }) My html file: <body> <div> <h2> Engine Information</h2> <table> <form action="." method="POST" hx-post="."> {% csrf_token %} <tbody> <tr> <th>Type</th> <td>{{form.type}}</td> </tr> <tr> <th>Serial Number</th> <td>{{form.serialNumber}}</td> <th>or Material Number</th> <td>{{form.itemNumber}}</td> </tr> <tr> <th>Manufactoring Date</th> <td>{{form.date}}</td> <th>Phase</th> <td>{{form.phase}}</td> <th>Capacity</th> <td>{{form.capacity}}</td> <th>Center Quantity</th> <td>{{form.centerQuantity}}</td> … -
Chart.js display no data message using django
I have a pie chart that I want to display no data message when there is no data to be shown I have tried the methods here but it seems to stop displaying the chart all together even when there is data. currently if there is no data it shows NAN% the data it based off the user data from a model. I have also tried to just use the if statement for the part displaying the Nan% but the if statement also just seems to cause it to stop rendering the chart. JS: <script> {% block jquery %} var endpoint = '/api/chart1' var defaultData = [] var labels = [] $.ajax({ methode: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart1() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart1(){ var ctx = document.getElementById('myChart').getContext('2d'); Chart.register(ChartDataLabels); var myChart = new Chart(ctx, { type: 'pie', plugins: [ChartDataLabels], data: { labels: labels, datasets: [{ label: '', data: defaultData, backgroundColor: [ 'rgba(255, 51, 51, 0.2)', 'rgba(255, 255, 0, 0.2)', 'rgba(0, 204, 204, 0.2)', ], borderColor: [ 'rgba(255, 51, 51, 1)', 'rgba(204, 204, 0, 1)', 'rgba(0, 204, 204, 1)', ], borderWidth: 1 }] }, options: { plugins: { tooltip: { enabled: … -
A multipart/form-data with nested serializers and files, DRF raises "The submitted data was not a file. Check the encoding type on the form."
I have this issue with using a multipart/form-data, nested serializers and the upload of images/files. I think my models and serializers are working well, but in some moment during the parse of the form data is when it fails. I've just extended the BaseParser to parse strings to lists and dicts. parsers.py class MultiPartJSONParser(BaseParser): media_type = 'multipart/form-data' def parse(self, stream, media_type=None, parser_context=None): parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META.copy() meta['CONTENT_TYPE'] = media_type upload_handlers = request.upload_handlers try: parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding) data, files = parser.parse() data = data.dict() for key in data: if data[key]: try: data[key] = json.loads(data[key]) except ValueError as e: pass return DataAndFiles(data, files) except MultiPartParserError as exc: raise ParseError('Multipart form parse error - %s' % exc) Why I do this? Because my intention is to pass a form-data like this: key Value user 6 address {"street": "Main St.", "number": "1"} first_name Alice last_name Bob image [file] ...\image_directory language [1,2] If I don't POST or PATCH with the image it works well, but when I send an image: The submitted data was not a file. Check the encoding type on the form. The "crazy" thing about this it is … -
NOT NULL constraint failed: cms_viewcount.session
I am trying to get users ip address for a blog project view counts, and when the user isn't logged in a get this error integrityError at /article/another-post-to-test-things-out/ NOT NULL constraint failed: cms_viewcount.session Here is my views.py # regular blog details def blog_detail(request, slug): template_name = 'cms/single.html' blog = Blog.objects.get(slug=slug) msg = False form = CommentForm() ip=request.META['REMOTE_ADDR'] if not ViewCount.objects.filter(blogview=blog, session=request.session.session_key): view=ViewCount(blogview=blog, ip_address=ip, session=request.session.session_key) view.save() blog_views=ViewCount.objects.filter(blogview=blog).count() if request.user.is_authenticated: user = request.user if blog.likes.filter(id=user.id).exists(): msg = True context = {'blog': blog, 'msg':msg, 'form':form, "view_count":blog_views,} try: if request.method == 'POST': form = CommentForm(request.POST) comment = form.save(commit=False) comment.blog = blog comment.owner = request.user comment.save() messages.success(request, 'Your review was successfully submitted!') return redirect('blog-detail', slug=blog.slug) if not request.user or not request.user.is_authenticated: return render(request, template_name, context) else: return render(request, template_name, context) except: return render(request, "cms/login-prompt.html", context) Here is the error on my browser also view.save() … Local vars Variable Value blog <Blog: Another Post to test things out> form <CommentForm bound=False, valid=Unknown, fields=(body)> msg False request <WSGIRequest: GET '/article/another-post-to-test-things-out/'> slug 'another-post-to-test-things-out' template_name 'cms/single.html' view <ViewCount:> PLease how can I fix this error , note everthing works fine when the user is logged in models.py #views count models class ViewCount(models.Model): blogview=models.ForeignKey(Blog, related_name="view_count", on_delete=models.CASCADE) ip_address=models.CharField(max_length=50) session=models.CharField(max_length=50) def __str__(self): … -
Mantain wagtail category across pages
I've a pagination system on my Wagtail website that works just fine with normal posts. However, I wanted to make pagination of post categories and I wasn't able to do it, it loads the "Posts" URL losing the category. You can see an example here when clicking page 2 https://wizardeo.es/publicaciones/?category=guias This is the code of my template {% if posts.paginator.num_pages > 1 %} {% if not 1 == posts.number and posts.number >= 4 %} {% if posts.paginator.num_pages > 5 %} <a href="?page=1">&lt;&lt;</a> {% endif %} {% endif %} {% for page_num in posts.paginator.page_range %} {% if posts.number == 1 %} {% if page_num > posts.number|add:-3 and page_num < posts.number|add:5 %} <a href="?page={{ page_num }}" class="{% if page_num == posts.number %} active {% endif %}">{{ page_num }}</a> {% endif %} {% elif posts.number == 2 %} {% if page_num > posts.number|add:-2 and page_num < posts.number|add:4 %} <a href="?page={{ page_num }}" class="{% if page_num == posts.number %} active {% endif %}">{{ page_num }}</a> {% endif %} {% elif posts.number == 3 %} {% if page_num > posts.number|add:-3 and page_num < posts.number|add:3 %} <a href="?page={{ page_num }}" class="{% if page_num == posts.number %} active {% endif %}">{{ page_num }}</a> {% endif %} {% … -
How to prevent djagno from updating certain fields?
I have a model that I use in django admin to keep track of action taken on a task. The model includes a user field to show which user added an action. The issue is when a new task update is added, django overwrite the previous user by the new user. As it can be seen bellow, I do not want to change the user (by field) whenever a new action is created. class Action(models.Model): action = models.ForeignKey(TaskAction, models.CASCADE) by = models.ForeignKey('auth.User', models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, editable=False) note = models.TextField(blank=True, null=True) def __str__(self): return str(self.action) class Meta: verbose_name = 'Task Action' verbose_name_plural = 'Task Actions' db_table = 'task_actions'