Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I push my local django project to git as different submodules?
I have a Django project with different apps in it. I have my project already pushed to a Git repo. What I wanted to is a way by which I can create separate Git repos (maybe called submodules) for my apps along with them included in my Project Repo. The final result should be like: Suppose, I have a local project with 2 separate apps A and B. On GitHub, I should have 3 different repository 1. Complete project repository including Apps 2. Repository containing folder of app A. 3. Repository containing folder of app B. So that I can use those apps again in any other project. Any solutions? -
Django| Create check constraint where left operand of Q object is models.Func()
I have a following model: class IpBlacklist(models.Model): ip = GenericIPAddressField( verbose_name='Ip address.', db_index=True, primary_key=True, unpack_ipv4=True, validators=[admin_validators.ValidateIpAddressOrNetwork(24), ] ) And I want to create check constraint that would restrict net masks on both ipv4 and ipv6 nets. In RAW SQL it looks like: alter table ipcheck add constraint netmask_bits_check check ( (family(ip) = 4 and masklen(ip) between 24 and 32) or (family(ip) = 6 and masklen(ip) between 120 and 129)); I have tried to do it via Check constraint in Meta: models.CheckConstraint( name='netmask_check', check=models.Q( models.Q( models.Func(models.F('ip'), function='FAMILY') == 4, models.Func(models.F('ip'), function='MASKLEN') in range(24, 33) ) | models.Q( models.Func(models.F('ip'), function='FAMILY') == 6, models.Func(models.F('ip'), function='MASKLEN') in range(120, 128) ) ) ) Basically it it just a pseudo -code as I don’t know how to write it properly….Proble is that i have Func() as a left operand and becouse of that i can't use all this '__gt', '__in', etc Any ideas how to do so without custom migrations and without custom transforms??? Thank you! -
Why is my localhost:8000 loading differently from 127.0.0.1:8000 django website
I'm very confused on my django website right now. I have always used localhost:8000 to check my website and it used to work. Now whenever i make changes to the style.css file, the localhost:8000 wont update the website. Instead, it updates only when i open the website through 127.0.0.1:8000. Anyone know whats the problem here? -
How to display a list of timezones for vendors to choose from when he lists an event and other visitors are able to see the time in their local time?
We have a web app(Django based backend and Node/ReactJs based front-end, MySQL based DB), and a Flutter based mobile app. We are creating a system where a vendor can create a meeting invite and list the time (and timezone) at which the meeting starts. Visitors for that meeting should be able to see the time (and timezone) in their local time. We will be having visitors' location and timezone ID based on their IP. I can't figure out how to display the list of timezones(preferably in the GMT+xxxx format ) for the vendor to choose when he creates an invite and in what format it should be sent to the backend and stored so that I am able to convert it and display it to the visiting user based on his location's timezone? I would be really grateful if someone here can point me to the right question if it has been asked already or some document from which I can refer to for the implementation? -
Prevent Django form inserting javascript that is loaded in head of page
I build an application with Django (version 2.2.1). All templates extend a base template, which loads jQuery as follows: <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script> In one template, the combination of an autocompleting input field from django-autocomplete-light (version 3.4.1) and a datepicker from django-bootstrap-datepicker-plus (version 3.0.5) caused the date picker not to work, due to the bootstrap datepicker not being able to initialize jQuery. It turns out that I stumbled upon the same problem as mentioned in this question. The problem is that the template contains a form, which contains a ModelSelect2 widget. This widget causes the form to load jQuery again, as can be seen in its media property: @property def media(self): """Return JS/CSS resources for the widget.""" extra = '' if settings.DEBUG else '.min' i18n_name = self._get_language_code() i18n_file = ( '%s%s.js' % (I18N_PATH, i18n_name), ) if i18n_name else () return forms.Media( js=( 'admin/js/vendor/jquery/jquery%s.js' % extra, 'autocomplete_light/jquery.init.js', 'vendor/select2/dist/js/select2.full%s.js' % extra, ) + i18n_file + ( 'autocomplete_light/autocomplete.init.js', 'autocomplete_light/forward.js', 'autocomplete_light/select2.js', 'autocomplete_light/jquery.post-setup.js', ), css={...}, # omitted, because irrelevant for this question. ) My question: is it somehow possible to prevent this double loading a javascript file? I guess that a form must be able to render itself without knowing what else has … -
How i can override user save Django allauth.socialaccounts
I need to override user save method in my custom OAuth2Adapter. How i can do this? I need save some special fields in my user Model auth_provider/views.py import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from config.settings.base import EXAMPLE_URLS from app.users.auth_provider.provider import ExampleProvider class ExampleAdapter(OAuth2Adapter): provider_id = ExampleProvider.id access_token_url = EXAMPLE_URLS["web"] + "oauth/token" authorize_url = EXAMPLE_URLS["web"] + "oauth/authorize" profile_url = EXAMPLE_URLS["api"] + "me" def complete_login(self, request, app, access_token, **kwargs): headers = {"Authorization": "Bearer %s" % access_token} extra_data = requests.get(self.profile_url, headers=headers) return self.get_provider().sociallogin_from_response(request, extra_data.json()) oauth2_login = OAuth2LoginView.adapter_view(ExampleAdapter) oauth2_callback = OAuth2CallbackView.adapter_view(ExampleAdapter) -
why am I getting 404 (Not Found) for my Django app?
I am finding it difficult to understand that I am getting 404 not found error when I upload a picture to my Django profile now while it was working before. Below is the error: www.schoolnskill.com/:124 GET https://www.schoolnskill.com/<path>/micky.jfif 404 (Not Found) When I RMB on the pic --> inspect I see the error. The things that changed is that before I was using default Db SQLite, but 2 days back I migrated to postgres. However, the issue is happening even before that. I remember, there were 2 failed attempts to migrate from SQLite to Postgres. But I don't think it has any effect. The failed attempt was due to wrong Postgres user and wrong password. But later on it was successfully migrated by rectifying the username and password. Please suggest. Do let me know if anything is required. Thank you, -
How can i get dropdown status ( pending or received ) from Django
i have facing an issue . when i adding item qty in my stock list then it's have an dropdown status whicch is carry two status as like Received and Pending . i can get all data except the status from dropdown . i need to help for this issue . my issue is that when i add item quantity as received then it's calculate the existing stock item . and when i select pending then it's not calculate before change status pending to received. or i request all of you that please do not hesitate for my written code . because i am newbe . my code as below models.py class Stock(models.Model): itemname = models.TextField() # product name itemid = models.IntegerField(default=0) # item specific ID as Like apple = 1 , orange = 2 etc itemidtest = models.CharField(default=0,max_length=250) # for test quantity = models.IntegerField(default=0) stockid = models.IntegerField(default=0) date = models.DateField() ref_number = models.CharField(default='-',max_length=10) supplier = models.CharField(default='-', max_length=100) purchase_date = models.DateField() buy_price = models.IntegerField(default=0) status = models.IntegerField(default=0) def __str__(self): return self.itemname views.py from django.shortcuts import render , redirect , get_object_or_404 from django.db.models import F import datetime from maincat.models import SubCat from parts.models import Parts from supplier.models import Supplier from . … -
Django transactions not rolling back on DatabaseError
I am trying to use database transactions with Django on a Postgresql DB. Have two INSERT queries, first one is a valid one and second one is invalid. Even after the second invalid query is caught, the first one is still committed to the DB. From Django's docs, it is supposed to rollback the first query as well. try: with transaction.atomic(): valid_query() invalid_query() except DatabaseError as e: print(e.args[0) Is there something I am missing? Do I have to rollback the transaction manually in the except block? -
Django email was not sent on using bultin django password reset. What to do?
First of all i have searched for similar problem but didn't got any problem similar to mine. urls.py from django.contrib.auth import views as auth_views urlpatterns[ path("password-reset/", auth_views.PasswordResetView.as_view(), name="password_reset"), path("password-reset/done/", auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path("password-reset/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path("password-reset-complete/", auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), ] Inside of settings.py settings.py EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_USE_TLS=True EMAIL_HOST_USER="MY EMAIL" EMAIL_HOST_PASSWORD="MY PASSWORD" I tried to to send mail from shell and i got the mail but from django builtin templates for password reset didn't send a mail. I have not got any error, server is also running after email is submitted still didn't got email. No email in SPAM either. -
Django Sorl-thumbnail doesn't generate thumbnail from Amazon presigned url
I'm using Jazzband Sorl Thumbnail for generating thumbnails. I have this template <a href="{{ gallery_photo.file }}" data-lightbox="accident-img" target="_blank"> {% thumbnail gallery_photo.file "275x200" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}" alt=""> {% endthumbnail %} <div class="galleryItemHover"> <i class="fas fa-search-plus"></i> </div> </a> Everything looks fine(thumbnail generation from other external urls works fine), but when gallery_photo.file has Amazon presigned url which looks like some-page-example.com/path/to/image/image_name.jpg?AWSAccessKeyId=access_key&Signature=signature&Expires=some_numbers thumbnail generation doesn't work. However I can display original image from presigned url on the page. How to solve this problem? How to create thumbnails from Amazon presinged urls? -
How to deploy each app of a Django project into different servers
For Example: I have developed a django Application which contains four apps inside called app_1, app_2, app_3 and app_4. Now I want to deploy app_1 on server_1, app_2 on sever_2, app_3 on server_3 and app_4 on server_4. Is it possible?? -
How to testing model.Serializer in pytest-django?
I'm trying to learn how to use tests in a DRF project, but I can't go out to test serializers, I can't add an image and primary keys, please show an example how you do it my test: def get_image(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGBA", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, name=name) @pytest.mark.django_db def test_valid_poster_serializer(): valid_serializer_data = { "title": "new poster", "description": "poster description", "image": get_image(), "address": "foo", "phones": "89991234586", "price": 100, "site": "https://foo-bar.com/", "latitude": 123456.0, "longitude": 123456.0, "categories": { "title": "new" }, } serializer = PosterSerializer(data=valid_serializer_data) assert serializer.is_valid() assert serializer.validated_data == valid_serializer_data assert serializer.data == valid_serializer_data assert serializer.errors == {} error text: it looks like the image field expects nothing but in the model this field is required E Common items: E {'address': 'foo', E 'categories': OrderedDict([('title', 'new')]), E 'description': 'poster description', E 'latitude': 123456.0, E 'longitude': 123456.0, E 'phones': '89991234586', E 'price': 100, E 'site': 'https://foo-bar.com/', E 'title': 'new poster'} E Differing items: E {'image': None} != {'image': <File: test.png>} E Full diff: E { E 'address': 'foo', E - 'categories': {'title': 'new'}, E + 'categories': OrderedDict([('title', 'new')]), E 'description': 'poster description', E - 'image': <File: test.png>, E + 'image': … -
"<ClaimDocument: test>" needs to have a value for field "id"
After adding ManyToMany field to ClaimDocument I'm getting this error: "<ClaimDocument: test>" needs to have a value for field "id" before this many-to-many relationship can be used. But I have no test field in my ClaimDocument model. Here are my codes: models.py: class Document(models.Model): created_date = models.DateTimeField(default=timezone.now) added_by = CurrentUserField() assigned = models.ManyToManyField(CustomUser, related_name='assigned', blank=True, null=True) forms.py: class CreateClaimDocumentForm(ModelForm): def save(self, commit=False): document = super(CreateClaimDocumentForm, self).save(commit=False) ClaimDocument.objects.create( assigned = document.assigned, ... -
Error the requested resource was not found on this server after reverse proxying Nginx+Docker+Django project
I am having a problem when I attempt to access localhost/auth/ this is possibly because of the nginx configuration or may be another other issue. The following is the result I get from nginx logs after attempting to make a request to the proxied address localhost/auth/ reverse-proxy | 0.0.0.0 - - [28/Aug/2020:08:21:47 +0000] "GET /api/ HTTP/1.1" 404 159 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) When I access http://localhost/admin/ the Admin login page renders as expected as shown below. Also at http://localhost/doc/ the redocs documentation page renders as well. Project Structure ├── nccggbot │ ├── chatbot/ │ └── core/ │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ ├── wsgi.py │ ├── static/ │ │ ├── admin/ │ │ ├── django_extensions/ │ │ |── drf-yasg │ │ ├── rest_framework │ │ │ ├── Dockerfile │ ├── manage.py │ ├── requirements.txt │ │ ├──reverse_proxy/ │ ├── default.conf │ └── Dockerfile ├──docker-compose-deploy.yml ├──README.md core/urls.py from django.contrib import admin from django.urls import include,path from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions from django.conf import settings from django.conf.urls.static import static schema_view = get_schema_view( openapi.Info( title="NCCG ChatBot API", … -
PostgresQL Altering BigAutoField on large table
I am currently trying to alter a normal Autofield to a Bigautofield using PostgesQL (and Django as framework). The process is going on for one day now and it seems that this is going to take forever as my database reached 2.147.483.647 rows. Is there any workaround to shift around this issue? Any hacks? Thanks in advance -
How to insert a foreign key dynamically after or before POST request Pyton Django
I am trying to assign foreign key during runtime,dynamically. I want that each user that is logged in can add new contacts to his own list. I understand that i need to use foreign key with Many-To-One relationship but I don't know how to implement this. The main goal is to assign the new contact that is added to the user that is logged in and adding him right now,I need to connect between them. model.py from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True,editable=False) #model calss to add adinonal info that the default user does not have #for ex: llike titles Titles = ( ("1", "Mr"), ("2", "Mrs"), ("3", "Miss"), ("4", "Dr"), ("5", "Prof")) Title=models.CharField(max_length=1,choices=Titles,blank=False,default=Titles[0]) first_name=models.CharField(max_length=128,blank=False) last_name=models.CharField(max_length=128,blank=False) def __str__(self): return self.user.username forms.py from django import forms from first_app.models import UserProfileInfo,Login,newContactInfo from django.contrib.auth.models import User class newUserForm(forms.ModelForm): class Meta: model=UserProfileInfo fields='__all__' class loginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model=Login fields="__all__" class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields=('username','email','password') class ContactForm(forms.ModelForm): class Meta: model = newContactInfo exclude=['user_profile_info'] views.py def contact(request): if request.method == "GET": contact_form = ContactForm() return render(request,"first_app/add_contact.html",context={'add_contact':contact_form}) if request.method=="POST": add_contacts_form = ContactForm(request.POST) # contact profileNameForm = newUserForm(request.POST, request.FILES) if add_contacts_form.is_valid() and profileNameForm: new_record = add_contacts_form.save(commit=False) new_record.user_profile_info=profileNameForm … -
Attempt to connect react admin and django via graphql. What is the problem?
React settings are taken from https://www.npmjs.com/package/ra-data-graphql-simple // in App.js import * as React from 'react'; import { Component } from 'react'; import buildGraphQLProvider from 'ra-data-graphql-simple'; import { Admin, Resource, ListGuesser } from 'react-admin'; import { CountryList } from './countries'; class App extends Component { constructor() { super(); this.state = { dataProvider: null }; } componentDidMount() { buildGraphQLProvider({ clientOptions: { uri: 'http://localhost:8000/graphql/' }}) .then(dataProvider => this.setState({ dataProvider })); } render() { const { dataProvider } = this.state; if (!dataProvider) { return <div>Loading</div>; } return ( <Admin dataProvider={dataProvider}> <Resource name="countries" list={ListGuesser} /> </Admin> ); } } export default App; Django Settings: //in project/app/schema.py import graphene from graphene_django.types import DjangoObjectType from .models import Organization, Project, Country class CountryType(DjangoObjectType): class Meta: model = Country fields = ("id", "title") class CreateCountry(graphene.Mutation): id = graphene.Int() title = graphene.String() class Arguments: title = graphene.String() def mutate(self, info, title): country = Country(title=title) country.save() return CreateCountry( id=country.id, title=country.title, ) class InforgMutation(graphene.ObjectType): create_country = CreateCountry.Field() class InforgQuery: countries = graphene.List(CountryType) country = graphene.Field(CountryType, pk=graphene.Int()) def resolve_countries(self, info, **kwargs): print(info) return Country.objects.all() def resolve_country(self, info, **kwargs): if 'pk' in kwargs: return Country.objects.get(pk=kwargs['pk']) return None // Djago settings GRAPHENE = { 'SCHEMA': 'config.schema.schema', } //in project/main_schema.py import graphene from app.schema import InforgQuery, … -
Django - RichText - Ckeditor - how to update content on site
I spent a lot of time trying to solve the issue but I am not able to find some good tutorial on how to update data in CKEditor on the site (not in the admin of Django) I am using the normal text field or textbox, I will just load get the data and put it under attribute value and the site will display it in the textbox, then I can edit it and post it back. But I am struggling with how to put data from the model to view and view it on-site in CKEditor, so I can change it. My environment looks like this: Forms.py class TestingContent(forms.ModelForm): content = forms.CharField(widget=CKEditorWidget( attrs={ 'width':'100%', } ) ) Models.py class GITCTesting(models.Model): text = RichTextField(default="Not_set") . . . View.py def gitc_testing_detail(request, Testing_id, GITC_id): gitctask = GITCTask.objects.filter(Q(idofgitc=GITC_id) & Q(related_control_id=Testing_id)) gitccontrol = GITCTesting.objects.get(Q(idofgitc=GITC_id) & Q(id=Testing_id)) post = get_object_or_404(GITCTesting, id=Testing_id) form = TestingContent(request.POST or None, request.FILES or None, instance=post) return render(request, 'rc_new/rcda_testing_detail.html', menu_contex) HTML template <div class="row"> {{ form.media }} {{ form.content}} </div> I basically tried to make "instance=post" in the form in view but I get and that it is not expected argument. I tried to change some code and get another error … -
DRF create method in viewset or in serializer
What is the difference between customizing the "create" method in DRF viewset or customizing it in the serializer? I understand the serializer is responsible to deserialize the data, i.e. the way the data is presented in the POST query; however, I can also create objects in related fields in the serializer. #views.py def create(self, request): pass #serializer.py def create(self, validated_data): return Model.objects.create(**validated_data) When should I customize views/create vs. serializer/create? -
Do you have any suggestion about my database structure?
According to my project, I have the following tables Bot -> Spider -> Market ->{Product,Trade}(Sub Tables) Bot: Bot_name Spider: Spider_class,spider_name Market: market_name, market_url,Market_location Trade: exchange_rate, currency Product: product_name, price, quantity So I am using Django and MySQL and I try like this: class market(models.Model): market_name = models.CharField(max_length=50,verbose_name="Market Name") market_url = models.CharField(max_length=50,verbose_name="market Link") market_location = models.CharField(max_length=50,verbose_name="Shop location") class product(models.Model): product_name = models.ForeignKey(market,on_delete=models.CASCADE) price = models.CharField(max_length=50,verbose_name="Price") quantity = models.CharField(max_length=200,verbose_name="Quantity") First I try something about a foreign key but after migration, it gives me product_name_id on MySQL and I just want to write product_name and I want to get all product_name's information from the market. So I couldn't figure out how to prepare the structure of my database. -
What is the best way to change the hash password on new Django?
Bcryptpasswordhasher was removed on Django2.1. https://docs.djangoproject.com/en/3.1/releases/2.1/#removed-bcryptpasswordhasher-from-the-default-password-hashers-setting How should I change the password of existing user? Should I switch to another hasher and then let the user change the password? Also, which hasher is best to use? -
The requested resource was not found on this server error while deploying Django/VueJs app on Heroku
I have been able to deploy my django/vuejs app on heroku successfully. The Django backend uses the django rest framework to serve the api endpoints while vuejs handles the frontend. I have set up the app on Heroku, added NodeJs and Python buildpacks, and then added my config vars. However, when i try to open the app on browser, i get Not Found. The requested resource was not found on this server.. heroku logs --tail shows the following: 2020-08-28T07:58:53.956114+00:00 app[web.1]: tmp_upload_dir: None 2020-08-28T07:58:53.956114+00:00 app[web.1]: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} 2020-08-28T07:58:53.956115+00:00 app[web.1]: forwarded_allow_ips: ['*'] 2020-08-28T07:58:53.956115+00:00 app[web.1]: accesslog: - 2020-08-28T07:58:53.956115+00:00 app[web.1]: disable_redirect_access_to_syslog: False 2020-08-28T07:58:53.956116+00:00 app[web.1]: access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" 2020-08-28T07:58:53.956116+00:00 app[web.1]: errorlog: - 2020-08-28T07:58:53.956117+00:00 app[web.1]: loglevel: debug 2020-08-28T07:58:53.956118+00:00 app[web.1]: capture_output: False 2020-08-28T07:58:53.956118+00:00 app[web.1]: logger_class: gunicorn.glogging.Logger 2020-08-28T07:58:53.956119+00:00 app[web.1]: logconfig: None 2020-08-28T07:58:53.956119+00:00 app[web.1]: logconfig_dict: {} 2020-08-28T07:58:53.956119+00:00 app[web.1]: syslog_addr: udp://localhost:514 2020-08-28T07:58:53.956120+00:00 app[web.1]: syslog: False 2020-08-28T07:58:53.956120+00:00 app[web.1]: syslog_prefix: None 2020-08-28T07:58:53.956120+00:00 app[web.1]: syslog_facility: user 2020-08-28T07:58:53.956121+00:00 app[web.1]: enable_stdio_inheritance: False 2020-08-28T07:58:53.956121+00:00 app[web.1]: statsd_host: None 2020-08-28T07:58:53.956121+00:00 app[web.1]: dogstatsd_tags: 2020-08-28T07:58:53.956122+00:00 app[web.1]: statsd_prefix: 2020-08-28T07:58:53.956122+00:00 app[web.1]: proc_name: None 2020-08-28T07:58:53.956122+00:00 app[web.1]: default_proc_name: mysite.wsgi 2020-08-28T07:58:53.956123+00:00 app[web.1]: pythonpath: mysite 2020-08-28T07:58:53.956123+00:00 app[web.1]: paste: None 2020-08-28T07:58:53.956124+00:00 app[web.1]: on_starting: <function OnStarting.on_starting at 0x7f10994d2488> 2020-08-28T07:58:53.956124+00:00 app[web.1]: on_reload: <function OnReload.on_reload at 0x7f10994d2598> 2020-08-28T07:58:53.956125+00:00 … -
How to use easy-thumbnails with static in template?
I wonder how (if it is possible) load thumbnail for static files with easy-thumbnails package. I tried: <img src="{% thumbnail 'img/V.png' 50x0 %}" /> <img src="{% thumbnail static 'img/V.png' 50x50 %}" /> <img src="{% static thumbnail 'img/V.png' 50x50 %}" /> but nothing works. -
Sencha ExtJS PDF Download
I have a rather complex frontend in Sencha ExtJS with a Python/Django Backend. I need to download PDFs via the Django Backend, which needs authentication. I tried an iFrame and window.open but I can not pass the auth token with this approach. How can I accomplish the pdf download from the backend with authentication? Thanks in advance, Reto