Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload excel file and read it insert into database in dango
I want to read excel file and whatever that excel file containing data that data insert into MySQL when uploading excel file using Django -
Django-Haystack clear_index not deleting database entries
I am using django and haystack and my problem is that when I try to clear the index it does not remove the entries from the database. As a result, if I rebuild the index the documents appear again. Is this an issue of haystack or am I doing something wrong? Thank you in advance -
Recurring code in Django views: how to avoid repetition?
For many - but not all - of my views I have to do some validation to make sure the user that is logged in has access to the object they are trying to access. For 30+ views I have this code: def whatever_view_name(request, id, access_id): check = Access.objects.filter(user=request.user, id=access_id) if check: access_object = check[0] else: return redirect(reverse("create_new_access_object")) .... and now my view-specific code will follow ... So I need to check if a particular database record (Access) exists for this particular user. This code is repeated a lot, which does not seem to be right. I've been thinking about using middleware, but there are two problems: a) I need to use this object in the view (see variable access_object so I fear I'd have to query it twice if I put it in the middleware), and b) I don't need to do this ALWAYS so I wonder how to only run it for some views and not all if this is middleware. Any thoughts? -
Saving country name from country field
I need country selection field on my form, my models.py: class ContactForm(models.Model): first_name = models.CharField(max_length=10) Country = models.CharField(max_length=10) And my forms.py: from django_countries.fields import CountryField class UserContact(forms.Form): first_name = forms.CharField(label='your first name', max_length= 10) country = CountryField().formfield() My views: def get_data(request): form = UserContact() if request.method == 'POST': form = UserContact(request.POST) if form.is_valid(): ContactForm.objects.create(**form.cleaned_data) return render(request, '# some url', { 'form': form} My problem is, when I submit the the form, in my admin page, in my ContactForm model, I have my first name that I entered, and just the country code! Not the full name of the country. I don't know how to do that. But I know that I can get the country name in shell using: from django_countries import countries dict(countries)['NZ'] 'New Zealand' So, for example, I need the New zealand to be saved in my database, not NZ. -
Django REST not rendering form correctly
I have the following code, that should render a list of FooBars. I have two problems: The first is, when I uncomment the state, foo and bar objects, the list renders them with actual data from the database (they're choice fields), but when I leave them commented, it just displays the choice integer. The second problem is, that when I then navigate to rest/foo/1/?html_form=true and look at the HTML form, it only renders the state, foo and bar fields, if I leave them commented. I want to leave them uncommented, so that the user can view the actual data, however that disables me or the user from editing those fields. What am I doing wrong? rest.py class FooBarSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) #state = serializers.SerializerMethodField(label=_('State')) #foo = serializers.SerializerMethodField(label=_('Foo')) #bar = serializers.SerializerMethodField(label=_('Bar')) def get_state(self, obj): return obj.get_state_display() def get_foo(self, obj): return obj.get_foo_display() def get_bar(self, obj): return obj.get_bar_display() class Meta: model = FooBar fields = ('id', 'state', 'foo', 'bar', 'bool1', 'bool2', 'bool3') class FooBarViewSet(viewsets.ModelViewSet): serializer_class = FooBarSerializer permission_classes = (IsAuthenticated, IsAdminUser) queryset = FooBar.objects.all() def render_form(self, request, serializer, status): from django.shortcuts import render return render(request, 'foo/foobar_item.html', { 'intent_form': serializer, 'intent_style': {}, }, status=status) router.register(r'rest/foo', FooBarViewSet, 'foobaritem') -
Not Recognizing New Models When Trying to Load Data
I added a model in Django project after building my database. It's PostgreSQL, not the standard SQLite. My initial import line works. This runs: from project import model1 When I try to load data into this model, I get the following error. django.db.utils.ProgrammingError: relation "project_model1" does not exist Not sure how to fix this. Do I need to delete the database and start again. -
AttributeError at /swagger/ 'NoneType' object has no attribute 'title' django python rest api
i am using python rest framework api and i want to install this package on it for documenation my api on swagger : https://github.com/axnsan12/drf-yasg/ i installed rest framework and its working fine and i installed the packge and added that to installed packages and here is what i changed in my url.py : from django.contrib import admin from django.urls import include, path from rest_framework import routers from django.shortcuts import redirect from tutorial.quickstart import views from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) SchemaView = get_schema_view( openapi.Info( title="asdasdsad", default_version='v1', ), public=False, permission_classes=(permissions.AllowAny,) ) swagger_info = openapi.Info( title="Snippets API", default_version='v1', description="""This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg) Django Rest Framework library. The `swagger-ui` view can be found [here](/cached/swagger). The `ReDoc` view can be found [here](/cached/redoc). The swagger YAML document can be found [here](/cached/swagger.yaml). You can log in using the pre-existing `admin` user with password `passwordadmin`.""", # noqa terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ) SchemaView = get_schema_view( validators=['ssv', 'flex'], public=True, permission_classes=(permissions.AllowAny,), ) and in the end i use paths like below : urlpatterns = [ path('', include(router.urls)), # re_path("^swagger(?P<format>.json|.yaml)$", SchemaView.without_ui(cache_timeout=0), name='schema-json'), path("swagger/", SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path("redoc/", SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('admin/', admin.site.urls), ] … -
How to apply discount to basket line?
New to Django-oscar and can't have answers on the official docs I'm trying to add a discount I tried this: line, created = self.request.basket.add_product(product=product, quantity=serializer.validated_data['quantity'], options=options) line.discount(discount_value=20, affected_quantity=1) line.save() and when I try to print basket.total_excl_tax_excl_discounts or basket.total_excl_tax I always get the same result (which is the total of basket no matter discounts I added) what am I missing ?? -
Dockerized Django app not applying unique constraint
I have two issues both of which are inter-related Issue #1 My app has an online Postgres Database that it is using to store data. Because this is a Dockerized app, migrations that I create no longer appear on my local host but are instead stored in the Docker container. All of the questions I've seen so far do not seem to have issues with making migrations and adding the unique constraint to one of the fields within the table. I have written shell code to run a python script that returns me the contents of the migrations file in the command prompt window. I was able to obtain the migrations file that was to be applied and added a row to the django_migrations table to specify the same. I then ran makemigrations and migrate but it said there were no changes applied (which leads me to believe that the row which I added into the database should only have automatically been created by django after it had detected migrations on its own instead of me specifying the migrations file and asking it to make the changes). The issue is that now, the new migrations still detect the following change … -
Django request's session consistency across different browsers
I have the session engine settings as follows: SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' SESSION_SAVE_EVERY_REQUEST = True CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 60*60, } } I go to 127.0.0.1:8000 with Browser 1 and can successfully log in. Then I go to 127.0.0.1:8000 with Browser 2 and can also successfully log in. Now I go to 127.0.0.1:8000 with Browser 1 and get the following error message: SuspiciousOperation at / The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. How can this error be avoided? The user should be able to log in with as many browsers as he likes. I don't mind if he gets logged out from the non-active browsers, but an error is not acceptable. -
How to add "Return Product" after "Product Delivery" functionality in Django Oscar
I want to add "Return Product" after "Product Delivery" functionality in Django Oscar. in settings.py i added below code. OSCAR_ORDER_STATUS_PIPELINE = { 'Pending': ('Processing', 'Cancelled',), 'Processing': ('Shipped', 'Cancelled',), 'Shipped': ('Delivered', 'Return', 'Returned', 'Cancelled',), 'Returned': ('Return', 'Returned',), 'Delivered': (), 'Cancelled': (), } OSCAR_ORDER_STATUS_CASCADE = { 'Processing': 'In progress', 'Shipped': 'Shipped', 'Delivered': 'Delivered', 'Returned': 'Returned', 'Cancelled': 'Cancelled' } i have written Ajax function to change the status after Order gets "Delivered" to "Return". below is the function. @csrf_exempt def return_order(request): # Return Order after Delivery if request.is_ajax(): data = request.body.decode('utf-8') try: order = Order.objects.get(id=int(data)) EventHandler().handle_order_status_change(order=order, new_status='Return') return HttpResponse(json.dumps({'status': 'True', 'msg': 'OK'})) except Exception as e: print(e) return HttpResponse(json.dumps({'status': 'False', 'msg': 'Error'})) I am geting Error something like this 'Return' is not a valid status for order 100213 (current status: 'Delivered') -
Django Microservices - skip all user created tables for non-user services
I am using Django in a Microservice architecture. I already have a userService for authentication with JWT with an apiGatewayService that checks if token is valid before routing requests to other services. This means that I do not need all the standard tables that are created for a user (user tokens, sessions, email etc) in my other services when I run python manage.py migrate. Is there a way to opt out of creating these unnecessary tables? I have read some people just saying not to run migrations so as not to create these tables, but I obviously want to create other tables (say I have an ordersService, I want an orders table etc). -
send VoIP notifications via PushKit in django
Hot to send VoIP notifications via Pushkit in Django server. Is it possible to send Pushkit notification using APNSNotificationWrapper -
Group objects by different models
I have two models: class Combo(models.Model): price = models.DecimalField class Choice(models.Model): combo = models.ForeignKey(Combo, on_delete=models.CASCADE) items = models.ManyToManyField(Item) And also I have models for order: class Order(models.Model): comment = models.CharField(max_length=300) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) amount = models.PositiveIntegerField Combo consist of all Choices linked to Combo and to have Combo price we need to have one item for each Combo choice. For example Combo#1 has two choices with items: Rag, Brom. Scoop. So if our order has 2 rags, 1 broom and 2 scoop we will get 2 combos and one broom as item. How can I split Order to combos and items to have 2 QuerySets - one for Combos and other for Inems not included to combos? Thanks! -
fetch data from databse based on choices django
i am creating artist booking web app and i have a dropdown list of artists like celeb, dancer, model so when i click any of them it should fetch only specific list in html template. i'm storing the artist based on choices this is my models.py: from django.db import models class artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) artist_name = models.CharField(max_length = 50) artist_type = models.IntegerField(choices = CHOICES) description = models.TextField(max_length = 500) def __str__(self): return self.artist_name view.py: def talent(request): artists = artist.objects.all() context = { 'aka': artists } return render(request, 'main_site/talent.html', context) when i am rendering this it get all the list but i need specific list like when i click on dancer it should get dancer only this is base.html navbar: <ul class="menu-horizontal text-left "> <li><a href={% url 'mainsite-index'%} class="menu-horizontal text-left nav-font">Home</a></li> <li><a href={% url 'mainsite-about'%} class="menu-horizontal text-left nav-font">About</a></li> <li class="dropdown"> <a href="#" class="menu-horizontal text-left dropdown-toggle nav-font" data-toggle="dropdown">Artist</a> <ul class="dropdown-menu nav-font" style="margin-top: 7px"> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Celebrities</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Singer</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Comedian</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Dancer</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Model</a></li> … -
Google django-allauth config
I have been able to successfully configure django-allauth with my Django app. When i attempt to signup via Google, i see a Sign Up form getting shown before login, which is prompting user to enter username, email etc. like the following: Sign Up You are about to use your Google account to login to example.com. As a final step, please complete the following form: Username: E-mail (optional): Sign Up » Is there a config. which i can use to bypass this form? Please suggest how to avoid this. -
how to save username(phone) and password by unidecode in django?
I’m Use a Customuser Model in Django. When Register User by Persian or Arabic Digit Can't Log because Username and Password Save in Persian. in Login Form Can Change Entry to unidecode But in Register Form Can't. if Register by English Digit Can log by every Digit form (English, Persian, etc) But if Register Persian or Arabic Can't Log. How Resolve it? User Unidecode for Digit and text-unidecode for Charfiled in Code Try to unidecoede Phone(username) and Password in Reg Form But Unsuccessful class UserManager(BaseUserManager): def create_user(self, phone, name, family, password=None, is_active=True, is_staff=False, is_admin=False): if not phone: raise ValueError("Users must have an phone") if not password: raise ValueError("Users must have a password") if not name: raise ValueError("Users must have a name") if not family: raise ValueError("Users must have a family") this_phone = unide(phone) this_password = unidecode(password) user_obj = self.model( phone = this_phone, name = name, family = family ) user_obj.set_password(this_password) # change user password user_obj.is_active = is_active user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj -
Django admin custom choice formfield choice
In the django admin I'm trying to create a custom choice if a field in the database is None or with a value but I cannot make it work I can only get the whole queryset but I cannot get the id of the data so I can filter the request. Any suggestions? def formfield_for_choice_field(self, db_field, request, **kwargs): ordered = False qs = self.get_queryset(request) for query in qs: if query: if query.order: ordered = True if db_field.name == "order": if db_field.value: ordered = True if db_field.name == "status": if ordered: kwargs['choices'] = ( ('Ordered', 'Ordered'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Late', 'Late'), ('Never Arrived', 'Never Arrived'), ) else: kwargs['choices'] = ( ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Late', 'Late'), ('Never Arrived', 'Never Arrived'), ) return super(xxxxxx, self).formfield_for_choice_field( db_field, request, **kwargs) -
Deserialize different fields names than attributes names
I would like to deserialize input given like: { "NameFilter": ["John", "Paul"], # name has to be exactly 4 letters length "AgeFilter": [ { "Min": 10, "Max": 12 }, { "Min": 8, "Max": 99 } ] } To something like this: { 'name_filter': ['John', 'Paul'], 'age_filter': ['10-12', '8-99'] } In order to do that I have created 3 serializers: class NameFilterSerializer(serializers.Serializer): name_filter = serializers.CharField(max_length=4, validators=[MinLengthValidator(4)]) def to_representation(self, instance): return instance class AgeFilter(serializers.Serializer): min = serializers.IntegerField() max = serializers.IntegerField() def to_representation(self, instance): return str(instance['Min']) + '-' + str(instance['Max']) class FilterSerializer(serializers.Serializer): name_filter = NameFilterSerializer(many=True) age_filter = AgeFilter(many=True) def to_internal_value(self, data): return { 'name_filter': data['NameFilter'], 'age_filter': data['AgeFilter'] } It returns correct values but in case of invalid input data ("Min" is not a number or "NameFilter" contains "NameExceeding4letters") it does not raise the error. What am I missing? -
Django resend activation link, missing 1 required positional argument: 'user'
I have read similar questions but I cannot understand why this is not working. I am trying to send a reactivation email to user when they click on a link. The activation link is generated properly when the user signs up and the email is sent, but when I try to call the same function again to reactivate link, it is not working saying it is missing one parameter. Here's the function: acounts/views.py def sendactivationmail(request, user): # Creating token and masing uid of user token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() # Sending email for email verification subject = 'Please Verify Your Email' from_email = settings.DEFAULT_FROM_EMAIL to_email = [user.email] context = { 'url': settings.BASE_URL + reverse('user-activation-link', kwargs={ 'uidb64': uid, 'token': token, }), } contact_message = render_to_string('verify_email.html', context) plain_message = strip_tags(contact_message) send_mail(subject, plain_message, from_email, to_email, html_message=contact_message, fail_silently=True) return redirect(reverse('login')) accounts/urls.py from django.conf.urls import url from .views import * from . import views from urllib import request from django.contrib.auth.models import User urlpatterns = [ url(r'^reactivate/$', views.sendactivationmail(request, User), name='reactivate'), Is this the right way to pass on the request and user parameters to the function? -
How to enable text compression in a django project?
Currently we are trying to increase the performance of our website. Our project is running in django and developed in javascript. Now after running audits in chrome we realised that we haven't enabled text compression. We already searched the web and found diffrent results but can't really find a general solution which is working for us. We tried the following already: COMPRESS_ENABLED = True We expect the content-encoding in our Response Header to show up. Please let me know if you need any other code details. Hope someone can help us. -
How do I store a user's google+ profile information with google+ API in my database?
I have djongo engine based google authentication web application. It signs in the user by using google+ API. My database is able to store the username and email. How do I get it to store the user's first name, profile picture url etc from google+ profile information in my database? -
Django: update_or_create, filter with list of kwargs
Is there any way of using list in kwargs filter of update_or_create? Here are my models: class Partner: ... class MyClassB: partner = models.OnetoOneField(Partner, related_name='some_name') .... I tried using for loop, and it works fine. # partners = list of queryset objects. for partner in partners: MyClassB.objects.update_or_create(partner=partner, defaults= {'name': None}) This operation is being used very frequently and I was thinking of optimizing this update_or_create. is there any way I could update all partners in one go? Something like: MyClassB.objects.update_or_create(partner__in=[partners], defaults={'name': None}) This code is part of an API that would be hit by a thousand partners every 5 seconds. And I want to avoid additional overhead of using for loop here. Is there any optimized way? -
How to create Django Subfolder for multiple country like subdomains
I wanted to make a multiregional website using Django. One way is to use subdomains For eg: in.example.com //India ae.example.com // UAE Note: The content is going to be the same just the language and payment gateway will change as per region/country. Another way is to use subfolders For eg: example.com/in example.com/ae I need to work using the later method of example.com/COUNTRY. How can I do so using Django? -
How do you get a string from Django PostgreSQL ArrayField?
I'm trying to get a string out of an ArrayField in my database but it only prints by characters, not the full string. For example, the ArrayField is named words and in the database it shows as {word1, word2, word3} so in the HTML I put {{ object.words.0 }} and { is rendered on the screen. How can I get it to render word1? I have added django.contrib.postgres to INSTALLED_APPS. This is what it looks like in my model: from django.db import models from django.contrib.postgres.fields import ArrayField class WordArr(models.Model): words = ArrayField(models.CharField(max_length=200, null=True))