Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Country State City Chained Dropdown
Configuration: I have created 2 apps csc and members. CSC: contains country, state, city and Users contains a custom user model. The users model using foreign keys to access country, state and city from CSC app. The CSC database contains all the countries, states, cities. And i am displaying user list in fronend and also an option to filter the content by country, state, city by django-filter. I am using django smart_selects to chain them in admin. Question: I wanted to show only those countries, states and cities, which has the members not all my country database. and also i wanted to link those 3 dropdowns. CSC - Models.py class Country(models.Model): name = models.CharField(_('Country'), max_length=255, null=True) country_code = models.CharField(_('Code'), max_length=10, null=True) iso_code_short = models.CharField(_('ISO Code Short'), max_length=2, null=True) iso_code_long = models.CharField(_('ISO Code Long'), max_length=3, null=True) def __str__(self): return self.name class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(_('State'), max_length=255, null=True) def __str__(self): return str(self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) state = ChainedForeignKey('State', chained_field="country", chained_model_field="country", show_all=False, auto_choose=True) name = models.CharField(_('City'), max_length=255, null=True) def __str__(self): return str(self.name) Members - models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('Email'), max_length=255, unique=True) first_name = models.CharField(_('First Name'), max_length=100, null=True, blank=True) last_name = models.CharField(_('Last Name'), … -
Django - Sending POST request to another webiste - lack of headers
I'm currently struggling to integrate third-party payment system with my django website. When sending POST request along with form data to payment site it responds with an 403 Forbidden error - CSRF verification failed. You are seeing this message because this HTTPS site requires a 'Referer header' to be sent by your Web browser, but none was sent.. I've installed cors_headers, configured it as suggested in documentation and set CORS_ALLOW_ALL_ORIGINS temporarily to True. When inspecting network tab I've noticed that when requests are within same domain requests are included: same-origin-headers But when sending POST request to the third-party site, they are not: cross-origin-headers I'm including my django view as well as html form: Django view: def payment_loading(request): if request.method == 'GET': order = Order.objects.get(session=request.session.session_key) context = { 'order': order, } return render(request, 'payment_loading.html', context) HTML form: <h1>Processing payment</h1> <form name="dotpay_post" action="https://ssl.dotpay.pl/test_seller/" method="POST"> {% csrf_token %} <input name="api_version" value="{{ order.dotpay_object.api_version }}" type="hidden"> <input name="id" value="{{ order.dotpay_object.shop_id }}" type="hidden"> <input name="amount" value="{{ order.dotpay_object.amount }}" type="hidden"> <input name="currency" value="{{ order.dotpay_object.currency }}" type="hidden"> <input name="description" value="{{ order.dotpay_object.description }}" type="hidden"> <input name="control" value="{{ order.dotpay_object.control }}" type="hidden"> <input name="url" value="{{ order.dotpay_object.url }}" type="hidden"> <input name="type" value="{{ order.dotpay_object.type }}" type="hidden"> <input name="urlc" value="{{ order.dotpay_object.urlc }}" type="hidden"> <input … -
How to integrate worldpay payment gateway with django app?
I am trying to integrate worldpay payment gateway into my django app. In their documentation there is only cURL provided for reference. Can anyone help me how to get started with it using python requests or urllib module? -
django complete email verification
before this question is going to be marked as a possible duplicate, I want to address a few things. I want to make sure that users have a single email field called email. They also have an is_verified field to indicate whether the email has been verified. There are a few pitfalls in most of the email verification implementations. Lets say that an user creates an account and has an unverified email. Lets say that the user does not actually own the email, though. Now, the actual owner of the email enters the site. But, as the email is already saved in the database, we get an integrity error - that the email is already in use. Thus, any scammer can enter a random email and claim it. This reduces the user experience. How can this be avoided so as to provide a complete email verification system? ( One where the actual owners can claim their emails) thanks a lot! -
django message alert exit button doesn't work
I'm new in django. I try to use the message alert to highlight the succes in posting new item to the display. Alert window includes exit button 'x' to dismiss alert. Message window works but the exit button doesn't and I can't figure out why. My html: {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> {{message }} </div> {% endfor %} {% endif %} My viev: from django.contrib import messages ... ... messages.success(request,('Succes')) Can you tell me, why it doesn't work? -
Django: Is there a way to manually order objects in a ManyToManyField?
Here is my models.py: from django.db import models class Photo(models.Model): file = models.ImageField(upload_to='images') class Album(models.Model): photos = models.ManyToManyField(Photo,related_name="photos",blank=True) admin.py from .models import Photo, Album class AlbumAdmin(admin.ModelAdmin): filter_horizontal = ("photos",) admin.site.register(Photo) admin.site.register(Album, AlbumAdmin) Is there some way to manually order the models in the filter_horizontal, or do I just have to do all that in the views.py using python? -
i have treid writing calc in place of . but still it show theres no package named calc
enter image description here please help I am not able to continue my Django tutorial -
Why is my Django server not running after following all instructions properly?
I am a beginner learning Django. I've been watching this video on free code camp and it is teaching me to make a uro shortner. However, even after following exact steps my Django server isn't starting to run. Do help -
Is the a way in which I can integrate whatsApp Order in my django ecommerce website
Am creating a django ecommerce website and I want to add an option where users can checkout through whatsapp. I want them to be able to send all their orders to the admin's whatsapp. Anyone who can help me -
How to implement Django-private-chat2?
Has anyone used Django-private-chat2? I am struggling to find a tutorial on this as no documentation is available. Please tell how to implement it? -
I am new to python and This is the TypeError:'<=' not supported between instances of 'datetime.datetime' and 'module'
import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("Date published!!!") def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now -
how to make text stay after the search has been made
I have a serch field on my page <form method="GET" class="container mb-5"> <input type="search" class="form-control rounded" placeholder="Write a name" aria-label="Search" aria-describedby="search-addon" name="search"/> <button type="submit" class="btn btn-outline-primary px-5" >Search</button> </form> And here is my views def my_view(request): value_one = request.GET.get("search", None) objects = MyModel.objects.all() if value_one: objects = objects.filter(field_one=value_one) After I input something in a search field and push the button 'search', text which was in search field dissapears, I want it to stay until the next input. Is it possible to do with Django or not? Don't even know how to google it, everything I found was on different topic -
How to automatically update a page without refreshing in django?
I am creating a website using Django on the stock market. I am fetching the live stock market data from an API. I want to update the live price of a stock every 5 seconds (which is given by the API). How can I do this without refreshing the page? I found that Ajax is very helpful for this but I am not being able to implement this properly. Thus, can someone please give an example of the code which is required in the html page to update the values using Ajax. I was thinking of using a separate URL which could send the data in a JSON format. Please help me out if possible. -
Post request Manytomany field DRF with postman
Objective: Creating a new entry in database from Postman using the "POST". I am trying to send the data from Postman and I am using nested serializing. I have changed the create method i have shared the snippet below. Also, I tried this solution but it did not work. Can someone please point out the mistake I am making? When I am trying to post as form-data the error is {"magazine":["This field is required."]}. When I am trying to post it as raw data the error is Direct assignment to the forward side of a many-to-many set is prohibited. Use magazine.set() instead. Here is my models: class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey('authors.Author', on_delete=models.CASCADE) magazine = models.ManyToManyField('articles.Magazine') def __str__(self): return self.title class Magazine(models.Model): name = models.CharField(max_length=30) title = models.CharField(max_length=100) def __str__(self): return self.name This is my serializers: class MagazineSerializer(serializers.ModelSerializer): class Meta: model = Magazine fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer(read_only=True, many=False) magazine = MagazineSerializer(many=True) class Meta: model = Article fields = [ 'title', 'content', 'author', 'magazine', ] def create(self, validated_data): allmags = [] magazine = validated_data.pop('magazine') for i in magazine: if Magazine.objects.get(id=magazine["id"]).exists(): mags = Magazine.objects.get(id=magazine["id"]) allmags.append(mags) else: return Response({"Error": "No such magazine exists"}, status=status.HTTP_400_BAD_REQUEST) … -
How to automatically fill pre-existing database entries with a UUID in Django
I have added a UUID to the following model: class Post(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) ... But there already are entries in the database that were created without the uuid field. When I run migrate, it adds the same UUID to all my previous objects. Is there an easy way of populating the existing objects with a different UUID automatically? -
why my server terminal doesnt show error?
I am connected to my VPS (Ubuntu) via SSH. I use Django, where I process 1000's of images via Django-imagekit ( PIL ). but for some reason, it is not generating an error it just stops/terminates there. it shows all other print commands and everything. yes, I tried 'try and except' but it doesn't work, it just terminates at 'try' only. anyone any idea? -
AttributeError while accessing serializer.data in DRF serializer
This is my model and BaseManager: class CustomUserMangager(BaseUserManager): def create_user(self,email,password,**extra_fields): if not email: raise ValueError(_("Email is required")) email = self.normalize_email(email) user = self.model( email = email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_("Email address"), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserMangager() def __str__(self) -> str: return self.email and this is my Serializer: class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id','email','is_active') In Python mange.py shell: I try to use this: user = CustomUser.objects.get_or_create(email="a@gmail.com",password="1") >>> user (<CustomUser: a@gmail.com>, True) >>> user_serializer = CustomUserSerializer(user) >>> user_serializer.data and get this error: AttributeError: Got AttributeError when attempting to get a value for field email on serializer CustomUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'email' I dont know wwhat is the problem here :(( -
Uncaught ReferenceError: localstorage is not defined at (index):1228
when I tried to create a cart using javascript in local storage using django, it is showing me this error into the chrome console section.. what should I do now..? what is the proper code to not to get any kind of error like that. -
How to filter a comma separated string in Django Rest Framework?
I have some data that is similar to this: position: "1B, 2B, 3B, SS" I'd like to be able to run a query such as /players/?position=1B, however, this currently does not return anything because the items are separated by a comma. Here is stripped down version of the views.py: class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter): pass class PlayerProfileFilter(django_filters.FilterSet): position = CharInFilter(field_name='display_position', lookup_expr='in') Is there a way to filter the data in this way? -
how to do Django nested comment branching like linkedin social media website
how to make step by wise nested comment branching for social media website. like linked in comment section working. how to create a comment branching in the social media website .im trying too much no response in the social media website -
Audios files served by django not working properly
If I go to this link http://127.0.0.1:8000/media/some_file.mp3 Play and Pause works properly. But not able to change currentTime. see gif here. Django 3.0.10 and python 3.6 models.py class Audios(models.Model): name = models.CharField(max_length=50, null=True) audio = models.FileField(upload_to='', null=True) def __self__(self): return self.name views.py def index(request): obj = Audios.objects.all() return render(request, 'index.html', {'audios': obj}) index.html {% for i in audios %} <audio controls> <source src="{{i.audio.url}}"> </audio> {% endfor %} settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns += [ re_path(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ] -
updating PostgreSQL database index in Django
I have added the following to my model in order to activate indexing for my data in database: class Meta: indexes = [ models.Index(fields=['symbol', 'interval', '-date_time']), ] when migrating, it takes a while to index, which is fine. My question is that when adding new data, how should I update the index again? would it get indexed automatically or I need to run something? Thanks -
Client() got an unexpected keyword argument 'domain_url'
I start using Django multi-tenancy schemas: https://django-tenant-schemas.readthedocs.io/en/latest/use.html I followed the documentation but I'm getting an error I can't create a new tenant : this is my code : from customer.models import Client def create(self, request): formSerializer = self.serializer_class(data = request.data) if formSerializer.is_valid(): ## tenant = Client(domain_url='my-domain.com', schema_name='tenant1', name='Fonzy Tenant', paid_until='2014-12-05', on_trial=True) tenant.save() This is the client as described in the documentation from django.db import models from django_tenants.models import TenantMixin, DomainMixin class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass Error Message ; Client() got an unexpected keyword argument 'domain_url' -
After adding bootstrap to datatables colvis dropdown stopped working
i am working on a django project where i am using datatables, and i am trying to beautify it by using bootstrap. It works as expected colvis dropdowns show the columns without a problem but when i add bootstrap i can't see the columns to filter in dropdowns there is no explanation or errors on the console. I wonder if anyone had the same problem before and how did you solve it? Thanks Colvis dropdown image -
How to store and authenticate different user types in Django?
There are two different types of users, A & B. Users of type A authenticate using username and password while type B have email and password. The project uses token based authentication. The question is: how to manage both user types simultaneously? The approaches I have considered: Separate models for both user types and implement a custom auth backend to authenticate user signing in using email Single user model to cater for both user types. However, this would mean I have to an add additional field (email) and populate some random value for users of type A Apart from this, I have to store some custom information for logged in users like device type, location etc. Is it possible to override authtoken_token table to store this info or I have to create a separate model for that?