Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create forgot password using email OTP in django
In my project I have created custom user model and use default forgot password method it forgot password via link but I need to change it, how to forgot password using OTP method -
Timeout server-side while exporting data
I built a website with Django/Python server-side and jQuery client-side. I have an Export Page on my website where there is a link to confirm that links to a view/python function that performs several long operations. At the beginning I had a timeout client-side problem that I simply solved $.ajaxSetup({ type: 'POST', timeout: 300000, ... setting the timeout var into $.ajaxSetup. So far once the request via Ajax is done I show a loading image into a DIV and the user knows he has to wait until file is done. However, for very long server-side operations I end up getting Bad gateway response on NGinx and a timeout on testing server. How would you handle this problem in the easiest way possible? I can't send an email with a file link and I want to preserve the UX where the user clicking the link gets its export file . I am on my own server with my own NGinx so I can eventually work on server-side too if nothing can be done via django/python. Thank you. -
Facing routing error on running my application
Iam facing this error on running my django application. I tried developing a chat app. Iam facing some issues regarding routing. HTTP GET /chat/ 200 [0.06, 127.0.0.1:33094] HTTP GET /chat/jkhkjk/?username=jkjk 200 [0.04, 127.0.0.1:33094] WebSocket HANDSHAKING /ws/jkhkjk/ [127.0.0.1:33104] WebSocket CONNECT /ws/jkhkjk/ [127.0.0.1:33104] urls.py from django.contrib import admin from django.urls import path, include from .views import * from app import views urlpatterns = [ path('', home, name='home'), path('student/', student, name='student'), path('logout/', logout, name='logout'), path('signup/', signup, name='signup'), path('volunteer/', volunteer, name='volunteer'), path('chat/',index, name='chat'), path('chat/<str:room_name>/', room, name='room'), ] routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), # Using asgi ] -
Django graphql auth failing and user getting disabled
In my project I am using django graphql auth as shown in below link https://django-graphql-auth.readthedocs.io/en/latest/quickstart/ When I tried to run updateAccount with below query, mutation MyMutation { updateAccount(lastName: "John"){ success errors } } It shows response as, { "data": { "updateAccount": { "success": false, "errors": { "userId": [ { "message": "This field is required.", "code": "required" } ] } } } } Which shows userId is required. Then I pass the userId to the same, mutation MyMutation { updateAccount(userId: "8c8b1c0c-9460-4930-b263-1c0776f86d63", lastName: "John"){ success errors } } First request was successful however same request sent again has failed. { "errors": [ { "message": "User is disabled", "locations": [ { "line": 2, "column": 3 } ], "path": [ "updateAccount" ] } ], "data": { "updateAccount": null } } An error occurred while resolving field Mutation.updateAccount Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/graphql/execution/executor.py", line 452, in resolve_or_error return executor.execute(resolve_fn, source, info, **args) File "/usr/local/lib/python3.10/site-packages/graphql/execution/executors/sync.py", line 16, in execute return fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/graphql_jwt/middleware.py", line 72, in resolve user = authenticate(request=context, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 42, in sensitive_variables_wrapper return func(*func_args, **func_kwargs) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 76, in authenticate user = backend.authenticate(request, **credentials) File "/usr/local/lib/python3.10/site-packages/graphql_jwt/backends.py", line 14, in authenticate return get_user_by_token(token, request) File "/usr/local/lib/python3.10/site-packages/graphql_jwt/shortcuts.py", line 21, … -
Django model manager queryset not updating until server restarts
I have a program that lets users upload data files and lookup tables (both which are ID'd to a specific company) and map them together. One page lets users choose which company they want to map data for by looking at which companies have both data files and lookup tables, which I use a queryset/model manager for. The problem is if I load a new data file and hierarchy the queryset doesn't pick them up until the server restarts. The queryset returns all the companies that have a data file and hierarchies at the time the server starts, but not anything that's added afterwards. I think this must be because the queryset is defined at startup, but I'm not sure. Is there a way to work around this? forms.py class CompanySelectionForm(forms.Form): companies = RawData.objects.get_companyNames(source="inRDandH") companiesTuple = makeTuple(companies) print(companiesTuple) company = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-select'}), choices=companiesTuple) managers.py class RawDataManager(models.Manager): def get_queryset(self): return RawDataQuerySet(self.model, using=self._db) def get_companyNames(self, source): return self.get_queryset().get_companyNames(source) class RawDataQuerySet(models.QuerySet): def get_companyNames(self, source): if (source == 'inRDandH'): distinct_companiesRD = self.filter(fileType=0).values_list('companyName', flat=True).distinct() distinct_companiesH = self.filter(fileType=1).values_list('companyName', flat=True).distinct() distinct_companies = set(distinct_companiesRD).intersection(set(distinct_companiesH)) else: distinct_companies = self.values_list('companyName', flat=True).distinct() return distinct_companies -
I'm trying to input data, save it and display it in my view page. I'm not sure what I'm missing
I'm writing a simple product input app, where a user can input their product details, save it in the database and view it in another page. Everything seems to be going fine, no error messages when I run the server. However, when I put in the product details and submit, the page just refreshes and all the information disappears. Nothing shows up in the product list page. I've read a couple articles but not sure what exactly I'm missing. It seems like I've hit an invisible wall. Please assist. Thank you forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['SKU', 'Category','Name', 'Platform', 'Price','Discount', 'Date','Cost'] widgets = { 'SKU': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'SKU' }), 'Category': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'Category' }), 'Name': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'Name' }), 'Platform': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'Platform' }), 'Price': forms.NumberInput(attrs={ 'class': 'form-control', 'id': 'Price' }), 'Discount': forms.NumberInput(attrs={ 'class': 'form-control', 'id': 'Discount' }), 'Date': forms.DateInput(attrs={ 'class': 'form-control', 'id': 'Date' }), 'Cost': forms.NumberInput(attrs={ 'class': 'form-control', 'id': 'Cost' }), } views.py # Product views @login_required(login_url='login') def create_product(request): forms = ProductForm() if request.method == 'POST': forms = ProductForm(request.POST) if forms.is_valid(): forms.save() return redirect('product-list') context = { 'form': forms } return render(request, 'store/create_product.html', context) class ProductListView(ListView): … -
How can I create a model entry from a search result in Django?
I hope this doesn't get overcomplicated, I'll try my best to keep it streamlined. I'm trying to put the results from querying an external database to populate fields in my model. Think of it as having a local library and asking the user for an ISBN, and getting the author, genre, etc from Amazon, and then storing it in my db. The flow of what I'm trying to accomplish is: Show the user a search field > get the query (this will be a unique ID) > call an external script with that query, pull the data of the one entry > break down the data to match the form fields (dict?) > pre fill form > show user the pre filled form to review > user submits (or doesn't). I know how to make a functioning search that looks in MY db for stuff and returns a list template with the context, and I know how to make a CreateForm for the user to input an entry manually, but not how to mix them, or how to even add stuff to the context if I wanted to. The back and forth of context data in django between templates and … -
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?