Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and redis adding :1 to keys
I'm using django-redis to store some data on my website, and I have a problem where Redis is adding :1 at the beginning so my key looks like this: :1:my_key I'm not sure why is it doing this, I've read the documentation on django-redis and I couldn't find anything related, so my guess it has something to do with redis but I can't figure out what. In my settings.py I have the regular: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://xxxxx/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } And in my tasks.py I set keys like the documentation says: from django.core.cache import cache cache.set(my_key, my_value, 3600) So now I can't get the values using the cache.get(my_key) -
Django gives error at {% result_list cl %} when accessing models
unsupported operand type(s) for +: 'Listing' and 'float' Error Django admin The error seems to only happen when trying to access the models on the admin page, whats the cause? Views.py -
Unable to log-in in admi site using aadhaar no in django using custom model
I created a custom django model where I used aadhar number as USER_FIELD which does not give me any error but after creating the superuser I can't log-in in the admin site of django. -
How to solve 'NoneType' object has no attribute 'fields' in Graphene-django
Have this mutation class AddStudentMutation(graphene.Mutation): class Arguments: input = StudentInputType() student = graphene.Field(StudentType) @classmethod @staff_member_required def mutate(cls, root, info, input): try: _student = Student.objects.create(**input) except IntegrityError: raise Exception("Student already created") return AddStudentMutation(student=_student) Before executing the above mutation in graphiql, I add the request header "Authorization": "JWT <token>" so that the user is authorized. But I get the error graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'fields'. The error doesn't occur when I remove the header. It also works fine when I include it in requests for queries. Am I doing something wrong? I need the authorization to happen for mutations too. I tracked the Traceback and it leads to file .../site-packages\graphql_jwt\middleware.py. It appears it's a bug in the package in function allow_any() line 18 field = info.schema.get_type(operation_name).fields.get(info.field_name). New to this I need help. I'm using graphene-django==2.15.0 and django-graphql-jwt==0.3.4 -
Django with django-tenant, unable to perform migrations
Context I am trying to setup django-tenants for my Django application by following the official installation guide. My Django app used to run perfectly fine when I ran manage.py runserver. My settings.py looks exactly as in the guide: SHARED_APPS = ( 'django_tenants', 'iam', # the tenant models (Client & Domain) reside in this app 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... ) TENANT_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', ... ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ... # rest of middleware ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # the option for django-tenant 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { "ENGINE": 'django_tenants.postgresql_backend', ... # other db settings } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "iam.Client" TENANT_DOMAIN_MODEL = "iam.Domain" Problem After following all the steps in the installation guide I try to use python manage.py migrate_schemas --shared. This results in the following stacktrace: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File … -
Django inline formsets with Class-based view
I'm trying to do Django class-based CreateView inline formsets. I have a product model and a productImage model and productImage is inline everything looks fine but after i submit my product the images that are selected in formset will not save. Here is my code models.py: class Product(models.Model): name=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True), description=models.TextField(blank=True), vector_column=SearchVectorField(null=True, editable=False), meta={"indexes": (GinIndex(fields=["vector_column"]),)} category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%y/%m/%d') def __str__(self): return self.product.name views.py class ProductCreate(StaffAccessMixin, ProductFormValidMixin, ProductFieldsMixin, CreateView): model = Product def get_context_data(self, **kwargs): context = super(ProductCreate, self).get_context_data(**kwargs) if self.request.POST: context['product_image_formset'] = ProductImageFormset(self.request.POST) else: context['product_image_formset'] = ProductImageFormset() return context template_name = 'products/product-create-update.html' ProductFormValidMixin: class ProductFormValidMixin(): def form_valid(self, form): context = self.get_context_data() product_image_formset = context['product_image_formset'] if self.request.user.is_superuser: self.obj = form.save() if product_image_formset.is_valid(): product_image_formset.instance = self.obj product_image_formset.save() return redirect('administration:product-update', pk=self.obj.pk) else: self.obj = form.save(commit=False) self.obj.available = False return super().form_valid(form) ProductFieldsMixin: class ProductFieldsMixin(): def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: self.fields = ["name", "slug", "description", "category", "price", "available", "image", ] else: raise Http404 return super().dispatch(request, *args, **kwargs) forms.py: from django.forms.models import inlineformset_factory from .models import Product, ProductImage ProductImageFormset = inlineformset_factory(Product, ProductImage, fields=('image',), extra=3) Formset template: … -
How to automatically add repeated data migrations in Django using Djangos ORM?
I am new to Django and have read the basic and advanced tutorial along with some parts of the documentation on migrations and data migrations: https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations Also, I have read about fixtures but this seems to be suitable only for initial data provision: https://docs.djangoproject.com/en/4.0/howto/initial-data/#providing-data-with-fixtures The task I want to accomplish is to bulk insert data repeatedly from "outside" in a clean way using using Djangos ORM and all the benefits of migrations. So far, I haven't found a full example on how to do this because using the first option of data migration would require to touch a file everytime I insert/migrate new data. Any hints on how to accomplish this or am I missing something? Thanks in advance! -
django passing id in popup
In my Django project, I want to edit users from the user list on the popup {%for data in data%} <tr> <td>{{data.firstname}}</td> <td>{{data.phonenumber}}</td> <td> <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> view Savings </button> </td> </tr> {%endfor%} popup <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header" style="background-color:#136de4;color:white" > <h5 class="modal-title" id="staticBackdropLabel">Edit Profile</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="card-body"> <form method="post" id="formOne"> {% csrf_token %} {{form.as_p}} <div class="modal-footer"> <a href="{%url 'customer:savingsprofile' data.id%}"><button type="submit" class=" btn bg-gradient-info text-white btn-sm m-1" data-bs-dismiss="modal">Save Changes</button></a> </div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> but on the popup it is showing only the first (while clicking another row) data of the table -
Django customize Label of form
whenever I add a Labels to ModelForm, the Label will look in the HTML like this: #v check this colon <label for="id_url">URL:</label> When I created the labels like this: class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url', ) labels = { 'title': 'Title', 'url': 'URL' Where do the colons at the end of the Label in the HTML come from and how to remove them? -
Run periodic celery task with a dynamic schedule in django application
I am wondering if it is possible to have my end users dynamically adjust the schedule of a periodic task. So something along these lines: # celery.py def get_schedule(): config = get_user_config() # returns a model object of sorts return config.frequency_in_seconds app.conf.beat_schedule = { 'my_periodic_task': { 'task': 'my_periodic_task', 'schedule': get_schedule, # schedule updated based on `get_schedule` function }, } This way, if a user were to change the frequency_in_seconds field in their user config setting, it would dynamically update the beat schedule. My preference would be to do this outside of the Django Admin site and without any additional packages (e.g. django-celery-beat). Any thoughts or ideas would be much appreciated. Thanks -
How can I join two serilaizers in django rest framework that have a similar field value
I have two models in my Django Restframework. In my views I want to get all properties and for each property I get Profile data of that user who created it. How can I achieve this? example: #models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=200) location = models.CharField(max_length=200) class Properties(models.Model): title = models.CharField(max_length=200) price = models.CharField(max_length=200) category = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE) #serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = [ 'title','price','category','created_by' ] #views.py class PropertiesView(generics.ListAPIView): serializer = PropertySerializer queryset = Property.objects.all() -
User generated item multiple choice field Django
I am looking for a way to have a multiple choice field populated with choices made by a user. For example, they could have the following 3 entries: Yes, No, Unsure. I want a way to be translate this to a model. I understand this can be done with pre-defined options using a CharField, or ChoiceField, but I haven't seen anything with "dynamic" data, such as user-generated data. -
Run node things in docker (Django, Angular)
A have a frontend(angular) project inside a backend(django) project with this structure [structure][1] compose.yml services: db: image: postgres:13-alpine container_name: db restart: always env_file: .env.dev environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=stage - POSTGRES_PASSWORD=stage - POSTGRES_DB=stage volumes: - postgres_data:/var/lib/postgresql/data/ web: build: context: . dockerfile: Dockerfile image: web container_name: web env_file: .env.dev environment: - POSTGRES_USER=stage - POSTGRES_PASSWORD=stage - POSTGRES_DB=stage restart: always volumes: - ./:/leostudy links: - db depends_on: - db ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" redis: image: "redis:alpine" expose: - 6379 celery: restart: always build: context: . command: celery -A students worker -l info env_file: - ./.env.dev volumes: - ./:/leostudy/ depends_on: - db - redis - web volumes: postgres_data: Dockerfile # set work directory WORKDIR /proj # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev libffi-dev openssl-dev RUN apk --update add \ build-base \ jpeg-dev \ zlib-dev # install dependencies COPY ./requirements.txt . RUN pip install --upgrade pip \ && pip install -U pip setuptools \ && pip install -r requirements.txt # copy project COPY . . # run entrypoint.sh RUN ["chmod", "+x", "./entrypoint.sh"] ENTRYPOINT ["./entrypoint.sh"] So, I need to somehow build static with gulp … -
Django for loop data not displaying in template
I am not saving data in my data base. I am using an api service and I don't want to to save those api data in my data base. I just want to display those data in my html template. The problem only first data of for loop showing in template where I can see all for loop data from my terminal. I want to display my all for loop data in my html template. here is my code: views.py: for i in results[search_type]: if search_type == "organic_results": title = i["title"] print(title) context = {"title":title} I know I can use append method but it's showing all data together in my template as list. I want to so theme in my template using for loop like this: html {%for i in title %}{{i}}{%endfor%} my terminal result: Facebook - Log In or Sign Up https://www.facebook.com/ Newsroom | Meta - Facebook https://about.fb.com/news/ Facebook - Apps on Google Play https://play.google.com/store/apps/details?id=com.facebook.katana&hl=en_US&gl=US Facebook - Wikipedia https://en.wikipedia.org/wiki/Facebook Facebook Careers | Do the Most Meaningful Work of Your ... https://www.facebookcareers.com/ Facebook - Twitter https://twitter.com/facebook why only first data of for loop showing in my template? -
django.db.utils.OperationalError: fe_sendauth: no password supplied despite having supplied password in settings.py
I am trying to do python manage.py migrate to do migrations for my django app but i keep getting this error even though i have supplied the db name, user, password in settings.py. Any help will be appreciated. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accountant', 'USER': 'json', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '5432' } } Full stacktrace: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/json/anaconda3/envs/py33/lib/python3.8/site-packages/django/db/backends/base/base.py", line 130, in … -
Middleware in django keeps redirecting, visiting admin-site not possible
I am writing a django project where I need to separate the pages and the accounts. Do to so, I wrote a LoginCheckMiddleWare. The problem is that I am not able to visit the django-admin site anymore, because it keeps redirecting me. I don't what I did wrong. I also have an EmailBackEnd.py file, that I use for logging in with the email and not the username. LoginCheckMiddleWare.py from django.http.response import HttpResponseRedirect from django.urls import reverse from django.utils.deprecation import MiddlewareMixin class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): modulename = view_func.__module__ user = request.user if user.is_authenticated: if user.user_type == '1': if modulename == 'user.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('user:admin_index')) elif user.user_type == '2': if modulename == 'instructor.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('instructor:instructor_index')) elif user.user_type == '3': if modulename == 'student.views' or modulename == 'django.views.static': pass elif modulename == 'user.log_views': pass else: return HttpResponseRedirect(reverse('student:student_index')) else: return HttpResponseRedirect(reverse('user:login_user')) else: if request.path == reverse('user:login_user') or modulename == 'django.contrib.auth.views': pass else: return HttpResponseRedirect(reverse('user:login_user')) EmailBackEnd.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackEnd(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: … -
django multiple form separated in the html, merge again with submit
there is a formmodel like: class foo(forms.ModelForm): a = forms.BooleanField(label='a', required=False) b = forms.BooleanField(label='b', required=False) c = forms.BooleanField(label='c', required=False) d = forms.BooleanField(label='d', required=False) e = forms.BooleanField(label='e', required=False) f = forms.BooleanField(label='f', required=False) g = forms.BooleanField(label='g', required=False) h = forms.BooleanField(label='h', required=False) #... further there are multiple instances of foo in a list: L = [] L.append(foo(instance=object_1)) L.append(foo(instance=object_2)) L.append(foo(instance=object_3)) #... L.append(foo(instance=object_n)) this is shown on the html in different tables in different columns. The problem now is to send the data back correctly with subbmit. I have to put the tables and lines back together correctly. I was thinking of something like this: <form class="form-inline" action ="{% url 'bla:blo' %}" method="post"> Table #1 | ID of Form | Value #1 | Value #2 | Value #3 | Value #4 | | ---------- | -------- | -------- | -------- | -------- | <form id=1>| 1 | a1 | b1 | c1 | d1 |</form> <form id=2>| 2 | a2 | b2 | c2 | d2 |</form> <form id=3>| 3 | a3 | b3 | c3 | d3 |</form> <form id=4>| 4 | a4 | b4 | c4 | d4 |</form> Table #2 | ID of Form | Value #1 | Value #2 | Value … -
Django correct way to place form in template
this is my test model form class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url', ) It has two fields but for design reasons I need each input in a seperate DIV in the template like so (just an example) <form> <div> <input spellcheck="false" autocorrect="off" type="email" required="" name="re_email"> </div> <div> <input spellcheck="false" autocorrect="off" type="email" required="" name="re_email"> </div> </form> When I just add {{ form }} every input is in the form without a surrounding container. What is there correct way 2022 (not a Django 1.1 or 2016 tutorial) to place inputs manually in the template and then connect it with the model? -
AttributeError: type object 'x' has no attribute 'view'
i'm doing a project and I'm trying to incorporate the spotify API with it. Anyhow, i'm receiveing this error and really don't know how to get past it. Thanks in advanced, here is the code from views.py: from django.shortcuts import render from .credentials import REDIRECT_URI, CLIENT_SECRET, CLIENT_ID from rest_framework.views import APIView from requests import Request, post from rest_framework import status from rest_framework.response import Response class AuthURL(APIView): def get(self, request, format=None): scopes = 'user-read-playback-state user-modify-playback-state user-read-currently-playing' url = Request('GET', 'https://accounts.spotify.com/authorize', params={ 'scope': scopes, 'response-type': 'code', 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID }).prepare().url return Response({'url': url}, status=status.HTTP_200_OK) Here's the code of urls.py: from django.urls import path from .views import AuthURL urlpatterns = [ path('get-auth-url', AuthURL.view()), ] -
Can I override default CharField to ChoiceFoeld in a ModelForm?
I have a (horrible) database table that will be imported from a huge spreadsheet. The data in the fields is for human consumption and is full of "special cases" so its all stored as text. Going forwards, I'd like to impose a bit of discipline on what users are allowed to put into some of the fields. It's easy enough with custom form validators in most cases. However, there are a couple of fields for which the human interface ought to be a ChoiceField. Can I override the default form field type (CharField)? (To clarify, the model field is not and cannot be constrained by choices, because the historical data must be stored. I only want to constrain future additions to the table through the create view). class HorribleTable( models.Model): ... foo = models.CharField( max_length=16, blank=True, ... ) ... class AddHorribleTableEntryForm( models.Model) class Meta: model = HorribleTable fields = '__all__' # or a list if it helps FOO_CHOICES = (('square', 'Square'), ('rect', 'Rectangular'), ('circle', 'Circular') ) ...? -
React GET request from Django API is not working and how to solve this?
I am trying to build django-react application. I used netlify for react deployment and herokuapp for django api deployment. My api endpoint is working perfectly but my react can't fetch them from the actual endpoint. In localhost it fetch from my actual api [ http://cylindercommerce.herokuapp.com/api/products/ ] but in production it is trying to fetch from it's own url then end point [https://modest-knuth-50c56b.netlify.app/api/products] this one but it should fetch from [http://cylindercommerce.herokuapp.com/api/products/] this endpoint. I didn't change any code. so what is the problem here check the screenshot here -
How can I customize image properties in ckeditor using django
I want when I click on upload images I am directed directly to select images rather than being shown image properties box. Kindly help -
How do I update the records stored in my db using an html form as input?
I am very new to django and I have made an app that displays a different timetable for different user. I am stuck at this point where I can delete the records stored in my db but I am unable to update them through my html form. Is there a way to do this? Here are my files, models.py from pickle import TRUE from django.db import models from datetime import date from django.conf import settings class Timetable(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default = "", on_delete=models.CASCADE) subject = models.CharField(max_length=100) room_no= models.IntegerField() date = models.DateField(default=date.today) time = models.TimeField() semester = models.TextField() day = models.CharField(max_length=10, default="") views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required from .models import Timetable # Create your views here. def register(request): if request.method=='POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created, you are now able to login!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def tt(request): if request.user.is_authenticated: tt = Timetable.objects.filter(user=request.user).order_by('day') return render(request, 'users/time_table.html', {'tt': tt}) else: return render(request, 'homepage/home.html') @login_required def tt_add(request): return render(request, 'users/tt_add.html') @login_required def newPage(request): user=request.user sem = request.POST.get("semester") sub = request.POST.get("subject") room_no = … -
Conditional query in django [closed]
Am worried that it may cause any problem, as am using conditional querying paramters. Here is my query: data = Project.objects.filter(user=user if user.role == 1 else user.staff_to_id) In this, staff_to_idis just a self reference to a user to represents that this is a staff. So if Role == 1 then Projects will be fetched using "user" and when Role == 2 or something else it will Project will be fetched using "user.staff_to_id" Is this a bad practice ? -
Revisions not creating in TestCase ( Django, django-reversion, tests)
Trying to cover with tests django-reversion functionality for my model, but versions are not created in test db, in manual creation from admin interface everything works fine. Model: @reversion.register() class RuleSet(ModeratedBase, AdminUrlMixin): """Ruleset of a given type of contest related to the contest""" name = models.CharField( max_length=64, help_text="Short name of the ruleset.", unique=True ) rules = models.JSONField( default=dict, help_text="Base rules dict for Ruleset", blank=True, null=True, ) default_for = models.ManyToManyField( "ci_contest.ContestType", help_text="Field specifies content types ruleset is default for", related_name="default_ruleset", null=True, blank=True, ) def __str__(self): return self.name def get_versions(self): return Version.objects.get_for_object(self) Test: class RulesetTestCase(TestCase): fixtures = ["core-defaults", "gamer-defaults", "ledger-defaults", "contest-defaults"] def setUp(self): call_command("createinitialrevisions") self.ruleset = RuleSetFactory() def test_ruleset_get_versions(self): self.assertFalse(self.ruleset.get_versions().exists()) self.ruleset.rules = str(fake.pydict()) self.ruleset.save() print(self.ruleset.get_versions()) self.assertTrue(self.ruleset.get_versions().exists()) Print Output: <VersionQuerySet []>