Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if some datatype is string or list in python?
I'm trying to add a check here that if the receiver is just a string. then convert that into list else just pass. if type(receiver) == str: receiver=[receiver] error: TypeError: 'str' object is not callable -
How to access websocket from another function in another file
I'm trying to make a login page, and I want to access the websocket I've opened up. I'm assuming although I could be wrong, that you only want one websocket open at a time so I'm trying to use the one from earlier. But I'm having trouble accessing it. This is my main file that hosts what I have so far import React, { Component, useState, useEffect } from 'react'; import { render } from 'react-dom' import WebSocketStuff from './websocket'; import Navbar from './navbar'; import Login from './login'; import { BrowserRouter as Router, Switch, Route, Link, Redirect } from "react-router-dom"; function App() { return ( <div> <Navbar /> <WebSocketStuff /> <Router> <Switch> <Route path="/account/login" component={Login}></Route> </Switch> </Router> </div> ); } const appDiv = document.getElementById("app"); render(<App />, appDiv); This is the javascript file that has the websocket code. import React, { Component, useState, useEffect } from 'react'; export default function WebSocketStuff(props) { const [name, setName] = useState(''); console.log(window.location) var loc = window.location var socket; useEffect(() => { var wsStart = 'ws://' if (loc.protocol == 'https:') { wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname; socket = new WebSocket(endpoint); console.log(socket); socket.onmessage = function (e) { console.log("message", e) setName(e.data); … -
when I try to use SyncToAsync() using django and hit 3rd party API endpoint. I get 'SyncToAsync' object has no attribute 'get' error
Iam trying to use async functionality to django views with SyncToAsync(https://docs.djangoproject.com/en/3.2/topics/async/#sync-to-async). I have to hit a 3rd party API using request.get method. But when I hit my endpoint.I get the above error. Any idea how to resolve it... -
How to create models for friend system in django?
I haven't seen much talks about in the internet . I want to create a friend system for my personal project . I think if i can create it I will have better understanding of ORM which I don't I think . Please help me out guys :'( . And possibly explain in a nutshell of what you did . -
How do I make changes to my Django HTML view file that extends a base template?
I have a Django test project that I am working on, and have been working on it for hours now, and I am stuck. I can't add other html syntax into my html file that extends a base template into it. I have a base template that works on my html view, however, when I make changes inside the html view, it doesn't reflect. Looks like I am missing something between the HTML view, and the base template. Below is the HTML view <!DOCTYPE html> {% extends "base.html" %} <!--https://www.anwita-arun.in/ --> {% block head %} <html lang="en"> <head> <title>Test Project</title> </head> {% endblock %} {% block body %} <body> <h1 style="font-size: 250px"> Testing </h1> <p> aloha </p> <form method="POST"> <!-- Form creation with post. No method "post" needed --> {% csrf_token %} <!-- Insert token --> {{ form.as_p }} <!-- form variable --> <input type="submit"> <!-- Form input submission --> </form> </body> {% endblock %} Below is the base template <!DOCTYPE html> <!--https://www.anwita-arun.in/ --> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia"> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/4.10.1/bootstrap-social.css" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"> <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/css?family=Rajdhani&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Lobster&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/coliff/bootstrap-rfs/bootstrap-rfs.css"> … -
I'm unable to accept friend request from other users in my Django social site
unable to accept friend requests in my web app below are the errors that I'm getting when I'm trying to accept the friend request. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/users/friend-request/accept/5/ Django Version: 2.1 Python Version: 3.8.10 Installed Applications: ['users.apps.UsersConfig', 'feed.apps.FeedConfig', 'crispy_forms', 'stdimage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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: File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.users_profile__old) was the direct cause of the following exception: File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/rohan/ByteWalk-master/users/views.py" in accept_friend_request 88. user1.profile.friends.add(user2.profile) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py" in add 926. self._add_items(self.source_field_name, self.target_field_name, *objs) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py" in _add_items 1088. self.through._default_manager.using(db).bulk_create([ File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/query.py" in bulk_create 465. ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/query.py" in _batched_insert 1152. self._insert(item, fields=fields, using=self.db) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/query.py" in _insert 1133. return query.get_compiler(using=using).execute_sql(return_id) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in execute_sql 1285. cursor.execute(sql, params) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in execute 100. return super().execute(sql, params) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in execute 68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in … -
How to link my Django form selection to filtered database values
I am configuring a web page using Django in which I would like my form's dropdown options to filter the database options based on master ID. There are four options: allElements, oldElements, newElements, and testElements. My problem is that while I can create a for loop to iterate through the database based on any of the four variables I've defined, my form selection is not linked to the choices like I thought it would be. Can anyone help? My form: account_choices=[('allElements','All Elements'), ('oldElements','Old Elements'), ('newElements','New Elements'), ('testElements','Test Elements')] class SelectIdForm(forms.Form): Filter = forms.ChoiceField(choices = account_choices, error_messages={'required': ''}) My view: def metalist(request): form=SelectIdForm(request.POST) if account_choices == 'allElements': data = Metadata.objects.all().order_by('title') elif account_choices == 'oldElements': data = Metadata.objects.all().filter(metaMain = 1).order_by('title') elif account_choices == 'newElements': data = Metadata.objects.all().filter(metaMain = 2).order_by('title') elif account_choices == 'testElements': data = Metadata.objects.all().filter(metaMain = 3).order_by('title') else: data = Metadata.objects.all().order_by('title') return render(request, "Site/insights/metalist.html", {"allElements": Metadata.objects.all().order_by('title'), "oldElements": Metadata.objects.all().filter(metaMain = '423844416462').order_by('title'), "newElements": Metadata.objects.all().filter(metaMain = '689665504419').order_by('title'), "testElements": Metadata.objects.all().filter(metaMain = '542384344085').order_by('title'), "form": form, 'data': data }) My HTML page: <form method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Click to Filter"> </form> {% for list in data %} <li> Metadata List: <a href="{% url 'Site:insights/metalist' account.title %}"> {{ metadata.title }}</a> </li> {% endfor %} I've … -
Django - Run all tests inside of "test" sub-folder
So I've been running tests using the command python manage.py test to run every test inside the test folder and I'd like to run all test in a subfolder of the test folder. So I tried python manage.py test <app name>.test.<sub-folder>(path to the test sub-folder), but it doesn't work. I created an __init__.py file inside <sub-folder> that imports all the test files in <sub-folder>, but that didn't work. Every time I run python manage.py test <app name>.test.<sub-folder> the terminal outputs Run 0 tests in Xs. How do you run all tests inside of a sub-folder of the test folder in Django? -
Django virtual environment successfully installed. But when I run 'pip freeze' in command prompt it says 'No python at C drive'
Python is already installed and the version is 3.8. Could anyone help me? [1]: https://i.stack.imgur.com/44FSS.jpg![enter image description here](https://i.stack.imgur.com/kGWX3.jpg) -
I have a model with a many to many field. How can I display the information only if that field is selected?
I am making a recipe app. The model Recipe has a ManyToMany field favorites. On my favorites page I only want to display the recipes that are favorited. I can only figure out how to display all of the recipes. How can I set it to only display the recipes that has a user favorite it? models.py: class Recipe(models.Model): title = models.CharField(max_length=45) description = models.CharField(max_length=180) recipe_image = models.ImageField(upload_to=get_image_path, blank=True, null=True, default="/static/photos/food_default.jpg") favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True) def __str__(self): return self.title views.py: def pinned_view(request): fav = Recipe.objects.all() model = { "fav": fav } return render(request, 'pinnedRecipes.html', model) pinnedRecipes.html: <div id="favoritedCollapse" class="collapse" aria-labelledby="favorited" data-parent="#accordion"> <div class="card-deck list-inline p-0"> <a href="#" class="card card-custom list-inline-item m-4"></a> {% for fav in fav %} {% for recipe in fav.recipes.all%} <img class="card-img-top img-thumbnail img-custom" src="{{ recipe.recipe_image.url }}" alt="Image Not Found" /> <div class="card-body"> <h5 class="card-title text-truncate"></h5>{{ recipe }} {% for recipe in fav.recipes.all%} <p class="card-text text-truncate">{{ description }}</p> {% endfor %} </div> </a> {% endfor %} {% empty %} <h3>No Favorites </h3> {% endfor %} </div> </div> -
Why is my else statement not working in django rest framework?
I have the following code: views.py @api_view(['DELETE']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def selected_job_delete(request,pk=None): if pk != None: job=Job.objects.get(pk=pk) jobdetail = Job_detail.objects.get(job=pk) jobtrack = Job_track.objects.get(job = pk) jr = Job_removed() jdr = Job_detail_removed() jtr = Job_track_removed() jr.jobname = job.jobname jr.owner = job.owner jr.enabled = job.enabled jr.start_date = job.start_date jr.start_time = job.start_time jr.date_added = job.date_added jr.version = job.version jr.save() jdr.job = jr jdr.json = jobdetail.json jdr.save() jtr.job=jr jtr.jobdetail= jdr jtr.save() operation = job.delete() data = {} if operation: data["Success"] = "Successfully deleted" else: data["Failure"] = "Unsuccessful" return Response(data) urls.py path('api/jobs/<int:pk>/delete', views.selected_job_delete), Lets say my database in Job have the only following id of 40. I want to delete it so i key the url of api/jobs/40/delete and the deletion will happen, followed by the task in the function. The output result in my postman will show it is successfully deleted . But if I key the url of api/jobs/41/delete, the id of 41 does not exist in my database, it does not run my else statement to show unsuccessful . Instead it shows me How can I make it to show unsuccessful instead of the whole chunk of the error that it does not exist? -
TransactionManagementError in Django when make migrate
I am new to programming , I have an issue when make migrate in Django 3.2.9. Here is my code, models.py from django.db import models from django.db.models.deletion import CASCADE, PROTECT # Create your models here. class Promotion(models.Model): description = models.CharField(max_length=255) discount = models.FloatField() class Collection(models.Model): title = models.CharField(max_length=255) class Product(models.Model): slug = models.SlugField() title = models.CharField(max_length=255) description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLD, 'Gold') ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) membership = models.CharField( max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) class Order(models.Model): STATUS_Pending = 'P' STATUS_Complete = 'C' STATUS_Failed = 'F' STATUS_CHOICES = [ (STATUS_Pending, 'Pending'), (STATUS_Complete, 'Complete'), (STATUS_Failed, 'Failed') ] placed_at = models.DateTimeField(auto_now_date=True) payment_status = models.CharField( max_length=1, choices=STATUS_CHOICES, default=STATUS_Pending) customer = models.ForeignKey(Customer, on_delete=PROTECT) class Address(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) customer = models.OneToOneField( Customer, on_delete=models.CASCADE, primary_key=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=PROTECT) product = models.ForeignKey(Product, on_delete=PROTECT) quantiy = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=5, decimal_places=2) class Cart(models.Model): created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=CASCADE) product = models.ForeignKey(Product, on_delete=CASCADE) quantity = … -
How do I write a Django query to get distinct objects linked to another object?
I'm using Python 3.9 and Django 3.2. I have this class, which has a field for another ... class Transaction(models.Model): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) account = models.ForeignKey('Account', on_delete=models.CASCADE) I woudl like to get the distinct set of Account objects, linked to certain transactions., so I treied this class TransactionManager(models.Manager): def get_accounts_with_pending_transactions(self): """ Returns acounts with pending transactions """ return Transaction.objects.filter(status=Transaction.Status.PENDING).values("account").annotate(n=models.Count("pk")) ... However, the above seems to return a list of dicts as opposed to objects. Thus, I don't have access to all the fields from my Account objects. Is there any way to write a query to get the Account objects such that they are already hydrated as actual objects? -
Django - What happens when you delete an entity in a table that has a foreign key ManyToMany relationship to another?
I've noticed that Django doesn't let you set the on_delete parameter for ManyToManyField. This made me curious what happens if you delete an entity in a ManyToMany relationship? So for example, let's say we have Book, which has a ManyToMany relationship to Author. Let's say that a book A has 3 authors: "Tom Lam", "Lam Tom" and "Britney Britney". Then let's say "Britney Britney" gets deleted from the Author table. Does "Britney Britney" get removed from the ManyToMany relationship with Book? Does an exception get thrown when trying to delete "Britney Britney?" What does Django do in the case that an entity is deleted when it exists in a ManyToMany relationship? -
Django-allauth: Redirect users post sign-up/sing-in to a specific page depending on the page they are coming from
Problem I have an invite system in my django app that allow users to invite other people (using their email) to join their team. When an invited user clicks on an invitation, they are redirected to an url that carries informations about the specific team the user was invited to. Such url calls a view called accept_invitation that handles the following use-cases: a) If a user is logged-in already AND they are also the invited user (i check the email of the invite), I add the user to the team and redirect them to the team's page. b) If a user is logged-in already BUT they are not the invited user, I redirect them to a page where I invite them to log-in with a different account. c) If a user is logged-out, I redirect them to a page where I invite them to log-in and/or sign-up to continue. Use-case a) works just fine but use-case b) and c) I had to figure out how to propagate the informations of the invite to the following screens and past the login. My initial idea was to add the parameters of the invitation to the request.session so that after the login-in I … -
Fix Django "Unresolved attribute reference" for prefetched field
Let's say I have the following Django models: class Toolbox(models.Model): name = models.CharField(max_length=255) tools = models.ManyToManyField("Tool") class Tool(models.Model): class Size(models.TextChoices): SMALL = "S" MEDIUM = "M" LARGE = "L" name = models.CharField(max_length=255) size = models.CharField(max_length=10, choices=Size.choices) I have a function to get all small tools for each toolbox. The @queries_disabled() comes from django-zen-queries to ensure the small tools have been prefetched and avoid N+1 performance problems. @queries_disabled() def get_toolbox_to_small_tools_mappings(toolboxes: list[Toolbox]) -> dict: return {toolbox: toolbox.small_tools for toolbox in toolboxes} The problem is my editor (PyCharm) is highlighting a warning: Unresolved attribute reference 'small_tools' for class 'Toolbox' I can fix this my changing the argument's type hint: def get_toolbox_to_small_tools_mappings(toolboxes: list[Toolbox] | QuerySet): ... This feels a little hacky to me. Is there a better way to fix this? -
In Django how I can create automatically a many to many entry based on a field found in two models
I have the following models example: class TestSet(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Class(models.Model): name = models.CharField(max_length=50) test_set_id = models.ForeignKey(TestSet) def __str__(self): return self.name class Test(models.Model): title = models.CharField(max_length=50) test_set_id = models.ForeignKey(TestSet) def __str__(self): return self.title class ClassTest(models.Model): class_id = models.ForeignKey(Class) test_id = models.ForeignKey(TestSet) memo = models.CharField(max_length=250) def __str__(self): return self.memo What I want to do is when a new Class or Test is created, it should also create automatically a ClassTest entry if their test_set_id matches with the currenct entries on the database. Example: Lets say I already have three Test objects with test_set_id = 1 I create a new Class object with test_set_id = 1 After creating the new Class object, the program should also create 3 new entries in the ClassTest model connecting classes to tests based on the match of the test_set_id field. It should work the same if a new Test object is added. -
how to compare two querysets in django
I'm writing an if statement in Django that compares two querysets and extracts the same assignment. Although the results of cycle_per_day and next_visit_per_day are different, the field values are the same because the same Class Model is used. The assignment_id field is also included in both querysets. In other words, I would like to add a condition called if next_visit_per_day query reset exists in the cycle_per_day query set. But it doesn't apply. What went wrong? cycle_per_day = cycle_visit.filter(dosing_date__day=day, dosing_date__year=self.year, dosing_date__month=self.month, assignment__teacher=self.user.first_name) next_visit_per_day = next_visit.filter(next_visit__day=day, next_visit__year=self.year, next_visit__month=self.month, assignment__teacher=self.user.first_name) d = '' for cycle_visit in cycle_per_day: d += f'{cycle_visit.get_html_url_cycle}' for next_visit in next_visit_per_day: if next_visit.assignment_id in cycle_per_day: d += f'{next_visit.get_html_url_drop}' else: d += f'{next_visit.get_html_url_next_visit}' -
Form not submitting to the DataBase when using HTMX
I have the following models, and as you can see they are related to each other class Leads(models.Model): project_id = models.BigAutoField(primary_key=True, serialize=False) created_at = models.DateTimeField(auto_now_add=True) expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD') expected_licenses = models.IntegerField() country = CountryField(blank_label='(select_country)') status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled'), ('Idle', 'Idle') ], max_length=10) estimated_closing_date = models.DateField() services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'), ('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'), ('Software License', 'Software License'), ('Software Development','Software Development')], max_length=40) agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE) company = models.ForeignKey(Company,on_delete=models.CASCADE) point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) application = models.CharField(choices=[('O&G','O&G'),('Renewables','Renewables'),('Mining','Mining'), ('Other','Other'),('CSS','CSS')], default='O&G',max_length=20) sub_category = models.CharField(choices=[('Wind','Wind'),('Geo-Thermal','Geo-Thermal'),('Solar','Solar'), ('Tidal','Tidal')], max_length=20, blank=True) @property def age_in_days(self): today = date.today() result = self.estimated_closing_date - today return result.days def __str__(self): return f'{self.project_id}' class LeadEntry(models.Model): revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD',blank=True) date = models.DateField() lead_id = models.ForeignKey(Leads,on_delete=models.CASCADE) id = models.BigAutoField(primary_key=True, serialize=False) probability = models.DecimalField(max_digits=2, decimal_places=2, default=0, blank=True) @property def est_revenue(self): result = self.revenue * probabiity return result Essentially a lead entry is related to the lead, and I'm using HTMX to essentially add data to LeadEntry database using a form. Form class LeadEntryForm(forms.ModelForm): class Meta: model = LeadEntry fields = ('lead_id','date','revenue','probability') widgets = {'date': DateInput()} I have 2 views, one that will simply pass an HTML with a button for the user … -
bad performance for loop with instance and bulk create
I need to use bulk_create to create a lot of "detalle"(details), the problem is i have to iterate trough a json to get the arguments, and i got 4 fk so django ask to me for the instance, not the id. but to have id i have to do a .get(), so i got a bad performance, because its 4 gets by each iteration. its there a way to get all objects instances and put in a list or something to perform load then the instance without using get every time? class DetalleFichaAllViewSet(viewsets.ModelViewSet): serializer_class = DetalleFichaUpdateAllSerializer def create(self, request, *args, **kwargs): user = self.request.user data = request.data try: ficha = Ficha.objects.get(autor=user.id) DetalleFicha.objects.filter(ficha=ficha.id).delete() except Http404: pass # Create Ficha now = datetime.now() date_time = now.strftime("%Y-%m-%d %H:%M") print("AAAAAA DATA:", data) Ficha.objects.filter(autor=user.id).update(fecha_creacion=date_time, autor=user, nombre=data["nombreFicha"], descripcion=data["descripcionFicha"]) ficha = Ficha.objects.filter(autor=user.id).last() recintos = Recinto.objects.all() productos = Producto.objects.all() estandar_productos = EstandarProducto.objects.all() cotizaciones = Cotizacion.objects.all() detalles_ficha = [] for detalle in data["detalles"]: recinto = recintos.get(id=detalle[1]) producto = productos.get(id=detalle[10]) estandar_producto = estandar_productos.get(id=detalle[9]) try: cotizacion = cotizaciones.get(id=detalle[4]) except ObjectDoesNotExist: cotizacion = None print("Fecha: ", detalle[8]) detalle = DetalleFicha(carreras=detalle[0], recinto=recinto, nombre=detalle[2], cantidad_a_comprar=detalle[3], cotizacion=cotizacion, valor_unitario=detalle[5], valor_total=detalle[6], documento=detalle[7], fecha_cotizacion=detalle[8], estandar_producto=estandar_producto, producto=producto, ficha=ficha) detalles_ficha.append(detalle) DetalleFicha.objects.bulk_create(detalles_ficha) print("Array convertida", detalles_ficha) print(detalles_ficha[0]) return Response(status=status.HTTP_200_OK) -
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17) for Python venv
I'm having trouble setting up my database on Django. I am running my server on CentOS7 and although I downloaded the version of SQLite I wanted to use, Python keeps pointing to the preinstalled version that is not compatible with my version of Django. I've looked through the other questions that had the same problem as me: django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17)) How to use the latest sqlite3 version in python https://number1.co.za/upgrading-sqlite-on-centos-to-3-8-3-or-later/ But the thing that differs between all of these problems and mine is that I used the Python Manager that comes with aaPanel to install my version of Python (3.8.3) which creates a virtual environment for the version of Python that I'm using whereas the others download and compile it from the source. I have tried finding where the correct configure file (as I have found multiple that were not helpful) that is outlined in each of the answers to these questions could be, but to no avail. How could I go about pointing my version of Python to the up-to-date version of SQLite that I have installed? -
Getting "Authentication credentials were not provided" error when I don't want to require authentication
I have a project with JWT authentication in Django Rest Framework. Usually I require user to be authenticated but in the case of GET action (both list and retrieve) I would like everyone to be able to access it with no authentication required. The code for this functionality is very simple: class GetUserViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin): # allowed for everyone serializer_class = UserSerializer permission_classes = [permissions.AllowAny] queryset = User.objects.all() The permissions are set to allow any but there is probably some inconsistency with default auth class in Settings.py # --------------------------REST-framework-------------------------- REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } The last thing that could matter are my endpoints: urlpatterns = [ path("", UserViewSet.as_view({"post": "create"}), kwargs={'quantity': 1}), path("<int:quantity>/", UserViewSet.as_view({"post": "create"})), path("", GetUserViewSet.as_view({"get": "list"})), path("<int:pk>/", GetUserViewSet.as_view({"get": "retrieve"})), path("<int:pk>/", UserViewSet.as_view({"put": "update", "delete": "destroy"})), ] What I don't understand is that in other app where I have register functionality there is no such an error. I will show you this viewset: class ApiUserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer_class = ApiUserSerializer permission_classes = [permissions.AllowAny] queryset = ApiUser.objects.all() @extend_schema(request=ApiUserSerializer, responses=TokenSerializer) def create(self, request, *args, **kwargs): api_user_serializer = self.get_serializer(data=request.data) api_user_serializer.is_valid(raise_exception=True) api_user = api_user_serializer.save() refresh = RefreshToken.for_user(api_user) token_serializer = TokenSerializer( data={ "access": str(refresh.access_token), "refresh": str(refresh) } ) … -
Django-allauth: My post-sign-up redirect flow with Google Auth is broken and I can't figure out why
I integrated django-allauth with my Django app but something is not fully working: Problem If a user that does not have an account in my DB tries to sign-up using the the google allauth process, after the authentication process it is sent to the home page (behind login filter) successfully. However, if a user that already has an account in my DB (manually created) tries to login using the google auth by visiting /accounts/google/login/, after the authentication process it is sent to /accounts/social/signup/ (a weird page that django-allauth has). Funny enough thought, the user is logged in and if they try to access the home page they can and everything works. So it's just the redirect that is broken. I narrowed it down to the fact that the user's email already exist BUT there is no social account associated. Setup I have a custom user model where email is the main unique id of a user. from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create … -
Django Heroku Porting
Trying to set up Django configurations for a public url. So I ran this first. $ echo "web: python manage.py runserver 0.0.0.0:\$PORT" > Procfile $ git add Procfile $ git commit -m "Specify the command to run your project" In Procfile: web: python manage.py runserver 0.0.0.0:\$PORT release: python manage.py migrate In settings.py: PORT = os.getenv("PORT", default="5000") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["url"] In env.: PORT=5000 SECRET_KEY=value Was using the above commands and got (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku config:get PORT 5000 (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 3:08:10 PM web.1 | CommandError: "0.0.0.0:\$PORT" is not a valid port number or address:port pair. [DONE] Killing all processes with signal SIGINT 3:08:10 PM web.1 Exited with exit code null I also used $PORT without the backslash and $. How would I proceed from here to make the public url working. -
Django FileField auto urlencoding problem
image_file = models.FileField(storage=s3, max_length=512, blank=True) I have a model with theis image_file field backed by s3 storage. The only problem I have with this field is if the filename contains any url-encode-able characters, it will auto encode the filename. For example, if the filename contains %40, when retrieve the value from the model, it becomes %2540. I wonder if there is a switch I can turn this feature/bug off.