Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form looping closing tag
i'm trying to submit more than one form with one button using this as an example. The difference is that i'm adding forms dynamically using this code: {% load crispy_forms_tags %} <form method="POST" action="{% url 'App:Submit' %}"> {% csrf_token %} {% for form in forms %} <h3>Hour {{ form.Hour }}: </h3> <form> {% csrf_token %} {{ form|crispy }} </form> <br> {% endfor %} <br> <div class="col text-center"> <button class="btn btn-primary" type="submit">Send</button> </div> </form> Using this example, in Chrome, the main <form> tag with the action closes after the first loop. Any idea why this is happening? Thanks -
How to create if statement on a redirect to change Django model
I am trying to create a if statement in my Django view that detects when I am redirected to my complete order url. I want to do this because I would like to change my Django model Order 'complete' field to true. My redirect is coming from a javascript function in my paypal intergration. checkout.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Checkout</h1> <div class='container'> <div class='row'> <div class='col-6'> <form action="" method='post' id='payement-form'> {% csrf_token %} <!-- {{ form|crispy }} --> <div class='col-12' id='paypal-button-container'></div> </form> <script src="https://www.paypal.com/sdk/js?client-id="> // Required. Replace YOUR_CLIENT_ID with your sandbox client ID. </script> <script> function redirect() { var url = "{% url 'complete-order' %}" window.location.href = url } paypal.Buttons({ createOrder: function (data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '0.01' } }] }); }, onApprove: function (data, actions) { // This function captures the funds from the transaction. return actions.order.capture().then(function (details) { // This function is the redirect redirect() alert('Transaction completed by ' + details.payer.name.given_name); }); } }).render('#paypal-button-container'); </script> </div> {% endblock content %} views.py @login_required(login_url='login') def checkout(request): order = Order.objects.get(user=request.user, complete=False) context = { 'order': order } return render(request, 'videogames/checkout.html', context) @login_required(login_url='login') def paymentComplete(request): order = Order.objects.get(user=request.user, complete=True) … -
Django admin.TabularInline function in a ModelForm outside the admin
Is there any way to replicate the TabularInline function outside the admin? I'm working with this model: class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools") gene_cand_lists = models.ManyToManyField(GeneCandList, through='SamplePoolIndexCand', through_fields=('sample_id', 'gene_cand_list_id'), blank=True, verbose_name="Llista de gens candidats") class Meta: db_table = 'sample' The intermediate table is: class SamplePoolIndexCand(models.Model): sample_id = models.ForeignKey(Sample, null=True, blank=True, on_delete=models.CASCADE, db_column='id_sample', verbose_name='Mostra') pool_id = models.ForeignKey(Pool, null=True, blank=True, on_delete=models.CASCADE, db_column='id_pool', verbose_name='Pool') index_id = models.ForeignKey(Index, null=True, blank=True, on_delete=models.CASCADE, db_column='id_index', verbose_name='Índex') gene_cand_list_id = models.ForeignKey(GeneCandList, null=True, blank=True, on_delete=models.CASCADE, db_column='id_gene_cand_list', verbose_name='Llista de gens candidats') class Meta: unique_together = (("sample_id", "pool_id", "index_id", "gene_cand_list_id"),) db_table = 'sample_pool_index_cand' Using TabularInline in the admin I can do this to enter multiple set of values to one sample: Is there an easy way to do this in a ModelForm? -
Django user login or sign up not working. Does Django 3.2 have backwards compatibility?
I created a Django project with Django==2.8. And after implementing the login page everything works fine. but another collaborator pulled my code but he used Django==3.2 and compiled using that. Since then my login or create user does not work. It redirects to the same page with username and password both in the URL. The project still works when I run the server but most of the backend does not work. -
Why request.POST.get always empty in Django when using with react?
I am using react with Django framework and not Django rest framework and when I send a post request from react side, the request.POST.get('token', '') is always empty. token = request.POST.get("token") I tried many things like changing content type using request.data instead but nothing is working. Can anyone please tell Why I am not getting the post variable? -
Django server returns Authentication Error
my Django server that is deployed on Linux server returns 401 authentication error even though jwt token is included in the request. It works fine on my local machine, but after I deployed on a server and tried Get, Post request from postman, it returned 401 authentication error. I"m using Django Rest Framework, corsheader, JWT token. here is my source code. setings.py import os from datetime import timedelta from django.urls import reverse from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! try: from .secret_key import * except ImportError: pass # Application definition INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'users', 'invitations', 'dm', 'posts', 'corsheaders', "rest_framework_serializer_field_permissions", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '[アプリ名].urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'evers_backend.wsgi.application' ASGI_APPLICATION … -
Use Phone number Field In AbstractBaseUser Django
I am Using This Package, But When I Want To Build The Database And Migrates, It Gives Me an Error: "ImportError: Module 'Accounts.apps' does not contain a 'AccountsConfigphonenumber_field' class. Choices are: 'AccountsConfig'." How Can I Use Another Package App In The Base User Model? Models.py: class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=200) phone_number = PhoneNumberField(unique=True) address = models.TextField(max_length=1000) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = 'phone_number' objects = UserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin Settings (This Section): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Accounts.apps.AccountsConfig' 'phonenumber_field', ] AUTH_USER_MODEL = 'Accounts.User' Forms.py: from django import forms from .models import User from django.contrib.auth.forms import ReadOnlyPasswordHashField from phonenumber_field.modelfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget class UserCreationForm(forms.ModelForm): phone_number = PhoneNumberField(widget=PhoneNumberPrefixWidget(initial='IR')) password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'password', 'phone_number') class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = User fields = '__all_ Managers.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, phone_number, password=None): if not email: raise ValueError('Users Must Have An Email Address') if not phone_number: raise ValueError('Users Must Have A Phone … -
couldn't apply migrations from django to mssql
python manage.py migrate Operations to perform: Apply all migrations: Likes, admin, auth, contenttypes, sessions, store, tags Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "C:\Users\Sulaiman\Desktop\jango\manage.py", line 22, in main() File "C:\Users\Sulaiman\Desktop\jango\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\operations\models.py", line 528, in database_forwards alter_together( File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\sql_server\pyodbc\schema.py", line 156, in alter_unique_together self.execute(sql) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\sql_server\pyodbc\schema.py", line 861, in execute sql = str(sql) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\backends\ddl_references.py", line 201, in str return self.template % self.parts KeyError: 'include' -
Django REST Framework unable to send multiple data
I am trying to send multiple JSON data in a single POST as a list like - [ { "name": "data", }, { "name": "data", } ] but getting the following error. { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } Here are my codes - Serializers.py class my_serializer_name(serializers.ModelSerializer): class Meta: model = my_model fields = '__all__' def validate(self, data): #Performing validation ...... ...... viewsets.py class my_viewset(viewsets.ModelViewSet): queryset = models.my_model.objects.all() serializer_class = serializers.my_serializer http_method_names = ['get', 'post'] def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() serializer = serializers.my_serializer(queryset, many=True) return Response(serializer.data) router.py router = routers.DefaultRouter() router.register('name' , my_viewset) How to solve this issue? -
What does GEOSGeometry exactly
Sorry it may be absurde but I got confused. I have seen two ways of creating a Polygon. from django.contrib.gis.geos import GEOSGeometry, LineString, Polygon 1- geometry = GEOSGeometry(Polygon(coordinates, srid=4326)) 2- geometry = Polygon(coordinates, srid=4326) Why is it important to add GEOSGeometry instead of just using the 2) ? -
ERROR: Could not build wheels for couchbase which use PEP 517 and cannot be installed directly
I am following the couchbase documentation and tried to install the python SDK and I am getting the above error. sudo -H python3 -m pip install couchbase I am using pipenv for my virtual environment. -
Django error : object has no attribute 'resolve_expression'
Can you give me a hint where to look or what to look for? Using Python 3.7.9 and Django 3.1.8, I have the following exception when in DEBUG mode. The problem does not appear when running in normal mode. The problem is new, it was first seen this week (it might have been there before). Going back in git does not help, the problem is still there. There is a lot of code changed. Can you please give me a hint or a solution? Django is new for me and I do not know how to tackle the issue. Exception has occurred: AttributeError (note: full exception trace is shown but execution is paused at: __getattribute__) 'Organization' object has no attribute 'resolve_expression' File "****/legal_entity/submodels/organization.py", line 416, in __getattribute__ (Current frame) return super().__getattribute__(name) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1062, in resolve_lookup_value if hasattr(value, 'resolve_expression'): File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1267, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1380, in _add_q split_subq=split_subq, check_filterable=check_filterable, File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "****/core/subserializers/abstract/business_object.py", line … -
How to handle Many-to-Many Relation in Django without an Intermediary Table?
I have inherited a weird table structure: class Customer(models.Model): account_number = models.CharField() class Subscription(models.Model): account_number = models.CharField() So the Customer and Subscription models are linked by their account numbers. Each customer can have multiple subscriptions, and each subscription can have multiple customers, but there is no intermediary table; there is no "Account" table. How do I handle this sort of thing? If I have a Subscription queryset, how do I go about getting the corresponding Customer queryset without doing a horribly long query like customers = Customer.objects.filter(account_number__in=list(subscriptions.values_list('account_number', flat=True))) I'm trying to avoid this because it would generate a massive query that would take a very long time to execute. -
Issue passing id into url attempting fetch in Django
I'm trying to get the user post from jsonplaceholder. I get the user id from the users endpoint, and from there I'm trying to go to the user posts endpoint. With the 'print(context)' that is in views.py I correctly get the json data of the user I passed in the 'all_users' view, but I'm getting NoReverseMatch at /users/1/ Reverse for 'user' with no arguments not found. 1 pattern(s) tried: ['users/(?P<id>[^/]+)/$'] views.py def user(request, id): response = requests.get(placeholder_url + 'users/' + str(id) + '/posts') user = response.json() context = { 'user': user } print(context) return render(request, 'user.html', context) urls.py urlpatterns = [ path('users/', all_users, name='users'), path('users/<str:id>/', user, name='user') ] users.html <p class="card-text">{{ user.email }}</p> <a href="{% url 'user' user.id %}" class="btn btn-outline-primary">See Posts</a> -
Django REST Framework - How to display an APIException if HTTP_400_BAD_REQUEST?
I'm new to DRF and just have setup my first usable POST endpoint, please see my code to create a new User object using POST: views.py: @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): if request.method == 'POST': serializer = CreateUserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return JsonResponse(serializer.data, safe=False) serializers.py class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('user', 'password') extra_kwargs = {'password': {'write_only': True}} # We don't want to show the hashed password def create(self, validated_data): password = validated_data.pop('password') user = User.objects.create_user( validated_data['user'], ) user.set_password(password) user.save() return user So far so good. If I now want to create a User Object using POST it works fine for the first time. But if I send the same request twice, the second request just returns "Bad Request". That also makes sense as the User object is already existing. It would be awesome if I would be able to catch this exception somehow and return a message instead of HTTP_400_BAD_REQUEST. So I checked the DRF docs right here, https://www.django-rest-framework.org/api-guide/exceptions/ It says: Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned … -
django select filtered related object
I have 3 models: class ForumTopic(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=100) class ForumMessage(models.Model): topic = models.ForeignKey(ForumTopic, on_delete=models.CASCADE) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) class ForumMessageVote(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) message = models.ForeignKey(ForumMessage, on_delete=models.CASCADE) vote = models.IntegerField(default=0) I want to select all ForumMessage for specific ForumTopic and attach to result of this query ForumMessageVote filtered by specific User and current ForumMessage. How I can do this? -
Duplicated element after Ajax run
I am trying to Auto-complete form fields using Ajax and Jquery. First I used Django and the views.py function is: def CreateWellMon(request): if request.method == 'POST': form = SurveillanceDesPuits_F(request.POST or None) if form.is_valid(): form.instance.author = request.user form.save() return redirect('WellMonitor') else: try: PUITS_id = request.GET.get('PUITS') record = SurveillanceDesPuits.objects.filter(PUITS_id__id__exact=PUITS_id)[:1] record2 = SurveillanceDesPuits.objects.get(id= record[0].id) form = SurveillanceDesPuits_F(instance=record2) return render(request, 'measure/Surveill_Wells/Add_wellMntr2.html', {'form': form}) except: record2 = SurveillanceDesPuits.objects.all().first() form = SurveillanceDesPuits_F(instance=record2) return render(request, 'measure/Surveill_Wells/Add_wellMntr2.html', {'form': form}) So here I just selected the last record from the database at first. After when the user chooses a Well it reloads the last record of the element. my HTML page code is: {% extends 'Home/base2.html' %} {% block content %} {% load crispy_forms_tags %} <div class="w3-panel w3-border w3-light-grey w3-round-large sizeA"> <h2>Well Information</h2> <h2 class="border-bottom pb-1 mb-3"><b>Add New montoring record 3</b></h2> </div> {% if form %} <div class="border p-3 mb-3 mt-3 w3-round-large w3-light-grey border-dark"> <form method="POST" id="SurveillanceDesPuits_F" data-record-url="{% url 'Add_wellMntr' %}"> {% csrf_token %} <!-- form from views.py--> <div class="border p-2 mb-3 mt-3 border-secondary"> <div class="form-row"> <div id= "PUITS" class="form-group col-md-3 mb-0"> {{form.PUITS|as_crispy_field}} </div> <div class="form-group col-md-3 mb-0"> {{ form.CS |as_crispy_field}} </div> <div class="form-group col-md-3 mb-0"> {{ form.MODE|as_crispy_field}} </div> <div class="form-group col-md-3 mb-0"> {{ form.SITUATION |as_crispy_field}} </div> </div> <div … -
Cannot assign "'somedata'": "otherdatal" must be a "" instance.`
is it possible to insert the session value to the foreign key.? here i have 2 models class candidate(models.Model): fname=models.CharField("First name ",max_length=20,default="") lname=models.CharField("Last name ",max_length=20,default="") email=models.EmailField("Email ",max_length=254,primary_key=True) password=models.CharField("Password ",max_length=100,default="") def __str__(self): return self.email #self.fname+" " +self.lname here iam taking the email from above model as a session and trying to put this session value to the foreign key field of the below model class canDetails(models.Model): candEmail=models.ForeignKey(candidate,on_delete=models.CASCADE) location=models.CharField("location ",max_length=30) role=models.CharField("role ",max_length=20) cv=models.FileField(upload_to="media/canDetails/") def __str__(self): return self.candEmail but here i am getting error like Cannot assign "'cb@gmail.com'": "canDetails.candEmail" must be a "candidate" instance. i am trying to get all the details from candidate model and candDetails model at once thats why i using pf and fk here,so is it the right way i am following...? how can i deal with this ? any suggestions pls.? -
Heroku / Redis Connection error on Python/Django Project
I'm trying to set up django so it send automatic email when a certain date in my models i reached. However i setup a Heroku-Redis server and am trying to connect to it. I created a simple task to test out if celery is working but it always returns the following error: Error while reading from socket: (10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None) I setup celery according to the website: celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'incFleet.settings') app = Celery('incFleet') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Tasks.py import datetime from celery import shared_task, task from time import sleep from .models import trucks from datetime import datetime @shared_task() def sleepy(duration): sleep(duration) return 0 #@shared_task() #def send_warning(): And my settings.py # Celery Broker - Redis CELERY_BROKER_URL = 'redis://:p0445df1196b44ba70a9bd0c84545315fec8a5dcbd77c8e8c4bd22ff4cd0a2ff4@ec2-54-167-58-171.compute-1.amazonaws.com:11900/' CELERY_RESULT_BACKEND = 'redis://:p0445df1196b44ba70a9bd0c84545315fec8a5dcbd77c8e8c4bd22ff4cd0a2ff4@ec2-54-167-58-171.compute-1.amazonaws.com:11900/' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' -
Why is this django annotated queryset with rawSQL values not set but raw query returns results?
The problem I have is the django queryset does not contain the data from raw sql query interfaces = Interface.objects.filter( membership__in=membership_set ).annotate( utilisation=RawSQL( 'SELECT utilisation FROM interfacestat WHERE interface.name = interfacestat.ifl AND interfacestat.date = "%s"' ,(recent_date,) ), ).order_by('name') So I am using a RawSQL expression to populate the utilisation field. I check the raw sql with print(interfaces.query) and run that directly on MySQL. It returns results for the utilisation field on a few records - however when I loop through the queryset the utilisation field is always unset (None). eg. interfaces[0].__dict__ {'_state': <django.db.models.base.ModelState object at 0x109b1fdf0>, 'id': 230083, 'name': 'ae1.3216', ...'utilisation': None} Looping through: ipdb> all = interfaces.values() ipdb> for item in all: print(item.get('utilisation')) None None None None None None None None None None None None None -
Heroku error while deploying. error: RPC failed; HTTP 504 curl 22 The requested URL returned error: 504
I had no problems in the past with the deployment to Heroku via HTTP transport, but recently I am unable to deploy. This is the error I am getting: Enumerating objects: 58668, done. Counting objects: 100% (57434/57434), done. Delta compression using up to 16 threads Compressing objects: 100% (16705/16705), done. Writing objects: 100% (57124/57124), 50.77 MiB | 76.23 MiB/s, done. Total 57124 (delta 44149), reused 52353 (delta 40249) error: RPC failed; HTTP 504 curl 22 The requested URL returned error: 504 fatal: the remote end hung up unexpectedly fatal: the remote end hung up unexpectedly I've tried switching to SSH transport and it works, but Heroku is retiring SSH transport, so I need to figure out this error. Also I tried to change the postBuffer according to atlassian's page, but I got the error again. git config --global http.postBuffer 157286400 Does anybody have an idea how to solve this? There are very few resources on the web that I found, and none of them are fixing the problem. -
Django-q how to delete scheduled tasks from code
I use django-q to schedule a periodic task associated an entry in my model Repository (code here after). But when I delete a Repository entry, the associated Schedule entry is not deleted, and so the django-q jobs associated is not cancelled. Any idea ? from django_q.models import Schedule class Repository(models.Model): id = models.AutoField(primary_key=True) [...] scheduled_scan = models.ForeignKey(Schedule, on_delete=models.CASCADE, default=None, blank=True, null=True) thanks a lot -
Django Channels full image path
If I want to get full image path in django rest I just need to write something like this: def get(self, request) qs = SomeModel.objects.all() serializer = SomeSerializer(qs, many=True, context={'request': request}) return Response(serializer.data) And then the result will be { "image": "http://127.0.0.1:8000/media/someimg.png" } But there is no request django channels. I know that there is self.scope but it can't be used like request. Is there any option to get request or even some class with build_absolute_uri() function inside consumer? Here is some of my code: Consumers: # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user = self.scope['user'] chat_room = ChatRoom.objects.get(pk=self.room_name) message = Message.objects.create(author=user, chat_room=chat_room, content=message).pk # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] serializer = WSMessageSerializer(Message.objects.get(pk=message)) # Send message to WebSocket self.send(text_data=json.dumps(serializer.data)) WSMessageSerializer: class WSMessageSerializer(serializers.ModelSerializer): author = FriendSerializer() class Meta: model = Message fields = ['id', 'author', 'content', 'created_at'] FriendSerializer: class FriendSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ['id', 'username', 'first_name', 'last_name', 'full_name', 'pfp'] -
Clean way to customize forms based on user's group in Django
I want to customize my model's forms based on user's group. The customization that I am talking about are small, but to give you an idea, my "customizations" would be something like : users within GroupA would have a BooleanField with True as default, even though default is False for others users within GroupB would have a CharField (input text) hidden (not changeable) users within groupC would have not the same options as others for a CharField with options (different options in select) ... Currently, I actually achieved to do this by doing a mix of logic in my views.py and in my forms.py. But I don't really like to mix logic in 2 different files, so I came to ask your opinion about which is the best (cleanest) way in your opinion and how to achieve it. Here are the 2 technics that I think of: 1. Creating a form for each group in forms.py. This would be the cleanest way imo. By creating a form for every group (MyModelGroupAForm(ModelForm), MyModelGroupBForm(ModelForm), ...) , I can easily change a field/input/... in my forms.py file everytime that a change is requested and/or a group is created. Then, all I have to … -
django filter for NOT IN as lookup_expr
We can make the django filter with "in" expression sending comma separated string. Such as import django_filters class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter): pass class BookFilter(django_filters.FilterSet): author = NumberInFilter(field_name="author__id", lookup_expr="in") However, I was looking for way to send comma separated query-data and get response which do not have the query-data. something like class BookFilter(django_filters.FilterSet): author = NumberInFilter(field_name="author__id", lookup_expr="not_in") Definitely there is nothing like "not_in". Can you please give me a solution to achieve this?