Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best practice to pass F401 (imported but unused) from flake8 with django?
I have a django-project. Typical structure of an app is: admin views models __init__.py foo.py bar.py init.py from .foo import FooModel from .bar import BarModel I am new in linters and tried wemake-python-styleguide Question: should I ignore the error F401 or add all=[...] or mark #noqa or add init.py to per-file-ignores in setup.cfg? -
Pruning PostgreSQL Tables and Store in JSON files
For my Django application I am using PostgreSQL and there are tables to store log entries such as Webhook events, email logs etc. I would like to keep these event logs only for 30 days and move the older logs to JSON file stored in Google Storage Bucket. Is there any recommended way to do this operation on a periodic basis? Essentially I would like to prune old records and store them in a JSON file periodically. -
How To Create Social Application Tokens With Django
I'm Successfully With This Tutorial : https://www.section.io/engineering-education/django-google-oauth/ In this tutorial, she's created how to login with google. I Just Started To Learn Back End With Django, And i Want to send this data with django rest api. My Friend is Front End and he need my user data. He said create the tokens. Im Confused to create the tokens. And i see in the table there is a name "Social Application Tokens". My Question is: How To Create Social Application Tokens Automaticly when user login with Google?, And Whats the tools to create that ? -
request.POST does not contain clicked button information
This is the code I have in forms.py class RsaForm(forms.Form): primeP = forms.IntegerField(label='Prime number (p)', required=True) primeQ = forms.IntegerField(label='Prime number (q)', required=True) clearText = forms.CharField(label='Cleartext', widget=forms.Textarea, required=False) cipherText = forms.CharField(label='Ciphertext', widget=forms.Textarea, required=False) And this is the code I have in views.py that I am using with my template rsa.html def rsaView(request): # if this is a POST request we need to process the form data if request.is_ajax and request.method == 'POST': # create a form instance and populate it with data from the request: form = RsaForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required pParam = form.cleaned_data['primeP'] qParam = form.cleaned_data['primeQ'] cleartextParam = form.cleaned_data['clearText'] ciphertextParam = form.cleaned_data['cipherText'] print(request.POST) pubkey, privkey = rsa.gen_keys(pParam, qParam) if 'encryptinput' in request.POST: # Encriptacion RSA print('Encriptado.') ciphertext = rsa.encrypt(cleartextParam, pubkey) return JsonResponse({"ciphertext": ciphertext}, status=200) elif 'decryptinput' in request.POST: # Desencriptacion RSA print('Desencriptado.') cleartext = rsa.decrypt(ciphertextParam, privkey) return JsonResponse({"cleartext": cleartext}, status=200) else: return JsonResponse({"error": "Hubo un error."}, status=200) else: print("Invalid form.") # if a GET (or any other method) we'll create a blank form else: form = RsaForm() thisCryptosystem = Cryptosystem.objects.get(name="RSA") template = loader.get_template('cryptogyapp/rsa.html') context = { 'thisCryptosystem': thisCryptosystem, 'form': form } return HttpResponse(template.render(context, request)) And this is my … -
How to compute unified diff in queryset order in django template
[statistic.html] test: {% for h in research.history %} {% ifchanged h.summary_json.field_summary.teacher %} {% if h.summary_json.field_summary.teacher|length > 0 %} {{ h.summary_json.field_summary.teacher|after_teacher }} {% endif %} {% endifchanged %} {% endfor %} test: ['who'] ['Haily', 'mark'] ['Haily'] ['Haily', 'mark'] ['Haily', 'Aden'] I am trying to combine the results of 5 querysets into (1,2) (2,3) (3,4) (4,5) and print the comparison values of the results of the queryset using unified_diff of the difflib module. example) +++ @@ -1,2 +1,2 @@ Haily -mark +Aden I would appreciate it if you could tell me how to apply them in order. [teampltetag.py] def compare_teacher(v1, v2): for diff in difflib.unified_diff(v1, v2): return str(diff) [statistic.html] {% compare_teacher ?? ?? %} -
Django Admin error referencing wrong column in ForeignKey
I've setup a relationship using django's ForeignKey against 2 unmanaged tables like so: class Product(BaseModel): publish_name = models.CharField(unique=True, max_length=40) # this works: associated_country = models.ForeignKey('geonames.Countryinfo', models.DO_NOTHING, db_column='published_country', blank=True, null=True) # this doesn't: associated_continent = models.ForeignKey('geonames.Continentcodes', on_delete=models.DO_NOTHING, db_column='published_continent' blank=True, null=True) class Meta: managed = True db_table = 'product' class Continentcodes(models.Model): code = models.CharField(max_length=2, primary_key=True, unique=True) name = models.TextField(blank=True, null=True) geoname_id = models.OneToOneField('Geoname', models.DO_NOTHING, blank=True, null=True, unique=True) class Meta: managed = False db_table = 'geoname_continentcodes' class Countryinfo(models.Model): iso_alpha2 = models.CharField(primary_key=True, max_length=2) country = models.TextField(blank=True, null=True) geoname = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True) neighbours = models.TextField(blank=True, null=True) class Meta: ordering = ['country'] managed = False db_table = 'geoname_countryinfo' verbose_name_plural = 'Countries' I've written some unit tests that pass for inserting and retrieving the foreign key values for the Continentcodes and Countryinfo relationships in the Product model, but when I go to edit an entry in the django admin interface I see this: The above exception (column geoname_continentcodes.geoname_id_id does not exist LINE 1: ...ntcodes"."code", "geoname_continentcodes"."name", "geoname_c... ^ HINT: Perhaps you meant to reference the column "geoname_continentcodes.geoname_id" It looks like it's trying to reference geoname_continentcodes.geoname_id_id for some reason. I have tried adding to='code' in the ForeignKey relationship, but it doesn't seem to effect anything. Additionally, the … -
Factory Boy not correctly generating one to one relationship
I have two factories. class ProfileFactory(DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory(UserFactory) id = Faker('uuid4') first_name = Faker('first_name') last_name = Faker('last_name') class UserFactory(DjangoModelFactory): id = Faker('uuid4') email = Faker('email') password = Faker('password') class Meta: model = User These correspond to a couple models: class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Profile(UUIDModel): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=25, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) I would like to be able to call ProfileFactory() and a profile and user be generated. However I am currently getting an error: users.models.User.profile.RelatedObjectDoesNotExist: User has no profile. How do i correctly create both items? -
Add to cart button doesn't respond
I've been implementing new features to an e-commerce site and suddenly the "Add to cart" button stopped working. When the user clicks the "Add to cart" button, the site sends an "add" request into the views.py file and all the logic happens here: views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) store.html {% block content %} ................................ <div class="row"> {% for product in products %} <div class="col-lg-3"> <hr style="width:0"> <img class="thumbnail" src="{{ product.imageURL }}" style="border-radius: 15px;" alt=""> <div class="box-element product" id="box_product_element"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-action="add" class="btn btn-outline-success add-btn update-cart" style="border-radius: 10px;">Add</button> <a class="btn btn-outline-secondary" href="{% url 'product-detail' product.category.slug product.slug%}" style="border-radius: 10px;">View</a> <h4 style="display: inline-block; float: right"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} </div> ............................... {% endblock content %} When the user clicks the button, the site is not refreshing, therefore there must be a problem with sending the request from HTML? Please, help me to fix it. -
Django: Keeping the latest row for rows that have the same value in a column
So right now I have a table that is similar to: | ID | NAME | Date| |---------|------|---| | 1 | BOB | 2007| | 2 | BOB | 2007| | 3 | BOB | 2008| and I want to remove the first two and keep the third row. I've tried using distinct() with order_by() but it only seems to remove one one of the first two rows. -
DRF - How do you include foreign data within a Serializer?
I have a Model that looks a bit like this: class Foo(models.Model): data = models.ForeignKey(Data, on_delete=models.CASCADE) source = models.ForeignKey(Source, on_delete=models.CASCADE) # other fields... In this case I'd like to show the full models for data and source, rather than just their IDs. I also need data to be read-only as it's generated automatically. My Serializer looks like this: class FooSerializer(serializers.ModelSerializer): data = DataSerializer(read_only=True) source = SourceSerializer() class Meta: model = Foo fields = ["data", "source"] read_only_fields = ["data"] What I don't quite understand is: Why isn't data read-only, like it would be if it were a "normal" serializer field? How can I say "save a new source if an identical one doesn't exist already?" -
Celery unregistered task with Django and RabbitMq
I am getting the following message when implementing Celery with Django and RabbitMq [2022-04-07 00:05:10,310: ERROR/MainProcess] Received unregistered task of type 'callservices.celery.send_user_mail'. The message has been ignored and discarded. I have followed all the configuration steps, which I show below in each file within the Django directory, but I have not been able to find the problem. Why does it mention that the task is not registered? celery.py from celery import Celery from django.core.mail import EmailMultiAlternatives, send_mail os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'callserviceapp.settings') app = Celery('callserviceapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task() def send_user_mail(randomNumber, email): print("hola") subject = 'Some subject' body="Some body" send_mail(subject, body,'xxxxx.ssmtp@gmail.com', [email],fail_silently = False) return 1 init.py # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from celery import app as celery_app __all__ = ('celery_app',) setting.py INSTALLED_APPS = [ 'sslserver', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'callserviceapp.apps.CallserviceappConfig', ] CELERY_BROKER_URL = 'amqp://localhost' -
How many database calls does Django make with foreign key relations?
I have a model "Model_A" with foreign key field "fk" to model "Model_B". When serializing model "Model_A", I am trying to get 2 fields from model "Model_B" but I want to make 1 database call. class Model_B(models.Model): f1 = models.Charfield() f2 = models.Charfield() f3 = models.Charfield() class Model_A(models.Model): fk = models.Foreignkey(Model_B, on_delete=models.CASCADE) Does the following code make 1 or 2 database calls? ma = Model_A.objects.get(pk=1) return { 'f1': ma.fk.f1, 'f2': ma.fk.f2, } Or would the following make more sense? mb = Model_A.objects.get(pk=1).fk return { 'f1': mb.f1, 'f2': mb.f2, } -
Django: How to convert indexed QueryDict into array of QueryDicts?
I am handling a POST request and I receive in request.data the following data structure: <QueryDict: {'document[0]name': ['sample-0.pdf'], 'document[0]folder': ['folder-0'], 'document[1]name': ['sample-1.pdf'], 'document[1]category': ['file'], 'document[1]folder': ['folder-1']}> How can I convert this to the following data structure: [<QueryDict: {'name': ['sample-0.pdf'], 'folder': ['folder-0']}>, <QueryDict: {'name': ['sample-1.pdf'], 'category': ['file'], 'folder': ['folder-1']}>] -
How to add column with drop-down list on Django admin change list template?
I have a TaskRequest model that contains column named 'owner'. This column contains users from group named 'owners'. I want to have an option to select users directly from change list view without clicking on task name. How can I implement a drop-down list so it is visible in the table in my TaskRequest app. Do I really need to overwrite admin template or there is another way to do that? -
Using React with Django to render stars on the page
I am developing manga website which has star rating for each manga. I am using React (which I'm very very new to) with Django. I render div with class stars with id which corresponds to number of stars this manga has. After that Corresponding number of stars must be rendered on webpage with react code. {% block script %} <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> {% endblock %} {% for manga, rating in mangas %} <script type="text/babel"> function Apicall(props) { console.log((props.value)) return Render_rating(props.value) }; function Render_rating(props) { for (var i = 0; i = parseInt(Math.round(props)); i++) { return Render_stars() } } function Render_stars() { return ( <img src="static/mangas/fullstar.png"/> ) } console.log(document.querySelector(".stars").id) ReactDOM.render(<Apicall value={document.querySelector(".stars").id} />, document.getElementById('app')) </script> <div id="manga"> <a href="{% url 'manga' manga.id %}"> <div class="stars" id="{{ rating }}"></div> <div id="app"></div> <h1>{{ manga.title }}</h1> <img src="{{ manga.image.url }}"> <br/>{% for genre in manga.genre.all %}{{ genre }}<br/>{% endfor %} {{ manga.Description }} </a> </div> {% endfor %} I understand that there are many issues with my react code. document.querySelector(".stars").id always renders number 0. Also I want to know about more elegant way to structure react code with Django. I am very new to it so... -
Updating profile picture through serializer
I cannot update a profile image on my extended user model. Here is my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city', allow_blank=True, required=False) country = serializers.CharField(source='profile.country', allow_blank=True, required=False) profile_pic = serializers.ImageField(source='profile.profile_pic', use_url=True, required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic'] # fields = UserDetailsSerializer.Meta.fields + ('city', 'country') extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}, 'profile_pic': {'required': False} } def update(self, instance, validated_data): profile_data = validated_data.pop('profile', {}) city = profile_data.get('city') country = profile_data.get('country') profile_pic = profile_data.get('profile_pic') instance = super(UpdateUserSerializer, self).update(instance, validated_data) profile = instance.profile if profile_data: if city: profile.city = city if country: profile.country = country if profile_pic: profile.profile_pic = profile.profile_pic profile.save() return instance When I try to update this image with a new image I do not get any error messages however the image is not updated (image remains the same). -
makemigrations results in django.db.utils.OperationalError: no such column: (Python 3.10 and Django 4.0.3)
First, and this is really important, this error is being returned WHEN I run python manage.py makemigrations (Python 3.10 and Django 4.0.3) In my research of the many instances of this error I've seen that as the first suggestion for this particular error message. I repeat, this issue is NOT going to be solved with the answer, just run python manage.py makemigrations The error I get when adding a new field and running makemigrations is: django.db.utils.OperationalError: no such column: events_eventsetting.timezone_aware_venues OK, now for some additional details. This is not my first Django project. I've been building some solid apps and am very comfortable with adding fields to models. Many, many times, I've done the following without a hitch...until a few days ago Add a new syntactically correct field run 'python manage.py makemigrations' run 'python manage.py migrate' And that's being going very well until a couple of days ago. For additional context, I have not changed the virtual environment in anyway - the requirements.txt file has the exact same contents. I have also added no apps or made any changes to settings.py. When working on a project with about 10 tables and over 200 columns across the DB a few days … -
Any simple alternative to default_if_none that can also handle '0' value?
I am running the following command to filter out empty values in my template: {{ product.error_value1|default_if_none:"--" }} This works well for Null Values but doesn't work if the value entered is "0". I wish the command 'default_if_null' existed. This way it would only check for null. Any suggestions on an alternative? -
calculating percentages on a field in Django
I have the model below and I am trying to calculate the percentages of product quantities. Any help would be greatly appreciated. Thanks model.py class Stock(models.Model): date = models.DateField(default=now) product = models.CharField(max_length=100, null=True, unique=True) quantity = models.IntegerField(default='0') view.py total= Stock.objects.aggregate(total_vote=Sum('quantity')) per = Stock.objects.values('quantity') percentage = [ {'quantity': p['quantity'], 'percentage': p['quantity'] * 100 /total} for p in per ] -
How to add multiple attachments in mail in django
i have multiple file fields form and i want to send all field file to one email in django. kindly suggest. email code: def sendEmail(request): message = "hello world" subject = "Test" mail_id = "customer@example.com" email = EmailMessage(subject, message, EMAIL_HOST_USER, [mail_id]) email.content_subtype = 'html' doc1 = request.FILES['detail_sheet'] doc2 = request.FILES['photo'] doc3 = request.FILES['id_proof'] doc4 = request.FILES['address_proof'] doc5 = request.FILES['company_id_card'] doc = [doc1,doc2,doc3,doc4,doc5] for f in doc: file = f email.attach(file.name, file.read(), file.content_type) email.send() -
Django - Input boxes not styling properly when inheriting from base.html
I am creating a simple login page using Django & Tailwind.css. My form was styling fine until I inherited a <nav> from base.html. When I did so, gray borders started appearing around my input boxes and the input boxes got slightly bigger. The original layout: The new layout (with base.html being inherited): I'm not sure why this is occurring, because all of the code remains the same, I am just {% extends "base.html" %} at the top of my login.html Here is my base.html code (contains the navar & responsive navbar): <!DOCTYPE html> <html class="screen-top"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock %}</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://shuffle.dev/vendor/icons/css/fontello.css?v=h7b" id="bs-base-css"> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="css2?family=Poppins:wght@400;500;600;700&display=swap"></style> <link rel="stylesheet" href="https://shuffle.dev/static/build/css/shuffle-preview.3a553ecf.css"> <link rel="stylesheet" href="https://unpkg.com/flowbite@latest/dist/flowbite.min.css" /> <script src="https://shuffle.dev/vendor/tailwind-flex/js/main.js"></script> <script src="https://cdn.tailwindcss.com"></script> {% block css %} {% endblock %} </head> <body id="page" class="antialiased font-body bg-body text-body bg-[rgb(248,250,251)]"> <!-- NAVBAR --> <div class="" id="content"> <section class="relative overflow-hidden"> <nav class="flex justify-between p-6 px-4" data-config-id="toggle-mobile" data-config-target=".navbar-menu" data-config-class="hidden" style="background-color: #2a3342;"> <div class="flex justify-between items-center w-full"> <div class="w-1/2 xl:w-1/3"> <a class="block max-w-max" href="{% url 'home' %}"> <img class="h-8" src="https://i.ibb.co/LRCrLTF/Screenshot-2022-04-03-140946-removebg-preview.png" alt="LOGO" data-config-id="auto-img-1-2" style="transform: scale(2); padding-left: 30px"> </a> </div> <div … -
Type checking between Python classes and JavaScript objects (Django with Vue)
I have a project that has a Python (django) backend and a (mostly) Vue frontend. I render forms with Django html templates instead of Vue, but would like to migrate the forms so that everything frontend is Vue. I want to implement some sort of type checking system that could throw linting errors if I try to create object properties in the frontend that don't match the form data object that exists in the backend. However, I have no idea how to do this given I'm going from Python to Javascript - or if it's even possible to typecheck a JS object from a Python class. I've seen this in Typescript + React, where the props object used to persist the controlled form's state is typed with the backend object. That way, if you tried to add a property to the object in the frontend that wasn't included in the backend model, you'd immediately get a linting error. But that works bc you're working in the same language. Any ideas on how to do this between languages? Maybe an intermediate step with a script to build JS models from the Python classes? -
How can I pass an id to route in Django?
I'm new with Django. Started learning it for 4 days now. I have an issue and I don't know how to solve it. I've searched high and low on Google, but I couldn't understand much from the solutions provided. Here is the issue: I've created models and views for the app I've created the database with all tables needed. In them I have 2 foreign keys which link between two tables In the html, I need to show only the information linked to the foreign key.(eg. I have a webpage in which I have all the countries. When I click on Argentina, I want only Argentina's provinces to be shown) Where and what do I need to do in order for it? Again, I've searched high and low on Google, because I don't think is something that complicated. But everything I found didn't solve my request. -
i'm getting this following error what should i do
Error during template rendering In template C:\Django-Project\resume\core\templates\core\home.html, error at line 1 core/base.html 1 {%extends 'core/base.html'%} -
A single field not showing up when using inlineformset_factory for multiple forms
I'm writing a django webapp that allows me to create orders for customers. I've used inlineformset_factory so that I can create multiple forms in my bootstrap template. Everything loads well, I get 10 forms I can fill out, however the ONLY field it is not loading is the customer field to choose from the drop down menu. Before I changed it to using the inlineformset_factory, the single form loaded fine with all the fields. So i dunno why this is happening. But then even when I submit the form regardless of the customer field appearing I get an error Anyone know why? createOrder from views.py As you can see the fields I want are 'date', 'client', 'customer', 'country', 'product' but only the customer is not showing up! Iget 10 forms but all without customer. def createOrder(request): OrderFormSet = inlineformset_factory(Customer, Order, fields=('date', 'client', 'customer', 'location', 'product'), extra=10 ) formset = OrderFormSet() #form = OrderForm() if request.method == 'POST': formset = OrderFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('/') context = {'form':formset} return render(request, 'accounts/order.html', context) Customer model from models.py: class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) location= models.CharField(max_length=200, null=True, choices=LOCATION) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): …