Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.2 how to add model decimal fields together inside model
I am trying to add all the decimalfields numbers together to form a sum inside the model this is my model class Ataskaita(models.Model): class Meta: verbose_name_plural = 'Ataskaitos' bendrija = models.ForeignKey(Bendrija, on_delete=models.CASCADE, related_name="ataskaita") atlyginimas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) sodra = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) vmi = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) pvm_saskaitos_kvitas = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) bankines_operacijos = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) sum = models.DecimalField(max_digits=10, decimal_places=2) and I want to add all the fields (atlyginimas, sodra, vmi, pvm_saskaitos_kvitas, bankines_operacijos) together so I have all of their total I looked around stackoverflow and I think the only way to do it is to create a method, but I already tried it, and it wouldn't work as intended -
Adding a linebreak into a django form
beginner here! i've created a Django form and it works but all the fields are in the same line when i open the page, could someone help please? that's my code, it works but they all stay in the same line class NewListingForm(forms.Form): title = forms.CharField(label="Title", max_length=64) description = forms.CharField(label="Description", max_length=200) -
Django module installed in virtual environment but i get ModuleNotFoundError
I'm trying to use a module called reportlab, which i have installed through pip, i did check with pip list inside my environment and it does appear, but when i try to run my server i'm getting the module not found error. i tried to reinstall the package but same issue occurs, any suggestions? -
Why is django only reading admin url and not other url?
Why django is reading only admin url and not others?Even if I delete the admin url I can still browse it -
why does the child template get overriden by the templates in extends when using the django framework
for login.html this is what I have {% block content %} <h2>Tryin to Log In</h2> {% endblock content %}``` for base.html this is what I have {% block content %} <h2>base template</h2> {% endblock %} My problem is that the base.html overwrites the templates in login.html I have looked into the settings.py and this is what I have TEMPLATES = [ { ... 'DIRS': [BASE_DIR / "templates"], ... }, ] -
Got an error when try to use Social Auth backends fir dj-rest-auth app DRF
I wanted to add social media auth endpoints from dj-rest-auth third-party app. I did everything from the dj-rest-auth documentation. I am getting this strange error, though: File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 53, in dispatch return super().dispatch(*args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 130, in post self.serializer.is_valid(raise_exception=True) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 429, in run_validation value = self.validate(value) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 121, in validate user = self.get_auth_user(username, email, password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 96, in get_auth_user return self.get_auth_user_using_allauth(username, email, password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 62, in get_auth_user_using_allauth return self._validate_email(email, password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 30, in _validate_email user = self.authenticate(email=email, password=password) File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 26, in authenticate return … -
what is the correct way to automatically set a ForeignKey(User, on_delete=models.CASCADE) to the current loging in user
i need to auto set the model field "auther = models.ForeignKey(User, on_delete=models.CASCADE)" to the current authenticated user so that any posts created are automatically assigned to the user that created them... currently with my code the user has to select their own username in a drop down list. i would like to remove this and have that field auto filled out in the back end to prevent users picking the wrong username. here is my models.py class Task(models.Model): SELECT = 'None' GREEN = 'Green' AMBER = 'Amber' RED = 'Red' PRIORITY = [(SELECT, 'Select Priority'),(GREEN, 'Green'), (AMBER, 'Amber'),(RED, 'Red'),] auther = models.ForeignKey(User, on_delete=models.CASCADE,) priority = models.CharField(max_length=5,choices=PRIORITY,default=SELECT,) date = models.DateField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title + ' | ' + str(self.auther) def get_absolute_url(self): return reverse('task') def is_upperclass(self): return self.PRIORITY in {self.GREEN, self.AMBER} here is my views.py class TaskView(ListView): model = Task template_name = 'tasks.html' ordering = ['-id'] class AddTaskView(SuccessMessageMixin,CreateView): model = Task template_name = 'add_task.html' fields = ['priority','title','description'] success_message = " Task was created successfully" class UpdateTaskView(SuccessMessageMixin, UpdateView): model = Task template_name = 'update_task.html' fields = ['priority','title','description'] success_message = " Task was updated successfully" class DeleteTaskView(SuccessMessageMixin, DeleteView): model = Task template_name = 'delete_task.html' success_url = '/task/' … -
Auto conplete using js and json data
Hey I have a django website and Im trying to write an autocomplete searchfield using js Im returning a json response in django view in this format: [{'label':"Spider man no way home", 'link':"/movies/spider-man-no-way-home", 'img':"imgae url"},{...},{...},...] Im receiving the name of the movie from input(Search box) and writing query to db using a GET request: /search/movie?="the movie name" in script file ` $(function() { $("#search").autocomplete({ source: //"autocomplete.php", [ {id:"Wikipedia", value:"Wikipedia", label:"Wikipedia", uri: 'https://www.wikipedia.org/', img:"https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"}, {id:"Google", value:"Google", label:"Google", uri: 'https://www.google.com', img:"https://www.buro210.nl/wp-content/uploads/2017/05/google-logo-icon-PNG-Transparent-Background-e1495781274381.png"} ], minLength: 1, select: function(event, ui) { //console.log(ui.item); //var url = ui.item.uri; //if(url !== '') { location.href = ui.item.uri; //} }, html: true, open: function(event, ui) { $(".ui-autocomplete").css("z-index", 1000); } }) .autocomplete( "instance" )._renderItem = function( ul, item ) { return $( "<li><div><img src='"+item.img+"'><span>"+item.value+"</span></a></div></li>" ).appendTo( ul ); }; }); ` I found this code in this page It works fine, but I wanna make it dynamic by an event listener that fetchs data from db this is how I fetch data: ` let all_data = []; searchinput.addEventListener("input", (e) => { fetch('/search/?movie=' + e.target.value) .then(response => response.json()) .then(data => { all_data = data }) }) ` if I pass the all_data array to source It's empty because the inpur is empty and … -
: could not translate host name "DB" to address: Temporary failure in name resolution
I was using docker for a project, and tried creating a second container for my postgresql database, when i run the command docker-compose up -d, the command line shows something like this:- - Container postgresql-DB-1 Started 1.4s - Container postgresql-web-1 Running And when I run docker-compose logs for the first time, the command line shows that everything is fine. However, when I run it a second time, it shows the error mentioned in the question title, and after that it keeps showing that error when I try to do anything with the docker commands Here's my Dockerfile:- # Pull base image FROM python:3.11.1 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Here's my docker-compose.yml file:- version: '3.11.1' services: web: build: . tty: true command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - DB DB: image: postgres:11 Here's my settings.py file:- from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for … -
Django CBV: How to subclass scattered parts of code from the parent class
I'm trying to jump from the world of FBV to CBV, but running into an immediate problem...which i'm sure must be pretty common and solvable and I just don't know how... I'm inheriting the general View class into my parent class, which has all the code from my FBV. I created a sub-class which inherits from the parent, and the page still loads fine. Good initial start! But now, I want to utilize the inheritance feature of CBV. I want to move (or override) multiple unique pieces in the parent to the child. I just want to leave the "common" code in the parent, and then all unique things to the child (and eventually other child classes). For example...I have about 1,000 lines of code in parent. And I will need to move / override probably 1/3 of it into child classes. But that 1/3 is scattered from the beginning to the end of the parent. It's not like the parent will be the complete first 1/2 of the code, and then the child classes will be last 1/2. Which presents 2 problems... A) For example, when I want to override a particular section of code in the child, some … -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed - Django
First, I know there are a lot of answers regarding this error, but I can't understand why this is erroring out in my case. I am learning Django and any help would be highly appreciated. I have a Ticket model with ForeignKey reference to Category, Type & GHDUser as below models.py ` # from accounts/models.py class GHDUser(AbstractBaseUser, PermissionsMixin): emp_id = models.IntegerField(primary_key=True) email = models.EmailField(_('email address'),unique=True) username = models.CharField(max_length=150, unique=True) # from ticket/models.py class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Type(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Meta: verbose_name = 'Type' verbose_name_plural = 'Types' def __str__(self): return self.name class Ticket(models.Model): status_options = ( ('open', 'Open'), ('pending', 'Pending'), ('closed', 'Closed') ) priority_options = ( ('high','High'), ('medium','Medium'), ('low','Low') ) ticket_no = models.CharField(max_length=10, blank=True) title = models.CharField(max_length=100) description = models.TextField(max_length=1000) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) type = models.ForeignKey(Type, on_delete=models.PROTECT, default=1) file = models.FileField(upload_to=user_directory_path, blank=True, default='files/Default_Avatar.png') raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE, related_name='raised_ticket') ` Now, I am able to create an instance for Ticket model from Admin Panel, but when I try to do the same via shell / using data from front end, I am getting the below error. django.db.utils.IntegrityError: FOREIGN KEY constraint … -
Django annotate field value from external dictionary
Lets say I have a following dict: schools_dict = { '1': {'points': 10}, '2': {'points': 14}, '3': {'points': 5}, } And how can I put these values into my queryset using annotate? I would like to do smth like this, but its not working schools = SchoolsExam.objects.all() queryset = schools.annotate( total_point = schools_dict[F('school__school_id')]['points'] ) Models: class SchoolsExam(Model): school = ForeignKey('School', on_delete=models.CASCADE), class School(Model): school_id = CharField(), This code gives me an error KeyError: F(school__school_id) -
annotate is adding an extra object to my queryset
I'm using DRF. I've got the following code where I annotate a queryset of Company objects with an additional joined field. It seems annotate is adding an extra object to my queryset. views.py def get(self, request, **kwargs): user = request.user companies = Company.objects.all() print(companies) user_in_queue = When(queue__users=user, then = True) companies = Company.objects.annotate(joined=Case( user_in_queue, default = False )) print(companies) the first print gives me <QuerySet [<Company: kfc>, <Company: kfc>]> With a json of [ { "name": "kfc", "id": 1, }, { "name": "kfc", "id": 2, } ] The second gives me <QuerySet [<Company: kfc>, <Company: kfc>, <Company: kfc>]> With a json of [ { "name": "kfc", "id": 1, "joined": null }, { "name": "kfc", "id": 1, "joined": true }, { "name": "kfc", "id": 2, "joined": null } ] I want a json of [ { "name": "kfc", "id": 1, "joined": true }, { "name": "kfc", "id": 2, "joined": null } ] -
How can i remove any allauth page?
I want to remove signup, reset password, and change password page from allauth django app. what should i do? because I need only login page. enter image description here enter image description here -
Django - How to manipulate Form data before it gets saved to model?
here is my views.py ` def CreateCourseView(request): TeeFormSet = inlineformset_factory(Golf_Course, Golf_Tee, form=AddTeeForm, extra=1,) if request.method == "POST": course_form = AddCourseForm(request.POST) teeformset = TeeFormSet(request.POST, instance=course_form.instance) if course_form.is_valid(): course_form.save() if teeformset.is_valid(): teeformset.save() return redirect("/") else: course_form = AddCourseForm() teeformset = TeeFormSet() return render(request, "Courses/add_course_form.html", {'teeformset': teeformset,'course_form': course_form,}) ` here is a shortened view of my models.py ` class Golf_Tee(models.Model): # choice list of index values INDEX = [ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), ] # choice list of par values PAR = [ (3, 3), (4, 4), (5, 5), ] course = models.ForeignKey(Golf_Course, on_delete=models.CASCADE) tee_name = models.CharField(max_length=255, unique=True) course_par = models.IntegerField() slope = models.DecimalField(decimal_places=2, max_digits=5) rating = models.DecimalField(decimal_places=2, max_digits=5) yardage = models.IntegerField() hole_1_par = models.IntegerField(choices=PAR, default = PAR[1][1]) hole_1_yardage = models.IntegerField(default = 0) hole_1_index = models.IntegerField(choices=INDEX, default = INDEX[0][0]) hole_2_par = models.IntegerField(choices=PAR, default = PAR[1][1]) hole_2_yardage = models.IntegerField(default = 0) hole_2_index = models.IntegerField(choices=INDEX, default = INDEX[0][0]) ` I'm trying to not have users enter in the total yardage, when they are already entering yardage for each hole. What I would like … -
Cannot configure pytest in my simple project
i have the folowing project structure, but when trying to run pytest in console i get error. Is the problem in pytest.ini? ERROR backend/tests/test_user.py - django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call backend |-foodgram |-foodgram |-manage.py |-api |-users |-tests |-pytest.ini in my pytest.ini [pytest] python_paths = foodgram/ DJANGO_SETTINGS_MODULE = foodgram.settings norecursedirs = env/* addopts = -vv -p no:cacheprovider testpaths = tests/ python_files = test_*.py -
Url with <int:pk> or <slug:slug> DJANGO
Stumped with this one, I need to be able to call an article via a pk or slug, for example user can do https://www.website.com/1 or https://www.website.com/article-slug both show the same article/page. And if neither 1 or slug exist show default article or nothing found. path('/', views.index, name='index’), path('slug:slug/', views.index, name='index’) Not sure how to proceed. -
Why am I getting "This field may not be null" errors when populating decimal and char fields from serialized data via Serializer in Django Model?
I am trying to populate DecimalField and CharField fields in a Django Model from serialized data via DRF Serializer, but I am getting strange errors of This field may not be null. Here is my model definition: class Product(BaseModel): product = models.CharField(max_length=255) recommended_action = models.CharField(max_length=255) recommended_action_value = models.DecimalField(max_digits=12, decimal_places=8) recommended_price = models.DecimalField(max_digits=12, decimal_places=8) rrp = models.DecimalField(max_digits=12, decimal_places=8) iam_price = models.DecimalField(max_digits=12, decimal_places=8) iam_index = models.DecimalField(max_digits=12, decimal_places=8) factor = models.DecimalField(max_digits=12, decimal_places=8) avg_in_stock = models.DecimalField( null=True, blank=True, max_digits=12, decimal_places=8 ) Here is my model serializer definition: class ProductSerializer(serializers.ModelSerializer): class Meta: model = models.Product fields = "__all__" And here is my view: @api_view(['POST']) def migrate_data(request, *args, **kwargs): if request.method == "POST": data = json.loads(request.body) product_serialized_data = serializers.ProductSerializer( data=data, many=True, context={"request": request}, ) if not product_serialized_data.is_valid(): print(product_serialized_data.errors) product_serialized_data.save() return Response(data={"detail": "Success"}) This is the data that I am passing to the POST request: { "product": "DE_Ford_2095160", "recommended_action": "increase", "recommended_action_value": 0.0315553, "recommended_price": 14.5862, "rrp": 14.14, "iam_price": 6.56898, "iam_index": 0.464567, "factor": 2.15254, "avg_in_stock": 1 } When I run this code, I get the following errors: [{'recommended_action': [ErrorDetail(string='This field may not be null.', code='null')], 'recommended_action_value': [ErrorDetail(string='This field may not be null.', code='null')], 'recommended_price': [ErrorDetail(string='This field may not be null.', code='null')], 'rrp': [ErrorDetail(string='This field may not be null.', code='null')], … -
sqlite3.OperationalError: foreign key mismatch during the creation of test DB
During the creation of the test database, I got an error sqlite3.OperationalError: foreign key mismatch - "history_message" referencing "history_device". This error is caused by the 1st migration file: import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Device', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('description', models.TextField(blank=True, null=True)), ('username', models.CharField(max_length=100)), ('client_id', models.CharField(max_length=100)), ], options={ 'verbose_name': 'Device', 'verbose_name_plural': 'Devices', }, ), migrations.CreateModel( name='Message', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField()), ('message', models.TextField()), ('client_id', models.CharField(max_length=100)), ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='history.device')), ], options={ 'verbose_name': 'Message', 'verbose_name_plural': 'Messages', }, ), ] I don't understand because I don't have any issues with the "prod db" but only with the "test db". -
Django - 'This field is required on form' load
I have a Django view that shows two create forms. Whenever the page loads all of the input fields display - 'This field is required". enter image description here Template code {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ listing_create_form.as_p }} {{ listing_media_form.as_p }} <button type="submit">Submit Form</button> </form> {% endblock %} views.py @login_required def createListing(request): listing_create_form = ListingCreateForm(request.POST or None, request.FILES) listing_media_form = ListingMediaForm(request.POST or None, request.FILES) if request.method == 'POST': if listing_create_form.is_valid() and listing_media_form.is_valid(): listing_create_form.instance.created_by = request.user form = listing_create_form.save() form.save() new_listing_id = form.pk # loop over images to upload multiple for image_uploaded in request.FILES.getlist('image'): image_instance = ListingMedia.objects.create(listing=form, image=image_uploaded) image_instance.save() return redirect('boat_listings') context = {'listing_create_form': listing_create_form, 'listing_media_form': listing_media_form} return render(request, 'listings/listing_create_form.html', context) forms.py class ListingCreateForm(forms.ModelForm): class Meta: model = Listings widgets = { "featured_image": forms.FileInput( attrs={ "enctype": "multipart/form-data" } ), } fields = "__all__" exclude = ("created_by", "created_on", "last_modified",) class ListingMediaForm(forms.ModelForm): class Meta: # image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) widgets = { "image": forms.ClearableFileInput( attrs={ "multiple": True } ), } model = ListingMedia fields = ['image'] Django template should render without field required message before user has inputted invalid inputs. -
How do I access the request object in a form_class, django, CBV
I am trying to pass the data from the request to my form. Currently, that is resulting in an error: 'NoneType' object has no attribute 'user' My view: class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task template_name = "tasks/task_form.html" form_class = DateInputForm My view (get_form_kwargs function): def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs() form_kwargs['request'] = self.request return form_kwargs Init from my form : def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) request = kwargs.pop('request', None) self.fields['tags'].queryset = Tag.objects.filter(user=request.user.id) -
Passing a variable to include in extends in Django templates
I have the following structure of templates: main.html <html> <body> <p> This works: {% block title %}{% endblock %} </p> {% include 'heading.html' with title=title %} {# but this does not work since it is not a variable #} </body> </html> heading.html <p> {{ title }} </p> page.html {% extends 'main.html' %} {% block title %}test title{% endblock %} How can I pass the title from page.html to heading.html? Ideally, it should be defined as a block like now, but alternatives are also welcome. I'd like to contain the solution within the templates if possible. -
In Django, how do I remove a permission from my site?
I added a permission to a model using the way recommended in the Django docs. E.g. class Car(Model): class Meta: permissions = ( ('can_drive', 'User is allowed to drive this car'), ) I then decided I don't want that permission so I removed the class Meta... code and ran: ./manage.py makemigrations ./manage.py migrate ./manage.py told me it removed the class Meta... code but the permission is still in Django admin. -
Need Help Regarding This Query in django model
class Post(models.Model): post_uuid = models.UUIDField(default=uuid.uuid4, editable=False) user = models.ForeignKey( User, related_name='post_model', on_delete=models.CASCADE) post_categories = models.ManyToManyField( 'Categories', through='PostCategories', blank=True) created_on = models.DateTimeField(default=timezone.now) updated_by = models.DateTimeField(null=True, blank=True) updated_on = models.DateTimeField(null=True, blank=True) deleted_by = models.DateTimeField(null=True, blank=True) deleted_on = models.DateTimeField(null=True, blank=True) class Meta: ordering = ["-created_on"] indexes = [ models.Index(fields=['post_uuid',]), models.Index(fields=['created_on',]), ] def __str__(self): return '{}'.format(self.id) class PostInLanguages(models.Model): post_in_language_uuid = models.UUIDField( default=uuid.uuid4, editable=False) post = models.ForeignKey( Post, related_name='post_language', null=False, on_delete=models.CASCADE) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_language = models.BooleanField(default=True) parent_post_language_id = models.PositiveIntegerField(null=True) description = models.CharField(max_length=400, null=True, blank=True) like = models.ManyToManyField( 'User', through='PostLanguageLike', related_name='post_like', blank=True) hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.post.id) class Meta: indexes = [ models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']), ] recouch_obj = PostInLanguages.objects.annotate(Count('parent_post_language_id')).filter(parent_post_language_id__count__gte=minimum_recouch,is_post_language=False).values_list("parent_post_language_id") Can anyone help to figure out what will this query return I just need postinlanguage object query set with minimum recouch filter Is_lang_post = True means this is a post If false means this is post of another post that means recouch -
404 error on new pages with wordpress blog ( on mysql) with django (postgres) using nginx on the same server
Condition : I have set up my server as follows : my wordpress blog ( on mysql) with django (postgres) using nginx on the same server. Error I am getting 404 error for new pages I create on the blog. ( it works when permalink settings is like this : https://www.example.com/blog/?p=1 It does not work when permalink setting contains post name New pages I create also behave in similar fashion - do not work with name slug My analysis is that it has something to do with ssl conf or nginx conf. Basically routing issue. I am a newbie. Here is the Nginx Conf: upstream app_server { server unix:/home/user/opt/env/run/gunicorn.sock fail_timeout=0; } #wordpress php handler upstream wordpress-prod-php-handler { server unix:/var/run/php/php7.0-fpm.sock; # serve wordpress from subdirectory location /blog { alias /home/user/opt/blog; index index.php; try_files $uri $uri/ /blog/index.php?$args; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_pass wordpress-prod-php-handler; } } Please help.. As specified, I was trying to get my blog and app on the same domain. www.example.com -> opens django app www.example.com/blog -> opens wordpress blog Now it works fine, but if anything comes after /blog -- such as example.com/blog/test will result in a 404 error. Nginx error log shows this …