Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to connect local django project to MySql running on AWS EC2? How?
What I tried: Installed MySql server on the EC2 instance. In the security group of the instance added inbound rule to connect over shh from all source Created a database and user Given that user all permissions using GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; Created a django project using django-admin startproject mysite and installed mysqlclient in project settings I changed the default database from sqlite to { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbtest', 'USER': 'root', 'HOST': '{IPv4 Public IP of the Instance}', 'PASSWORD': 'password', } Now when i run python manage.py runserver it gives me error django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'157.34.126.187' (using password: YES)") Than i granted all privileges to this specific IP as well using: GRANT ALL PRIVILEGES ON *.* TO 'root'@'157.34.126.187' WITH GRANT OPTION; Still no luck.Same Error. -
Django: "No migrations to apply" for existing server database
Added a small model 'new_model' in existing app 'existing_app' on Django, Entered commands manage.py makemigrations and manage.py migrate it migrated changes to local database. Tried to apply same on heroku but its not working there. I then tried to setup heroku database in local settings.py of project and migrations worked but it shown some well known error, I have attached the output with this discusssion. Attaching the final screenshot as output. enter image description here Just In Case if it may help_________ The following are the methods I have applied before the final solution:- With heroku run manage.py makemigrations Adding makemigrations command to procfile Pushing migrations as well, so it may replace server migrations Heroku bash and tried "makemigration" and "migrate" on it enter image description here The all four mentioned steps provided this output:- "No migrations to apply, and on migrate it shows you dont have new migrations", helping out to migrate changes on database. Thank You. -
How to remove all duplicate value when fetch data from Database in Django view page?
I have 2 tables in my database product and skuoption, the skuoption table has variant_id and this variant_id is storing multiple times with the same fields in skuoption table, please let me know how I can remove the duplicate value of variant_id when I fetch data on view page. here is my code for product-view.html file... <h3>₹ {{product.saleprice}}</h3> <div class="product-description border-product"> <div class="size-box"> <ul><b>Select Size: </b> {% for sku in product.skuoption_set.all %} <li><a href="javascript:void()">{{sku.variantsize}}</a></li> {% endfor %} </ul> </div></div> what condition i can add here ({% for sku in product.skuoption_set.all %}) or here {{sku.variantsize}}) so that i can remove duplicate values from my view page. Please have a look in the screenshot, which duplicate value i want to remove. -
How can we change time format in django admin
In django Template i am getting time in this format like : 17 : 19 : 05 I want to convert this in : 5:19 Pm format how can i convert this in this format can anyone please help me related this ?? -
Redirect to the page from where user clicked signin after login in django3.0
i want to redirect the user to the page from where he clicked the login instead of home. login view: def login_view(request): context = {} user = request.user if user.is_authenticated: return redirect('home') if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect('home') else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, "account/login.html", context) -
DRF m2m reverse serializer relations
How to make a reverse m2m in serializers? I have following models Models: class Group(models.Model): name = models.CharField(max_length=256) class User(AbstractBaseUser): username = models.CharField(max_length=255) group = models.ManyToManyField(Group, blank=True) I have following serialiazers Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username'] class GroupInfoSerializer(serializers.ModelSerializer): class Meta: model = Group fields = '__all__' How to achieve following response, any help pls: { "group": [ { "id": 1, "name": "title", "users":{ "id":"user_id" "username":"username", } }, -
there is an issue in importing ASGI.APPLICATION module even though i have specified in settings.py
1 Is this the problem with middleware or am i missing some modules? The error only persists when i add the AuthmiddlewareStack module. raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'nxchat.routing' -
Django - I can't makemigrations due to a missing field error
In one of my models (projects), I've deleted a field named 'fk_user', however when I try to run migrations I get the following error. django.core.exceptions.FieldError: Unknown field(s) (fk_user) specified for projects I've tried clearing all files in the migrations folder aside from init.py, i've cleared all migrations in the table but that doesn't resolve the issue. I've also created a new database and updated the name in the settings to this new database - however I keep getting the same error. Where is the reference to this being held? If I run a text search on my computer, the only other file that contains it is the init file and i've tried deleting the reference in here and even clearing the whole file however nothing works. -
django-filters: filter two attributes in the same filter
I have a model like this class Service(models.Model): """ ServiceProviderService""" service_provider = models.ForeignKey( ServiceProvider, on_delete=models.CASCADE, related_name="services" ) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) description = models.TextField(null=True, blank=True) price_from = models.PositiveIntegerField(_("Price range from"), default=0) price_to = models.PositiveIntegerField(_("Price range to"), default=0) I want to filter the ServiceProvider model with those price_from and price_to I tried this: class ServiceProviderFilter(FilterSet): """ServiceProvider Model Filters""" price_from = django_filters.NumberFilter(label='price from', method='price_from_filter') price_to = django_filters.NumberFilter(label='price to', method='price_to_filter') status = django_filters.ChoiceFilter(choices=lookups.SP_STATUS_CHOICES) class Meta: model = ServiceProvider fields = ['price_from', 'price_to', 'status'] def price_from_filter(self, queryset, name, value): return queryset.filter(services__price_from__gte=value).distinct() def price_to_filter(self, queryset, name, value): return queryset.filter(services__price_to__lte=value).distinct() the problem is that they are separate filters so it returns querysets that are valid for both. I want it to return only one queryset with values in between, like: return queryset.filter(services__price_from__gte=value, services__price_to__lte=value).distinct() is it possible? thanks -
requests.post in APITestCase causes requests.exceptions.ConnectionError
In my view that creates race I create also chat for this race using requests.post. When I'm calling this view with my Postman, everythink works, but when i try to test it I get following error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='api', port=8000): Max retries exceeded with url: /api/chat/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f03b9265df0>: Failed to establish a new connection: [Errno -2] Name or service not known')) I'm pretty sure error is caused by that, becouse when I commented request part of the code, tests were working. Here is one of my tests that raised error: def test_retrieve_wrong_id(self): self.client.force_authenticate(self.user) res = self.client.get(reverse("races:race", kwargs={"id": 420})) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) self.assertEqual(res.data, "No race with this id found!") And here is post that I have in view: res = requests.post("http://api:8000/api/chat/", data={ "chat_name": "chat", "race_chat": serializer.data["pk"], "chat_users": str(request.user.pk) }) I wrote tests using APITestCase and application is running in Docker. -
displaying only the selected fields of many to many field in the admin panel (django)
this is my model and i want to display only the selected fields of items manytomanyfield in the Order model class Order(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem, limit_choices_to={'id__in':assigned_tasks }) date = models.DateField(auto_now_add=True) ordered = models.BooleanField(default=False) a = models.CharField(max_length=10) def total(self): total = 0 for order_item in self.items.all(): total += order_item.prix_total() return total -
how to change values of select option of django's admin panel
I am trying to do a dynamic dropdown in django's admin panel so I want to change this this value is coming from sub_categorie.id but I want to change value to come from sub_categorie.category_name_id here is my models.py class categorie(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class sub_categorie(models.Model): sub_name = models.CharField(max_length=100) catagory_name = models.ForeignKey(categorie, on_delete=models.CASCADE, default=1) def __str__(self): return self.sub_name class Products(models.Model): Product_Name = models.CharField(max_length=100) price = models.FloatField() Description = models.TextField() ctg = models.ForeignKey(categorie, on_delete=models.CASCADE,blank = False, default=1) sub_category = models.ForeignKey(sub_categorie, on_delete=models.CASCADE,default=1) the value is coming from this model sub_categorie.id by default I want to change it to the sub_categorie.category_name_id how can I do it. here is my admin.py admin.site.site_header = 'MyShop Administration' class ProductsAdmin(admin.ModelAdmin): change_form_template = 'admin/categories.html' admin.site.register(sub_categorie) admin.site.register(categorie) admin.site.register(Products,ProductsAdmin) -
Django serialize related database entries in JSON and deserialize JSON to databse entries
I do have the following database layout (models.py): class Company(models.Model): company_id = models.CharField(unique=True) company = models.CharField() country = models.CharField(max_length=2) language = models.CharField(max_length=2) class Host(models.Model): ip = models.GenericIPAddressField() domain = models.CharField() company = models.ForeignKey(Company, on_delete=models.CASCADE) class Port(models.Model): port = models.CharField() number = models.IntegerField() name = models.CharField() host = models.ForeignKey(Host, on_delete=models.CASCADE) class Software(models.Model): software_id = models.IntegerField() software_name = models.TextField() host = models.ForeignKey(Host, on_delete=models.CASCADE) port = models.ForeignKey(Port, on_delete=models.CASCADE) The normal usecase is that one company has many hosts, one host has many ports and there can but doesnt has to be one software (like nginx) per host and port. When performing the following Host.objets.filter(company=1) it return all hosts related to that company. I'd like to serialize all hosts AND related data from related tables that get returned from that query to JSON so that i can delete these with Host.objets.filter(company=1).delete(). How can this task be accomplished and how can in deserialize the JOSN into database entries afterwards? -
Change table data when select from a dropdown value
At first please see the image : final result There is two dropdown and a table for showing data. 1st dropdown is 'Series' and second is 'Episode'. When a series will be selected episode dropdown will pull episode name from which is under the selected series. And also show the details in the table. Here is select input: <div class="card-header d-flex align-items-center"> <div class="flatpickr-wrapper flex"> <select class="selectpicker" data-live-search="true" id="seriesID"> <option>Select Series</option> {% for series in series_context %} <option value="{{series.id}}">{{ series.lesson_title }}</option> {% endfor %} </select> <select id="episodeID"> <option>Select Series</option> {% for ep_context in episode_context %} <option value="{{ep_context.series_of.id}}">{{ ep_context.title }}</option> {% endfor %} </select> </div> </div> And this way i tried: <script> $(document).ready(function () { var $seriesVar = $('#seriesID'); var $episodeVar = $('#episodeID'); var $options = $episodeVar.find('option'); $seriesVar.on('change',function () { $episodeVar.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); var $episodeTable = $('#episodeTable'); var $tbody = $episodeTable.find('tr'); $seriesVar.on('change', function () { $episodeTable.html($tbody.filter('[value="\'+this.value+\'"]')); }).trigger('change'); }); </script> My table id is "episodeTable" All data exist in the table. But data filter according to select dropdown not working. Please help me with the code or the logic that how it should be. -
Django unitest for tables with the same name in different databases
I'm writing unitests for django application, using django 2.2.11 My application uses several databases and during running unitest the following problems are encounter: Several databases have table with the same name, e.g database Control and Report: class Operation(models.Model): #fields list class Meta: managed = True db_table = 'OPERATION' app_label = 'Control' class Operation(models.Model): #fields list class Meta: managed = True db_table = 'OPERATION' app_label = 'Report' while running "python3 manage.py test $@" it fails at the stage of db creations (Creating test database for alias ...) with the error: File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 382, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "OPERATION" already exists Is there any Meta/ settings that have to be defined that django will understand that there are several different tables with the same name? Several models have Foreign key field related to other models: class Flow(models.Model): test = models.ForeignKey(Test, blank=True, null=True, on_delete=models.SET_NULL) While running unitests, the process fails while trying to run the following query: SELECT REFERRING.`id`, REFERRING.`test_id` FROM `FLOW` as REFERRING LEFT JOIN `TEST` as REFERRED ON (REFERRING.`test_id` = REFERRED.`id`) WHERE REFERRING.`test_id` IS NOT NULL AND REFERRED.`id` IS NULL The error is : File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 82, in … -
django restful login drf go to login/?next=/
I try to implement API view inside my normal login in Django but URL goes to login/?next=/ i try to implement DRF API for mechanism provide API for third-part application View I used APIview for authenticate Thirdpart inside authentication : #####Django rest framework Dependency########### from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated #####Django rest framework Dependency########### class HelloView(APIView): permission_classes = (IsAuthenticated,) # <-- And here def get(self, request): content = {'message': 'Hello, World!'} return Response(content) URL : urlpatterns = [ path('', RedirectView.as_view(url='/wf/todo/'), name='home'), path('batchadd/', CSVUploadView.as_view(), name='batchimport'), path('admin/', admin.site.urls), path('wf/', include('lbworkflow.urls')), path('attachment/', include('lbattachment.urls')), path('select2/', include('django_select2.urls')), path('impersonate/', include('impersonate.urls')), path('__debug__/', include(debug_toolbar.urls)), path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='accounts/login.html'),name='logout'), path('hello/', views.HelloView.as_view(), name='hello'), ] setting : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'lbattachment', 'lbutils', 'lbworkflow', # Third-Party Apps 'MSDM', 'MSDM.param', 'MSDM.hr', 'MSDM.wfapp.PM', # Third-Party Apps 'rest_framework', 'rest_framework.authtoken', ] LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = '/' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentiction.TokenAuthentication', # <-- And here ], } -
Django - Wanna make function based update view
Can someone help me to make a update view for the maleForm and femaleForm .? my template has three columns in one form where they work separately. If I give input for contact column and male column it will save in my database. So basically I want to update the male only as contacts,male and from are present in same html form. I can update the contact but not the male or female inputs. They all are in same page.I want to make working differently so I can update them. from django.urls import path , include from . import views urlpatterns = [ path('', views.index, name='index'), path('info/', views.info, name='info'), path('features/', views.features, name='features'), path('add/', views.add, name='add'), path('add/' ,views.success, name='success'), path('update/<str:pk_test>/' ,views.update, name='update') ] views.py def update(request,pk_test): template_name = 'update.html' contact = Contact.objects.all() # c_form = commentForm(instance=contacts) # if request.method =='POST': # c_form = commentForm(request.POST,instance=contacts) # if c_form.is_valid() : # contact = c_form.save() # messages.success(request, "Contact Updated") # return redirect("success") # else: # c_form = commentForm() # context = { # 'c_form' : c_form, # } contacts= Male.objects.get(id=pk_test) male_f = maleForm(instance=contacts) if request.method == 'POST': contact_m.save() c_form = commentForm(request.POST) male_f = maleForm(request.POST,instance=contacts) if male_f.is_valid(): contact_m = male_f.save(commit=False) contact_m.contact1 = contact contact_m.save() messages.success(request, … -
Getting all the Coordinate points within a certain radius
I am writing a function in django that will display me all the events in the certain radius. The only information I have coordinate points, I want to use a coordinates point as a center and then selecting all the the coordinate points withing a certain radius. I want to accomplish it in django, how can I do it? -
url {% url employes:check_matricule %} is not running in forms.py
I want to execute the url"{% url employes:check_matricule %}" to the data-url attribute in forms .py but the result "404 page not found" class EmployeForm(forms.ModelForm): matricule = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Matricule1', 'onkeyup': 'check_matricule(this);return false;', 'data-url': '{% url employes:check_matricule %}', } )) -
Django REST: Issue with POST request, required field
I'm running into an issue with a POST request. The field "employee" is required but I initialize it in the view (I set it to request.user), rather than in the request parameters. Yet I still get the following error: data: employee: ["This field is required."] The view class EmployeeQuestionView(viewsets.ModelViewSet): queryset = EmployeeQuestion.objects.all() serializer_class = EmployeeQuestionSerializer def perform_create(self, serializer): serializer.save(employee=self.request.user) Any ideas why? -
Getting runtime error while trying to run Runserver in python Django
So I have received a code that is not mine. My aim was to run the Django website I received as they told me all was working fine. But when I tried to run Runserver I got this error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\eneko\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? These are my package versions: Django 1.9.13 django-autoslug 1.9.7 pip 20.1.1 My python version is 3.8.2 Help would be very much … -
django celery task not executing
I'm trying to send and email and change the status filed of an order if the manu_date is today. I'm successfully running the task in the terminal, but not receiving any email or changing the status. tasks.py @shared_task def weekly_check(): orders = Order.objects.all() for order in orders: if order.manu_date == datetime.datetime.utcnow(): order.status = 'Processing/Manufacturing' order.save() send_mail('Order', 'Order ID:{} You order status has been updated'.format(order.id), 'dummyguy1680@gmail.com', ['dummyguy1680@gmail.com'], ) return None -
Changing language on login page does not work
I have a working login system after the user logs in. views.py def change_language(request): from django.conf import settings response = HttpResponseRedirect('/') if request.method == 'POST': language = request.POST.get('language') if language: if language != settings.LANGUAGE_CODE and [lang for lang in settings.LANGUAGES if lang[0] == language]: redirect_path = f'/{language}/' elif language == settings.LANGUAGE_CODE: redirect_path = '/' else: return response from django.utils import translation translation.activate(language) response = HttpResponseRedirect(redirect_path) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) return response Change language button <form action="{% url 'change_language' %}" method="post"> {% csrf_token %} <select name="language"> {% get_available_languages as LANGUAGES %} {% for language in LANGUAGES %} <option value="{{ language.0 }}" {% if language.0 == LANGUAGE_CODE %} selected{% endif %}> {{ language.0|language_name_local }} ({{ language.0 }}) </option> {% endfor %} </select> <input type="submit" value="Change language"> However on my login page, /accounts/login/?next=/, after changing language, instead of getting /pl/accounts/login/?next=/, which would translate the page, I get /accounts/login/?next=/pl/, which translate pages after login for me but that is not what I wanted. Also, if I try to change my language on my registration page /accounts/sign_up/ it redirects me again to /accounts/login/?next=/pl/ Basically, if the user is not logged in, change_language option redirects him to the login page but there is no @login_required decorator so I … -
How to resolve CyclicDefinitionError in factory_boy SubFactory call?
I have following models # in ModelA_App/models.py class ModelA(models.Model): TYPEA = 1 TYPEB = 2 TYPE_CHOICES = ( (TYPEA, 'TypeA'), (TYPEB, 'TypeB') ) type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES) name - models.CharField(max_length = 100) #in ModelB_App/models.py from ModelA_App.models import ModelA class ModelB(models.Model): label = models.TextFiled() model_a = models.OneToOneField(ModelA, on_delete=models.CASCADE) And I have following factories: #in ModelA_App/factories.py class ModelAFactory(factory.django.DjangoModelFactory): class Meta: model = ModelA name = factory.Faker('word') type = ModelA.TYPEA #in ModelB_App/factories.py from ModelA_App.models import ModelA from ModelA_App.factories import ModelAFactory class ModelBFactory(factory.django.DjangoModelFactory): class Meta: model = ModelB label = factory.Faker('text') model_a = SubFactory(ModelAFactory, type = factory.LazyAttribute(lambda o: '%d' % o.type)) class Params: type = ModelA.TYPEA I'd like to be able to create ModelB object with ModelA having TYPEB. Trying line ModelBFactory.create(type = ModelA.TYPEB) results in error: factory.errors.CyclicDefinitionError: Cyclic lazy attribute definition for 'type'; cycle found in ['type'] . How I can fix that? -
How to return specific field queryset DRF
I want to create a custom queryset class that returns different fields to pre-define two cases. 1st when DateField is greater than today and 2nd when it's less than today. In case it's greater return all fields, else return only date_to_open and post_name fields. views.py class GroupDetail(generics.RetrieveAPIView): serializer_class = serializers.GroupDetailsSerializer permission_classes = (IsAuthenticated, ) def greater(self): return models.Group.objects.filter(shared_to=self.request.user, date_to_open__gt=timezone.now()).exists() def get_queryset(self, *args, **kwargs): if self.greater(): query_set = models.Group.objects.filter(shared_to=self.request.user, date_to_open__gt=timezone.now()) else: query_set = SPECIFIC FIELDS return query_set serializers.py class GroupDetailsSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.name') images = GroupImageSerializer(many=True, read_only=True) shared_to = serializers.SlugRelatedField(queryset=models.UserProfile.objects.all(), slug_field='name', many=True) class Meta: model = models.Group fields = ('id', 'group_name', 'owner', 'group_text', 'created_on', 'date_to_open', 'shared_to', 'images', )