Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing an additional field through a model form without adding it to the model
I'm trying to figure out how to add a field to a model form without adding the field to the model itself. I just need to pass in this extra field to the view it returns. My django project has a page where the user uploads a text file which gets saved to the DB (the file upload form is the model form). It then returns a page where the important content from the text file is displayed. I want to add a dropdown on the same page as the file upload form that allows the user to select an option for how the content should be displayed when it returns the next page. I don't want this dropdown to be part of the model for the text file as I don't need to save it to the db. I'm having trouble figuring out how to pass this option into the view without adding it to the model itself. Upload form: <form method="POST" enctype="multipart/form-data" id="text-upload-form"> {% csrf_token %} {{ form.as_p }} <label for="display-type">Display type</label> <select id="display-type" name="display-type" form="text-upload-form"> <option value="highlighted">Highlighted display</option> <option value="dark">Dark display</option> </select> <button type="submit" class="save btn btn-default">Save</button> Views.py def parser(request): if request.method =='POST': text_upload = TextFileForm(request.POST, request.FILES) … -
Django user delete privilege role
Is possible to give roles/group to admin users to delete only the users they created? For example: admin1 created user1, user2 admin2 created user3, user4 admin1 should only have permissions to delete user1 and user2 and not have any access to user3 and user4. -
Django and jQuery: jQuery not working, but receiving no errors
I cannot figure out why my jQuery script isn't working. I've read through a bunch of stackOverflows but haven't been able to fix this issue. I have a form, and when a checkbox is checked, I want to enable a form field with the id div_id_newLockName. If the checkbox is unchecked, I want the form field to be disabled and greyed out. The checkbox has id div_id_newNameBool I have written code that I think should work, but it doesn't. I'm not receiving any errors though, which makes troubleshooting difficult. I'm hoping a second set of eyes can help. A picture of what the form looks like can be found here: In this picture, the "change name?" checkbox corresponds with div_id_newNameBool, and the "Lock Name" char field is what I want to toggle enable or disable. base.html (contains jQuery script) <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <style> <!-- unimportant css stuff --> </style> <body class="w3-content" style="max-width:1200px"> <!-- !PAGE CONTENT! --> {% block content %}{% endblock %} <!-- End page content --> </div> <script> $(document).ready(function(){ if ($("#div_id_newNameBool").is(':checked')){ $("#div_id_newLockName").prop("disabled", false); } else { $("#div_id_newLockName").prop("disabled", true); alert("DISABLED"); } }); </script> </body> </html> HTML page for form {% extends "homepg/base.html" %} {% load crispy_forms_tags … -
How to get reference to object in django-restframework APIView
I am trying to fill a chart.js chart with historical values from my database of a Team object. Currently I have a regular django view which loads the template of the team, and a specific django rest-framework APIView that returns json response for the chart's labels and data, which sits inside of the template rendered by the initial django view. I need reference to the current team to be accessible in the APIView, but not sure how to do that. urls.py: path('team/<slug:slug>/', views.team_view, name='team_view'), path('teamChart', views.TeamChartData.as_view()), views.py: def team_view(request, slug): user = request.user team = Team.objects.get(slug=slug) ... return render(request=request, template_name='team_view.html', context={'team':team, 'form':form, 'userTeam': userTeam}) class TeamChartData(APIView): # authenticate user authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self,request, format=None, *args, **kwargs): labels = ['hi'] chartLabel = "" chartdata = [1] data ={ "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, 'user':request.user.username, } return Response(data) teamChart.js var endpoint = '/teamChart'; $.ajax({ method: "GET", url: endpoint, success: function(data) { drawLineGraph(data, 'teamChart'); console.log("drawing"); }, error: function(error_data) { console.log(error_data); } }) function drawLineGraph(data, id) { .... } I've got the chart working for a user's account, but in the APIView I can reference the user from the request being made. I can't access the specific team page from that … -
Adding textarea in formset - django
I have a message form and a formset that includes questions for this message. I would like to add textareas in the form, instead of input field. - I am not sure why there are not many examples out there. The models looks like this: class Message(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) message_title = models.CharField(blank=True, null=True, max_length=255) message_introduction = models.TextField() def __str__(self): return self.message_title class Meta: db_table = 'messages' and: class Message_question(models.Model): message = models.ForeignKey(Message, related_name="message_questions", on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) message_question = models.TextField() def __str__(self): return self.message_question class Meta: db_table = 'message_questions' And the forms look like this: class MessageForm(forms.ModelForm): class Meta: model = Message fields = [ 'message_title', 'message_introduction', ] labels = { 'message_title': 'message_title', 'message_introduction': 'message_introduction', } widgets = {'created_at': forms.HiddenInput(),'updated_at': forms.HiddenInput()} class Message_questionForm(forms.ModelForm): class Meta: model = Message_question fields = ['message_question', ] widgets = { 'message_question': forms.TextInput(attrs={'class': 'formset-field', 'rows': 4}), } Is it doable and if yes, what element of the above code shoudl I change please ? -
Choose the correct option. ValidationError Django python
how to change validation from pk to name field in input forms? models class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) def __str__(self): return self.name forms class SettingDeviceAddForm(forms.ModelForm): class Meta: model = Device fields = ['name'] that is, in the form, you need to enter a name and check the name field, and I enter the name, and the check goes along the pk field. how to change the default pk field to name html form -
I have a TypeError (Object … is not JSON serializable) when I try to set a session value (Django). Why?
I have this strange TypeError raised : "Object of type Product is not JSON serializable" when I try to set a session value in a view (in basket app). The error occurs with request.session['Hello'] = 'foo'. However, this error does not occur elsewhere. For instance, in store app, in views.py, the following request.session['Hello World'] = 'Alloy' works very well. Do you know why ? Basket app / views.py (it bugs) from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) context = {'basket':basket} request.session['Hello'] = 'foo' return render(request,"store/basket_summary.html",context) store app / views.py (it works well) from django.shortcuts import get_object_or_404, render from requests.sessions import session from .models import Category, Product def home(request): print('----------// HOME PAGE //----------') request.session['Hello World'] = 'Alloy' context = {} return render(request, 'store/home.html', context) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/basket/ Django Version: 3.2 Python Version: 3.9.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'account', 'basket', 'orders', 'payment', 'contact', 'address', 'discount', 'shipping'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "C:\Users\Utilisateur\Documents\Environments\monoi_django_virtualenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Utilisateur\Documents\Environments\monoi_django_virtualenv\lib\site-packages\django\utils\deprecation.py", line … -
Django check if superuser in class-based view
I am converting my project from function-based view to class-based view. In a view function, I can check if a user is a superuser using request.user.is_superuser() function. I can check if a user is logged in by inheriting LoginRequiredMixin in a View class, I want to know if there is any similar way that can be used for checking if the user is a superuser in a View class. I want a Django app only accessible by the superusers of the site. -
Embeding videos in a a Django project?
Using Django-embed-video 1.4.0, we can easily embed YouTube videos into Django projects. However it doesn't seem to work if the video is from any source but YouTube. The embed video code is different for every website and whenever I enter a code from a site like TikTok, CNN, or Facebook, it says "URL could not be recognized." YouTube Video CNN Video Is there a way to modify the URL so that Django-embed-video recognizes the URL? Or is there another way to create a django website that can show embedded videos from a source other then youtube? models.py from django.db import models # Create your models here. from embed_video.fields import EmbedVideoField class Item(models.Model): video = EmbedVideoField() -
HTML checkbox prepended to textbox and their sizes
Here my HTML code <div class="input-group mb3"> <div class="input-group-prepend"> <div class="input-group-text"> {% if item.complete == True %} <input type="checkbox", value="clicked", name="c{{item.id}}" checked> {% else %} <input type="checkbox", value="clicked", name="c{{item.id}}"> {% endif %} </div> </div> <input type="text" value="{{item.text}}" class="form-control"> </div> I prepended checkboxes before the textboxes, yet their sizes is not same as you see. Do I have to change their height(maybe width) values in order to make them equal or do I miss something else? By the way I am using CSS(I am a newbie to HTML, do not be harsh please :D ). Could it be relevant with that or it' s sources? Thanks! -
RadioSelect field not proper shown
I put RadioSelect field to my form and in Chromium my choices are in the left side of form not like labels and other fields in center, how can I fix it? Please any sygesstions. In FF it's looks also different, it's positioned to the left side. template {% extends 'school/index.html' %} {% load crispy_forms_tags %} {% load crispy_forms_field %} {% block content %} <form method="post" align='center' autocomplete="off" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btnSubmit">submit</button> </form> {% endblock %} form.py from django import forms from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ class UserSignUpForm(forms.ModelForm): who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], required=True, widget=forms.RadioSelect(attrs={'style':'max-width: 20em; margin:auto; padding:300;', 'autocomplete':'off'}) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'first_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'last_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm password does not … -
I can't seek videos with django channels
I have a website and I could seek the videos but after I set up Django channels the videos don't seek, and I tried to solve this problem so I figured out when the server run with Starting ASGI/Channels the videos didn't do that, I have just one question Is this problem will continue with production or not? My asgi.p import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings') django.setup() application = get_asgi_application() -
How to upload geojson file in django postgresql
I would like to import a geojson file (Edge) in my postgresql database. I have a form for uploading the file. My problem is how to handle foreigns keys network, target, source and roadtype. Source and target must be Node instance. the file will be download inside the network page(pk). models.py class Edge(models.Model): param1 = models.FloatField(null=True, blank=True) param2 = models.FloatField(null=True, blank=True) param3 = models.FloatField(null=True, blank=True) speed = models.FloatField(null=True) length = models.FloatField(null=False) lanes = models.SmallIntegerField(null=True) geometry = models.LineStringField(null=True) name = models.CharField('Edge Name', max_length=200, blank=False) road_type = models.ForeignKey(RoadType, related_name='edges_road_type', on_delete=models.CASCADE) target = models.ForeignKey(Node, related_name='edges_target',on_delete=models.CASCADE) source = models.ForeignKey(Node, related_name='edges_source',on_delete=models.CASCADE) network = models.ForeignKey(RoadNetWork, related_name='edges_network', on_delete=models.CASCADE) my geojson file is like that { "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "id": 1, "name": "Out 1 - E", "lanes": 1, "length": 4.0, "speed": 50.0, "source": 1, "target": 2, "param1": 3000.0, "road_type": 2 }, I try this.It's too slow. Could you please help me def upload_edge(request, pk): template = "networks/edge.html" network = RoadNetWork.objects.get(id=pk) if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] geometry = object['geometry'] point1 = geometry['coordinates'][0] point2 = geometry['coordinates'][1] location = GEOSGeometry( LineString(geometry['coordinates'])) … -
How to change default page in paginator?
I changed default page like this (For this example I hardcored the number 3 as logic which I have in this function does not affect paginator) def test(request): paginator = Paginator(objects, 2) num = 3 page = paginator.get_page(number=num) return render(request,'personal.html', {'page':page,'paginator':paginator}) But now I can't go on other pages, it always returns page number 3. Is it possible to correct? Here is paginator {% if page.has_other_pages %} <nav> <ul class="pagination"> {% if page.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page.previous_page_number }}">&laquo; Previous</a> </li> {% else %} <li class="page-item disabled"> <span class="page-link">&laquo; Previous</span> </li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="page-item active"> <span class="page-link">{{ i }} <span class="sr-only">(current)</span> </span> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page.next_page_number }}">Next &raquo;</a> </li> {% else %} <li class="page-item disabled"> <span class="page-link">Next &raquo;</span> </li> {% endif %} </ul> </nav> {% endif %} And in another html I call it ... {% include 'paginator.html' with items=page paginator=paginator%} ... -
Display images manually that user has uploaded yet Python
How I display all the images manually that user has uploaded yet in Django show that I can create a Profile gallery -
Gunicorn / Procfile - module.wsgi not found
I'm trying to deploy a django app to heroku. My directory structure is: 'root'/ Procfile backend/ django_app/ manage.py mainapp/ settings.py wsgi.py I tried to follow the indications given on some posts here on stackoverflow but to no avail. I have a Procfile in the root directory. The latest version has: web: gunicorn backend.django_app.mainapp.wsgi --log-file - But it still gives me a module not found error: 2021-05-01T20:20:33.556737+00:00 heroku[web.1]: State changed from crashed to starting 2021-05-01T20:20:58.799412+00:00 heroku[web.1]: Starting process with command `gunicorn backend.django_app.mainapp.wsgi --log-file -` 2021-05-01T20:21:01.738041+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-05-01T20:21:01.739021+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Listening at: http://0.0.0.0:46010 (4) 2021-05-01T20:21:01.739198+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Using worker: sync 2021-05-01T20:21:01.744319+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [8] [INFO] Booting worker with pid: 8 2021-05-01T20:21:02.007630+00:00 app[web.1]: [2021-05-01 20:21:02 +0000] [8] [ERROR] Exception in worker process 2021-05-01T20:21:02.007644+00:00 app[web.1]: Traceback (most recent call last): 2021-05-01T20:21:02.007645+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-05-01T20:21:02.007645+00:00 app[web.1]: worker.init_process() 2021-05-01T20:21:02.007646+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-05-01T20:21:02.007646+00:00 app[web.1]: self.load_wsgi() 2021-05-01T20:21:02.007647+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-05-01T20:21:02.007648+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-05-01T20:21:02.007648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-05-01T20:21:02.007648+00:00 app[web.1]: self.callable = self.load() 2021-05-01T20:21:02.007649+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load … -
Why do I have a TypeError (Object ... is not JSON serializable) when trying to set a session value in a view?
I have this strange TypeError raised : "Object of type Product is not JSON serializable" when I try to set a session value in a view (in basket app). The error occurs with request.session['Hello'] = 'foo'. However, this error does not occur elsewhere. For instance, in store app, in views.py, the following request.session['Hello World'] = 'Alloy' works very well. Why is that happening ? basket app / views.py from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) context = {'basket':basket} request.session['Hello'] = 'foo' return render(request,"store/basket_summary.html",context) def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty':basketqty}) return response def basket_add_new(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product = get_object_or_404(Product, id=product_id) basket.add_new(product=product) basketqty = basket.__len__() response = JsonResponse({'qty':basketqty}) return response def basket_delete(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) basketqty = basket.__len__() baskettotal = basket.get_total_price() response = JsonResponse({'qty':basketqty, 'subtotal':baskettotal}) return response def basket_update(request): basket = Basket(request) if request.POST.get('action') == 'update-basket': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) basket.update(product=product_id, qty=product_qty) basketqty … -
Django database stored images showing only text descriptions
I am trying to store images on a database and then display them on a Django template. For some reason Django is only showing the alt (alternate - html attribute) instead of the actual image. This is the template {% extends "myapp/layout.html" %} {% load static %} {% block body %} <div class="sidenav"> <a href="{% url 'index' %}" id="active">Gallery</a> <a href="{% url 'about' %}">About</a> <a href="{% url 'contact' %}">Contact</a> </div> <div class="main"> <h2>Gallery</h2> {% for image in images %} <img class="gallery" src="{% static '{{image.image.url}}' %}" alt="{{image.description}}"> {% endfor %} </div> {% endblock %} This is my model from django.db import models # Create your models here. class Image(models.Model): image = models.ImageField(upload_to='images/') description = models.CharField(max_length=50) def __str__(self): return "Description of image: " + self.description This is what I'm seeing -
remove checkbox checked jquery
I show some checkbox to the user. When a user selects a checkbox, it is checked. If the user selects another checkbox after the first selection, the second checkbox will also be checked, but the first checkbox selected by the user will not be unchecked. I want to make sure that by selecting each check box, the previous check box is removed and several checkbox are not checked at the same time, that is, only one check box has the right to be selected. $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); <form action="" class="filter-form"> <input type="checkbox" name="price" value="new"> <input type="checkbox" name="discount" value="discount"> <input type="checkbox" name="old" value="old"> </form> -
How to get options order from select in (Model)MultipleChoiceField?
I need to somehow get the order of options from (in my case) ModelMultipleChoiceField. By that I mean indexes of options which are obtainable through JavaScript easily. I guess that to do that I would need custom Field which I've already created. It uses custom widget which allows user to reorder options of the field's select. class DataTypeForm(forms.ModelForm): file = forms.FileField() headers = OrderedModelMultipleChoiceField(queryset=Header.objects.none()) class Meta: model = DataType fields = ("file", "headers") def __init__(self, *args, **kwargs): super(DataTypeForm, self).__init__(*args, **kwargs) self.fields["headers"].queryset = Header.objects.filter(data_type=self.instance) class OrderedModelMultipleChoiceField(forms.ModelMultipleChoiceField): widget = OrderableSelectMultiple class OrderableSelectMultiple(forms.SelectMultiple): template_name = "django/forms/widgets/orderable_select.html" class Media: css = { "all": ("orderable-select-multiple.css",), } js = ("orderable-select-multiple.js",) How can I get access to those properties? -
why django channels is not working on server?
i create a django websocket chat app with django-channel and that is working in localhost very well ,but when i run it on the server with daphne and nginx is not working . since i dont have any error in journalctl -u daphne and journalctl -u nginx i think my nginx config has a problem this is nginx config in sites-available and also linked in sites-enabled : server { listen 80; server_name {DOMAIN-OR-IP}; location /ws/ { proxy_pass http://0.0.0.0:9000; proxy_http_version 1.1; proxy_read_timeout 86400; proxy_redirect off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location = /favicon.ico { access_log off; log_not_found off; } location /static_in_env/ { root /home/mhfd/newblog17/blog23; } location / { include proxy_params; proxy_pass http://unix:/home/mhfd/newblog17/blog23/blog23.sock; } } and this is config of daphne.service in systemd: [Unit] Description=daphne daemon After=network.target [Service] User={USER} Group=www-data WorkingDirectory={PROJECT-DIRECTORY} ExecStart={VIRTUAL-ENVIRONMENT-ADDRESS}/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 {PROJECT-NAME}.asgi:application [Install] WantedBy=multi-user.target i got no error but websocket chat (send and recieve) is not working? error image -
"ValueError: I/O operation on closed file" when reading CSV file from form data in Django
I want website users to be able to upload a CSV file to my webpage. The file is uploaded through a form with a FileField. I overrode the is_valid method of the FormField to check whether the file has a CSV extension or not. If the form is valid, I want to read the lines of the CSV and save them to a model. The is_valid method works well. But when I try to execute the code following the is_valid condition I run into "ValueError: I/O operation on closed file". Views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): csv_processor(form.cleaned_data['csv_file']) #messages.success(request, 'Archivo recibido para procesamiento') return HttpResponseRedirect(reverse('home_page')) else: form = UploadFileForm() return render(request, 'products/csv_upload_page.html', {'form': form}) csv_processor function def csv_processor(csv_file): csv_object = TextIOWrapper(csv_file, encoding='utf-8-sig') reader = csv.reader(csv_object) # Code to read lines follows here forms.py class UploadFileForm(forms.Form): csv_file = forms.FileField(label = 'Adjunte archivo csv', validators= [csv_content_validator]) def csv_content_validator(csv_file): if not csv_file.name.endswith('.csv'): raise ValidationError('Archivo debe tener extension csv') return True csv_object = TextIOWrapper(csv_file, encoding='utf-8-sig') reader = csv.reader(csv_object) first_row = next(reader) headers = ['SKU','Price'] # Check if column names match desired names for header_index in range(len(headers)): # Check if first row of the CSV file contains correct names … -
django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry"
Getting following error even after I have cleared all migrations.All was working fine until I tried to primary_key to my Cylinderentry model later on I removed but still it displays "django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry" " when I run py manage.py makemigrations it displays: You are trying to add a non-nullable field 'id' to cylinderentry without a default; we can't do that (the database needs something to populate existing rows).splays following : or when I run py manage.py migrate it displays: django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry" here is all models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName class ReturnCylinder(models.Model): rechoice=[ ('fill','Fill'), ('empty','Empty') ] reav=[ ('Yes','yes'), ('No','no') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) user=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) status=models.CharField(max_length=20,choices=rechoice) returnDate=models.DateTimeField(default=timezone.now) Availability=models.CharField(max_length=5,choices=reav) def save(self,*args,**kwargs): if not self.pk: IssueCylinder.objects.get(userName=self.user.userName).delete() if self.status=='yes' or self.status=='Yes': CylinderEntry.objects.get(cylinderId=self.cylinder.cylinderId).update(Availability=('available')) else: CylinderEntry.objects.get(cylinderId=self.cylinder.cylinderId).delete() super().save(*args,**kwargs) def __str__(self): return self.cylinder I don't where I m missing. Help!! -
mobile number standardization
You are given mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx The given mobile numbers may have +91,91 or 0 written before the actual digit number. Alternatively, there may not be any prefix at all. -
Has decompyle3 started to provide support for Python 3.9?
I forgot to add .gitignore in my repository root of my Python Django Project and I committed the code to my github repository. Now the root folder contains __pycache__, where all the compiled python files are located. I tried looking at, how to decompile the files and found the required resource uncompyle6 on PyPI. However, it works for Python 2.4 - 3.8. In addition, there is a Python decompiler decompyle3 for Python 3.7 - 3.8 which is stripped down from uncompyle6. But the version of Python I have been using all along is Python 3.9. Is there a way I can get around this and be able to solve my problem of decompiling my .py files anyhow so I can get the earlier project structure that I require?