Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do use the input of an HTML <select> tag as a value to get Django Models data, that has that particular input as one of it's data?
I'm using an HTML <select> tag to let the user select the title of a project, where the project is a QuerySet in a Django Model. So I want to use that value to display other data concerned with that project to the user. The name of the HTML <select> is select_project. In my views.py, I use the request.POST['select_project']and store it in a variable selected_project. In order to get other data in the QuerySet, I used Project.objects.filter(title=selected_project) and stored it in a variable displayed_project which I then used in a View where the user sees all the information about that QuerySet. But when the user goes to the view, he gets nothing. Only an empty <QuerySet[]>. Please could you help suggest a way around this? <select class="select_project" name="select_project"> {%for project in projects%} <option value="" name='select_project'>{{project.title}}</option> {%endfor%} Views.py def overview(request): if request.method=='POST': selected_project=request.POST['select_project'] displayed_project=Project.objects.filter(title=selected_project) return render (request, 'core/overview.html', { 'displayed_project':displayed_project }) Thank you! -
Login Issue Using django-Knox
I am trying to log in using my registration details in Djang-Knox. Unfortunately, I am having "non_field_errors": [ "Unable to log in with provided credentials." ] However, if I use admin details everything is working fine without issue. view.py class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) serializers.py # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, style={ "input_type": "password"}) #password2 = serializers.CharField( # style={"input_type": "password"}, write_only=True, label="Confirm password") class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} -
How do I delete an uploaded file from a Javascript Array?
Using the link here...Multiple file upload - with 'remove file' link I was able to basically get this working. However....It deletes the file upload from the screen...but it doesn't remove it from the array so it still gets uploaded. Been playing with this all morning. I am using Django....could it be that the getlist is not being emptied out upon delete? Thanks in advance for any thoughts... Javascript.. $(document).ready(function (){ $.fn.fileUploader = function (filesToUpload) { this.closest(".files").change(function (evt) { for (var i = 0; i < evt.target.files.length; i++) { filesToUpload.push(evt.target.files[i]); }; var output = []; for (var i = 0, f; f = evt.target.files[i]; i++) { var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">Remove</a>"; output.push("<li><strong>", escape(f.name), "</strong> - ", f.size, " bytes. &nbsp; &nbsp; ", removeLink, "</li> "); } $(this).children(".fileList") .append(output.join("")); }); }; var filesToUpload = []; $(document).on("click",".removeFile", function(e){ e.preventDefault(); var fileName = $(this).parent().children("strong").text(); for(i = 0; i < filesToUpload.length; ++ i){ if(filesToUpload[i].name == fileName){ filesToUpload.splice(i, 1); } } $(this).parent().remove(); }); $("#files1").fileUploader(filesToUpload); $("#files2").fileUploader(filesToUpload); $("#uploadBtn").click(function (e) { e.preventDefault(); }); }); HTML.... <div class="row files" id="files1"> <span class=""> <input type="file" name="files1" multiple /> </span> <br /> <ul class="fileList"></ul> </div> I cut down some of the HTML...I used the original version … -
Python issue with virtual environment
I set up Django CMS project and I created my first blog. When running the server I am opening http://127.0.0.1:8000/blog by default. I saved it in my Projects folder. Now I want to test Wagtail CMS but I cannot open the page because it is changing my localhost page from http://127.0.0.1:8000 to http://127.0.0.1:8000/blog and I get an error Page not found. I can only access admin panel and nothing more. I removed all environments and reinstalled all packages from scratch but it didn't help. I tried to create Django quickstart project and I have the same issue. Whenever running command python.manage.py runserver it redirects me to http://127.0.0.1:8000/blog and I get the same error which is 404 Not Found. I was following these steps when installing Django CMS. -
Django + Postgres + UUID
So I've been trying to add a UUID field to my model, to use it in my URL but I keep getting this error django.db.utils.ProgrammingError: column "id" is of type bigint but expression is of type uuid LINE 1: ..._book" ("id", "title", "author", "price") VALUES ('f6b15400-... ^ HINT: You will need to rewrite or cast the expression. Here is my models.py: from django.db import models import uuid from django.urls import reverse # Create your models here. class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) Here is the views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Book # Create your views here. class BookListView(ListView): model = Book template_name = 'books/book_list.html' context_object_name = 'book_list' class BookDetailView(DetailView): model = Book template_name = 'books/book_detail.html' context_object_name = 'book' Here is the urls.py: from django.urls import path from .views import BookListView, BookDetailView urlpatterns = [ path('', BookListView.as_view(), name='book_list'), path('<uuid:pk>/', BookDetailView.as_view(), name='book_detail'), ] -
ImportError attempted relative import with no known parent package - Django 2.x
I trying create Django App and when I try save some data with my form, my app doesn't recognize and gives an error and I debugging my code this appeared. Views.py from django import forms from django.shortcuts import redirect, render, get_object_or_404 from .models import Produto from .forms import ProdutoForm def NewProduct(request): data = {} producForm = ProdutoForm(request.POST or None) if producForm.is_valid(): producForm.save() return redirect('/products') data ['productForm'] = producForm return render(request, 'NewProduct.html', data) Models.py from django.db.models.fields import CharField, DateTimeField, IntegerField from django.db import models class Produto(models.Model): nomeProduto = models.CharField(max_length = 30, null = True) equipamento = models.CharField(max_length = 10, null = True) capacidadeProduto = models.FloatField(null = True) I tried in every way, saw tutorials, researched in various forums and nothing solved my problem. -
Method: set is not working properly in django-redis
I'm trying to store IP address in redis using django, but set method is not working. Here is my API in views.py: def cache_test(request): ip = str(request.META.get('REMOTE_ADDR')) cache.set(ip,'2',timeout=22) print(ip) print(cache.get(ip)) #print(radis_cache.get(1)) return HttpResponse(str(cache.keys('*'))) CACHES setting in setting.py CACHES = { 'default' : { 'BACKEND' : 'django_redis.cache.RedisCache', 'LOCATION' : 'redis://127.0.0.1:6379/', 'OPTIONS' :{ 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } Error: It work with following but don't show anything on get: def cache_test(request): #radis_cache = radis_cache['default'] ip = str(request.META.get('REMOTE_ADDR')) cache.set(ip,'2',timeout=0) print(ip) print(cache.get(ip)) #print(radis_cache.get(1)) return HttpResponse(str(cache.keys('*'))) I already try following but nothing work: cache.set(ip,'2') # Error: wrong number of arguments for 'set' command cache.set({ip:'2'}) #Error: missing 1 required argument Libraries list asgiref==3.4.1 Django==3.2.7 django-redis==5.0.0 psycopg2==2.9.1 pytz==2021.1 redis==3.5.3 sqlparse==0.4.2 -
MultiValueDictKeyError at /api/restaurateur/create_meal/ 'data'
I am trying to write data to the database but I get this error MultiValueDictKeyError at /api/restaurateur/create_meal/ 'data' Here is my model.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField() Here is my views.py @action(['POST'], detail=False, url_path='create_meal') def get_restaurant_meals(self, *args, **kwargs): restaurant = Restaurant.objects.get(owner=self.request.user.restaurateur) meal_data = self.request.data meal = Restaurant.objects.create(title=meal_data["data"], description=meal_data["description"], price=meal_data["price"], restaurant=restaurant, slug=meal_data["slug"], ) meal.save() serializer = MealSerializer(meal) return response.Response(serializer.data, status=status.HTTP_201_CREATED) I work with the django rest framework, my view is in the viewsets.ModelViewSet class -
Django InconsistentMigrationHistory when adding app initial migration
There are some interesting suggestions in a similar question but it doesn't help with my problem. Also, I have this app in production in several countries. We are migrating an app and started with managed=False on all models. We then had a claim_batch app that has a migration 0002_capitationpayment: dependencies = [ ('product', '__first__'), ('claim_batch', '0001_initial'), ] # Some models with foreign keys to "product.Product" The product module doesn't have migrations but it has models. When I do a showmigrations in this situation, I have: product (no migrations) And it works fine somehow. The problem is that I now need to add migration with a managed table in product. When I do the makemigrations and try to migrate, I'm getting: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration claim_batch.0002_capitationpayment is applied before its dependency product.0001_initial on database 'default'. It makes sense. The claim_batch.0002 is referencing a migration that is now existing but was not applied and it should not be possible to apply it after its dependency. Except in this scenario. If I try to remove the dependency from the already applied migration, I'm getting: ValueError: The field claim_batch.CapitationPayment.product was declared with a lazy reference to 'product.product', but app 'product' isn't installed. I'm guessing that a … -
How to add a calculated field to a django admin inline
I am trying to add a calculated field to a Django Admin Inline. Consider this set of classes: models.py: class MyGroup(models.Model): group_name = models.CharField() group_size = models.IntegerField() class MyUser(models.Model): user_name = models.CharField() groups = models.ManyToMany(MyGroup, related_name="users", through=MyMembership) class MyMembership(models.Model): group = models.ForeignKey(MyGroup) user = models.ForeignKey(MyUser) timestamp = models.DateTimeField(auto_add_now=True) I want to show the group.size field in the inline. I thought the following code would work: admin.py: class MyMembershipInline(admin.TabularInline): model = MyUser.groups.through fields = ( "group", "timestamp", "size", ) readonly_fields = ( "timestamp", "size", ) def size(self, instance): return instance.group.size @admin.register(MyUser): class MyUserAdmin(admin.ModelAdmin) fields = ("user_name",) inlines = (MyMembershipInline,) But I am getting the following error: Unknown field(s) (size) specified for MyMembership Any advice? -
Trying to contribute to django project but the lint is failing for me
I am trying to contribute code to django project, but my linter is not suited for it. I am using pylint and it is formatting the code in a very different way. Examples: Django project has a lot of strings with single quotes ', pylint converts that to " double quotes. Workaround can be that I can override that in settings. Method parameters are sliit across lines, when django project has them in single line. Many more examples are there. I tried joining #Django IRC channel to ask the same question there, but getting this error there you need to be logged into your NickServ account I tried running eslint because django project has a config file for the same, but that is also not working. eslint . Gives no output on command line. Any suggestion on how does django project manages linting? My last option is to disable pylint and manually format all the files that I am modifying, but that would mean for every other python project I would have to enable it and for this project I would have to disable it. Which will be tedious and prone to mistakes. Any pointers to any django documentation on … -
Django overwrite model save method to check if a many to many field has changed
so I have a model for which I need to overwrite the save property to check if a many to many relation has changed. Normally for like a char field you could do something like the below, but for many to many it works differently. class Interest(TimestampedModel): subjects = models.ManyToManyField('genre.Subject', blank=True) def save(self, *args, **kwargs): if self.id: old_subjects = Interest.objects.filter(pk=self.pk).first().subjects.all() subjects = self.subjects.all() if subjects != old_subjects: # Do stuff Any idea how to make something like this for a many to many field? -
user search engine with tags - Django - Python
I want to make a user search engine with profile tags. The search engine will show users and tags models.py class UserProfile(models.Model): objects = None user = models.OneToOneField(User, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=True, null=True) bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) location = models.CharField(max_length=100, blank=True, null=True) picture = models.ImageField(upload_to='uploads/profile_pictures/', default='uploads/profile_pictures/default.png', blank=True) followers = models.ManyToManyField(User, blank=True, related_name='followers') tag_i = TagsField(max_length=1000, default='non') views.py class UserSearch(View): def get(self, request, *args, **kwargs): query = self.request.GET.get('query') profile_list = UserProfile.objects.filter(Q(tag_i__icontains=query) | Q(user__username__icontains=query)) field_name = 'tag_i' obj = UserProfile.objects.first() field_object = UserProfile._meta.get_field(field_name) field_value = field_object.value_from_objects(obj) field_value = "".join(field_value) field_value = field_value.split(",") context = { 'profile_list': profile_list, "tags": field_value, } the current code assigns the same tags to everyone. How to assign tags to each person? what should I use instead.. obj = UserProfile.objects.first() to make tags suitable for individual users -
Django Rest Framework ordering by count of filtered pre-fetched related objects
I'm hoping someone might be able to help me. I am working with Django Rest Framework, and attempting to create an API that allows users to search for Providers that provide specific Procedures in particular Regions, and only return the relevant details. Set up I have these models (heavily simplified): # models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Region(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ["name"] class Procedure(models.Model): description = models.CharField(max_length=100) class Meta: ordering = ["description"] class Provider(models.Model): provider_name = models.CharField(max_length=200) class Meta: ordering = ["provider_name"] class Provision(models.Model): fk_procedure = models.ForeignKey( Procedure, related_name="providers", on_delete=models.RESTRICT, ) fk_provider = models.ForeignKey( Provider, related_name="services", on_delete=models.CASCADE, ) discount = models.FloatField( validators=[MaxValueValidator(100), MinValueValidator(0)], default=0, ) class Meta: ordering = ["-discount"] unique_together = ["fk_procedure", "fk_provider"] class ProvisionLinkRegion(models.Model): fk_provision = models.ForeignKey( Provision, related_name="regions", on_delete=models.CASCADE, ) fk_region = models.ForeignKey( Region, related_name="services", on_delete=models.RESTRICT, ) location = models.BooleanField(default=False) As you can see, there is a ManyToMany link between Provision and Region via ProvisionLinkRegion. I haven't defined this as a ManyToMany field though, as I need to store additional details (location) about the pairing. I have defined the following serializers on these models: # serializers.py from rest_framework import serializers from models import ( Provider, Region, Procedure, ProvisionLinkRegion, … -
I've got authentication error with Alpaca broker api
Want some help from you. I am working in Django/React project with Alpaca Broker APi https://alpaca.markets/broker https://prnt.sc/1sfzv9k I am trying to get relationship ID. Btw I am getting the error like screenshot Please help me if you have an expertise with Alpaca API Thanks -
How do I show the output of a shell command in Django using channels?
I want to display the content of an install command executed by the user on my webpage. The commands are typically slow, so I wanted to display a live output of their logs. I want the output of this command to be used inside a template. I know that I may need to write a websocket to do this, but I hear that django channel can help me with this. Can someone provide me with a simple example of how to do this? All I need is simple websocket code(websocket.py), django views(views.py), and the template(template.html). Of course, if settings.py needs changed, please let me know. Thanks, Jacob -
How to have common query in django for notification system?
I have an "bell" icon on nav bar - which shows notification for each users ! As of now, all the nav bars are made common layouts and included into blocks of each page in django. Now the problem is when ever i go to a screen, its needs to make query all on notification model to display the notifications ! And i have 24 pages, and which means notification needs to be fetched for 24 times. How to make this effeciently, so that i just query once and show notification on each page when user visits there Please guide, i dont know what code to show. If you need any code please mention on comment -
data in a formset passed by a form
hi I have this error in inserting a data in a formset passed by a form this is the error that appears in my browser: NOT NULL constraint failed: devtest_datigruppi.gruppi_scheda_id it practically fails to see this change: groups.gruppi_scheda = Schede.objects.get (tab_name = tabName) but via print the right thing appears to me schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() #gruppi if gruppi_formset.is_valid(): for gruppi in gruppi_formset: gruppi.save(commit = False) gruppi.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) print(gruppi.gruppi_scheda) gruppi.save() -
Arrangind models names according to our wish in Django admin dashboard
Django admin dashboard image ( click here) In the above django admin panel , the model names are arranged according to ascending order. Can i arrange them in my own wish ? If yes , can u suggest me how? -
Django don't send email message with attached zip file
everyone! I have a problem with sending an email with Django smtp email backend and SendGrid. My view is below. It makes batch of pdf files with pyppeteer, zip them to archive, attaches to the message and then send it to the email. It should be, but it doesn't work! I checked it with other view for email sending(a little bit diff logic without zip or something.) and it worked but this means that it's not the problem with sendgrid and any other stuff like secret keys in uwsgi configuration. The fact is, emails don't stuck in send grid list. I tried to put some dummy bites instead of pdf file like pdf_file = b'some bytes' and it worked on my local machine but didn't work on server. I got the size of zip-archive from a response. Please explain to me where I'm wrong. ### views.py @csrf_exempt @require_POST def generate_batch_pdf(request, blueprint): try: payload = json.loads(request.body) email = payload.get('email') uuids = payload.get('uuids') zip_buffer = io.BytesIO() compression = zipfile.ZIP_DEFLATED with zipfile.ZipFile(zip_buffer, 'a', compression, False) as f: for uuid in uuids: report_name = _report_name(uuid, blueprint) pdf_file = async_to_sync(generate_pdf_file)( request.get_host(), uuid, blueprint, report_name, ) f.writestr( zinfo_or_arcname='{0}'.format(report_name), data=pdf_file, ) msg = EmailMessage( subject='Отчеты Тест', body='Архив … -
Django app crash after pytesseract reads autogenerated image from pdf
When a user uploads files to my system, I start a new thread that scan them in order to find a specific pattern, while the view that handles the upload returns and the app is redirected to the main page. thread = threading.Thread(target=fucn1, args=(arg1,)) thread.start() In func1(), if the file is a PDF, I divide it into pages and then save and analize each of them, as below: def func1(uuid): documents = Document.objects.filter(model_uuid=uuid) result = set() for document in documents: if extension == 'pdf': pages = convert_from_path(filepath,500) for i in range(len(pages)): page = pages[i] img_filepath = local_directory + 'page_' + str(i) + '.jpg' page.save(img_filepath, 'JPEG') values = analize(img_filepath) result = set.union(result, values) else: values = analize(filepath) result = set.union(result, values) def analize(filepath): pattern = "xxxxxxxxxxxx" # Load image img = cv2.imread(filepath) # Extract text from image sret = pytesseract.image_to_string(img) return re.findall(pattern, sret) If the input file is already an image (png, jpg, jpeg), the division by pages is omitted, and everything works good. However, if the file is a PDF, the system crashes here: sret = pytesseract.image_to_string(img) Which leads me to think that there is an issue regarding pdf2image or poppler-utils. However, this function also gets executes when the input … -
Adding multiple parameters to a JS script from HTML
I would like to pass some data from my Python view function to a JS script using HTML. That's my view function def home(request): if request.method == 'POST': params = GameOfLifeForm(request.POST) if params.is_valid(): starting_grid = get_starting_grid(params.cleaned_data) to_html = { 'animation': True, 'gameoflifeform': params, 'start_grid': starting_grid, } else: to_html = { 'animation': False, 'warning_msg': 'Something went wrong. Try once again.' } return render(request, 'get_animations/home.html', to_html) else: form = GameOfLifeForm() return render(request, 'get_animations/home.html', {'gameoflifeform': form}) My form contains four parameters, one of them is called iterations and that is the one I would like to pass to JS script. Moreover I would like to pass start_grid. I tried to do it in the following way in my HTML file {{ start_grid | json_script:"start-grid" }} <script type="text/javascript" src="{% static 'js/runGameOfLife.js' %}" ></script> Then in my JS script I wrote var startGrid = JSON.parse(document.getElementById("start-grid").textContent); console.log(startGrid); Worked perfectly, I got the grid printed out in my console. Similar I could grab iterations from HTML {{ gameoflifeform.iterations.value | json_script:"iterations"}} <script type="text/javascript" src="{% static 'js/runGameOfLife.js' %}" ></script> When I tried to add both variables into my JS script it didn't work. {{ gameoflifeform.iterations.value | json_script:"iterations"}} {{ start_grid | json_script:"start-grid" }} <script type="text/javascript" src="{% static 'js/runGameOfLife.js' %}" ></script> … -
Cannot connect to celery signals from django
I have the default django integration from the celery docs. Also just added @before_task_publish.connect(weak=False) def before_task_publish_handler(*args, **kwargs): logger.error(f'Args {args}') logger.error(f'Kwargs {kwargs}') Running in the shell: debug_task.delay() There is no logging or breakpoint catching in pycharm. I do not think it connects to celery, but I do not know how to check. What am I missing? -
Using kong api gateway jwt plugin with django microservices
I am currently playing around with the Kong API Gateway and I would like to use it to validate the authentication and the authorization of users at the gateway and restrict access to services if the user is not logged in properly. I have already an existing authentication django microservice which issues JWTs whenever a user logs in but i cant share this tokens with the other microservices because each one of them have his own database. So i would now like to know if i can share the JWT secret produced by django and use it for jwt plugin of kong api and also do i need to create a consumer for every users and what is the right steps to achieve that ? Any hint would be highly appreciated. -
unable to create recs via foreign key association in django
I am completely new to django and python need your insights here I am trying to parse a list of csv files from a directory, storing the name and row_count in Files model and the content of the csv in Work model(associated with Files) I have two queries The recs are created in Files model , but no recs being created in Work model, below is my code and no error message is thrown Models class Files(models.Model): filename = models.CharField(max_length=100) work_count = models.IntegerField(default=0) class Work(models.Model): proprietary_id = models.IntegerField(default=0) iswc = models.CharField(max_length=1000) source = models.CharField(max_length=1000) title = models.CharField(max_length=1000) contributors = JSONField() file = models.ForeignKey(Files,on_delete = models.CASCADE) View root_dir="D:/Django/siva/files" for file in os.listdir(root_dir): with open(f'{root_dir}/{file}','r') as csv_file: csv_reader= csv.DictReader(csv_file,delimiter=',') Files.objects.create(filename=file, work_count=len(list(csv_reader))) for row in csv_reader: file_obj=Files.objects.get(filename=file) print(file_obj) Work.objects.create(proprietary_id=row['proprietary_id'],iswc=row['iswc'],source=row['source'],title=row['title'],contributors=row['contributors'],file_=file_obj) sample csv file title,contributors,iswc,source,proprietary_id Shape of You,Edward Christopher Sheeran,T9204649558,sony,1 Je ne sais pas,Obispo Pascal Michel|Florence Lionel Jacques,T0046951705,sony,3 And also is there any specific method to set the root_dir , so I don't need to change the filepath structure across OS's