Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse django custom admin site URL
I'm trying to get reverse for my custom admin which is using proxy model, but I cann't find out how to reverse to sub page. In my panel admin, model Advertisement has few pages and I want to reverse to one of them. I've already tried: reverse("admin:app_list", args['advertisement', 'deactivatedadvertisements']) class DeactivatedAdvertisements(Advertisement): class Meta: proxy = True class DeactivatedAdvertisementsAdmin(admin.ModelAdmin): """Panel for listing deactivated advertisements allowing to activate them.""" ordering = ["-deactivated_at"] list_display = [ "advertisement_title", "user", "root_category", "activate", "deactivated_at", ] I want to get url admin/advertisement/deactivatedadvertisement/ How can I reach it? -
Do i need to implement JWT in Django?
I am not very fimiliar with authentication but I know that JWT is the best practice and market standard but do I really need to implement JWT in Django can I not use Django built-in cookie-based authentication if not then and what are the advantages of using JWT over Django cookie-based authentication. -
How to make only the owner of a Product able to edit or delete it
I am developing a supplier management system. I have different admins and different suppliers, i will like that only the particular supplier that added the product is able to edit or delete it, so that even other suppliers are not able to edit or delete it. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() views.py @login_required @supplier_required def Editproduct(request, pk): title = "Edit Product" product = Product.objects.get(id=pk) form = AddProductForm(instance=product) if request.method == 'POST': form = AddProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, "Product Edited Successfully") return redirect('product') context = {"form":form, "title":title} return render(request, "core/editproduct.html", context) @login_required @supplier_required def DeleteProduct(request, pk): title = "Delete Product" product = Product.objects.get(id=pk) try: product.delete() messages.success(request, "Product Deleted Successfully.") return redirect('product') except: messages.error(request, "Failed to Delete Product.") return redirect('product') -
If user log in again, how to redirect the user to the last page he visited in his last session in django?
I am developing a website using django, and I want to redirect a user to the last page he was at during his last session before log out when he log in again. How can I do this? -
How to get the Total Sum for different fields of an object with annotate in Django?
I've got three models like this: class Corredor (models.Model): dorsal=models.IntegerField(primary_key=True) tipo=models.CharField(max_length=50) nombre=models.CharField(max_length=50) f_nacimiento=models.DateField(default=1/1/1975) nacimiento=models.IntegerField() categoria=models.CharField(max_length=50) pais=models.CharField(max_length=50) equipo=models.CharField(max_length=50) nombre_equipo=models.CharField(max_length=50) lid=models.BooleanField() gre=models.BooleanField() jor=models.BooleanField() giro=models.BooleanField() tour=models.BooleanField() vuelta=models.BooleanField() abandono_giro=models.IntegerField(default=0) etapa_aban_giro=models.IntegerField(default=0) abandono_tour=models.IntegerField(default=0) etapa_aban_tour=models.IntegerField(default=0) abandono_vuelta=models.IntegerField(default=0) etapa_aban_vuelta=models.IntegerField(default=0) class Meta: ordering=['nombre'] def __str__(self): return self.nombre class Equipo (models.Model): alias=models.CharField(max_length=50, primary_key=True) lid1=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid1", on_delete=models.CASCADE) lid2=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid2", on_delete=models.CASCADE) lid3=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid3", on_delete=models.CASCADE) lid4=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid4", on_delete=models.CASCADE) gre1=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre1", on_delete=models.CASCADE) gre2=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre2", on_delete=models.CASCADE) gre3=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre3", on_delete=models.CASCADE) jlg1=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg1", on_delete=models.CASCADE) jlg2=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg2", on_delete=models.CASCADE) lid_sup=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid_sup", on_delete=models.CASCADE) gre_sup=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre_sup", on_delete=models.CASCADE) jlg_sup=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg_sup", on_delete=models.CASCADE) ganador_e1=models.ForeignKey(Corredor,limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e1", on_delete=models.CASCADE) ganador_e2=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e2", on_delete=models.CASCADE) ganador_e3=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e3", on_delete=models.CASCADE) ganador_e4=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e4", on_delete=models.CASCADE) ganador_e5=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e5", on_delete=models.CASCADE) ganador_e6=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e6", on_delete=models.CASCADE) ganador_e7=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e7", on_delete=models.CASCADE) ganador_e8=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e8", on_delete=models.CASCADE) ganador_e9=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e9", on_delete=models.CASCADE) ganador_e10=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e10", on_delete=models.CASCADE) ganador_e11=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e11", on_delete=models.CASCADE) ganador_e12=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e12", on_delete=models.CASCADE) ganador_e13=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e13", on_delete=models.CASCADE) ganador_e14=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e14", on_delete=models.CASCADE) ganador_e15=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': … -
Django IntegrityError (null value in column violates not-null constraint) allows model object to be saved but then deletes object?
When troubleshooting the error django.db.utils.IntegrityError: null value in column "experience" violates not-null constraint DETAIL: Failing row contains (7, f, null, 1, 1, null, 5)., I added a save function to my model to print out the experience value so that I could see if it was really null or not. The experience value being saved is not null. When I ran my code after adding this save function, the object seemed to be created successfully without error when I click 'save' in helm. But, when I go to view my Scheduler objects, nothing appears there. Additionally, I get the message at the top of helm that my object was created successfully along with a message that the schedule event with ID "None" does not exist. I am really confused on why this is happening. My guess is that the save method I added is making it so that Django is not checking to see if errors exist which causes the object to appear created when it is not. I am fairly certain that the IntegrityError still exists and that this is related to why the object is deleted immediately after creation. I would appreciate any help someone can provide. Django … -
django media images wont display
I have deployed a Django project on a server. The project has a blog app in which you can add posts from the admin page. Each post has some paragraphs, a title, and an image. The posts get created perfectly, but sometimes when I revisit the site, the pictures I uploaded don't display. I have found out that if I clear the browser's cache by pressing ctrl+f5, the images will get displayed. But this is not ok, and I cant tell every user to clear their browser cache, obviously. here is a sample of this problem: and everything goes back to normal after cache clearing. this is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and I have added this line in my main urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to style form's dropdown options and add picture, instead of a generic list using Django
I want to have a user's profile pic and the value in the database when trying to submit a form. Currently the form just has a drop down that lists all the objects' ids in the DB, example: Object (1) Object (2) Object (3) Object (4) Object (5) I want the drop down to have: Username, profile pic (their actual image from static files), Object 1's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 2's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 3's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 4's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 5's string (whats actually in the DB) Here is some code, i'm open to any python solution (crispy/widget/etc.) My form.py from django.contrib.auth import get_user_model from .models import Observation, Data, Hypothesis, Experiment, Comment User = get_user_model() class SubmitObservation(ModelForm): description = forms.CharField(widget=forms.Textarea, label='Submit an Observation') class Meta: model = Observation fields = ('description',) exclude = ('user', 'status', 'activate_date', 'deactivate_date') #observation = forms.CharField(label='Observation', max_length=250) class SubmitData(ModelForm): data_description = forms.CharField(widget=forms.Textarea, label='Data') … -
csrf token missing axios to django rest framework
i was trying to make post request and face with error code 403,csrf token was missing.. tried many methods but didnt work at last disabled csrf token on settings.py and worked , so found the problem was in csrf token class Axios extends React.Component{ constructor(){ super() this.state = { persons: [] } } post(){ axios.post('http://127.0.0.1:8000/api/create', { title: 'titan', body: 'this is working', }) .then(function (response) { console.log(response); }) } get(){ axios.get('http://127.0.0.1:8000/api').then(Response=>{ console.log(Response.data) }) } componentDidMount(){ this.post(); this.get(); } render(){ return( <div> <h1>fetch</h1> </div> ) } } export default Axios; this is my code pls tell me a way to put csrf token in this as well as import statement... currently using axios -
Get User Specific Answer attribute from primary model instance - django
I have a Question model and then an Answer Model. Answer model saves answers specific to the logged-in user. I have successfully saved the answer of the login user and verified it in the admin. However, I am unable to get the answer, specifically for the logged-in user. Can you please point me in the right direction? I have already tried https://docs.djangoproject.com/en/3.1/ref/models/relations/ My Model: class Question(models.Model): question = models.CharField(max_length=200, null=True, blank=True) edit_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) answer = models.TextField(max_length=600, null=True, blank=True, default=" ") edit_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.answer My View def InterviewQuestion(request): questions = Question.objects.all() context = {'questions':questions} return render(request, 'jobs/ace-interview.html', context) My Template {% for question in questions %} <div class="card"> <div class="card-body"> <h5 class="card-title">{{question.question}}</h5> <p class="card-text">{{question.answer_set.answer}}</p> </div> </div> {% endfor %} I want Answer here specific to the user -
Django Admin Panel can't access specific items
I've got a model of an article and everything works fine except when I change their status to draft - it disappears from Admin Django Panel. New articles are successfully added, but then don't show, admin panel just can't access them. When I change the URL to force the admin panel to show me the details so I could edit it, I get a message that the article with given ID doesn't exist. So basically every draft article gets lost. But I know they have to exist in my database, because they show up on my article list view, but I can't go to detail view or draft view as I always get "No NewsModel matches the given query" Django 2.0.5 models.py class NewsModel(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.CharField(max_length=250) slug = AutoSlugField(populate_from='title') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES) image = models.ImageField(upload_to="news/") description = models.TextField(null=True, blank=True) def get_absolute_url(self): from django.urls import reverse return reverse('main:news_details', kwargs={'slug':self.slug}) def __str__(self): return self.title class Meta: ordering = ('-publish',) verbose_name = 'News' verbose_name_plural = 'News' admin.py @admin.register(NewsModel) class NewsAdmin(admin.ModelAdmin): list_display = ('title', 'game', 'news_type', 'author', 'finish', 'publish') views.py def news_details(request, slug): … -
Problems with django-microsoft-auth
A customer told me that he needs to make a system, in Django, that authenticates users against Azure Active Directory. I'm trying to use django-microsoft-auth (https://django-microsoft-auth.readthedocs.io/en/latest/usage.html) but I have several problems. When I'm going to execute the test site, I have the following error: ModuleNotFoundError: No module named 'tests.site' so I don't see how this test site works. I'm executing in Windows 10, 64 bits. I already do the conection to Azure Active Directoy but I don't know can I see the user that it's connected, make a login and a logout link, manage the user permits. I think that the quick start guide it's very poor for Django beginners deverlopers, like me, because not especify all of this items. I will ver glad if somebody can help me. I have spent many hours trying to solve these problems. Thanks. -
Django migration throws relation does not exist before migration makes the table
I'm trying to start from a clean database and run all the migrations, but I have a for that's used in a view that has options that it pulls from the database. When I try to run the migration, it throws an error. Commenting out the code fixes it, but this doesn't seem like a good solution for deploying to new environments. I've seen other questions where the answer is to just comment out your urls.py, but I was wondering if anyone found a clean solution for this? -
I am not able to add item to database
I have a product model, which i have the modelforms to make a form for and then implemented in my views and templates. After submitting the form, the product is not being added to the database and I don't know what the error seems to be. I made sure to use the enctype="multipart/form-data" because of the image field in the form and also request.FILES. N.B:I am getting Error Adding Product which is the else statement if the form is not valid, but i don't know how the form is not valid. models.py class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() image = models.ImageField(upload_to='images/products', default='images/products/default-product.jpeg', blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True) country = CountryField(blank_label='(select country)') def __str__(self): return self.name forms.py class AddProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' exclude = ['user'] views.py @login_required @supplier_required def Addproduct(request): title = "Add New Product" form = AddProductForm() if request.method == 'POST': form = AddProductForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, "Product Added Successfully") return redirect('product') else: messages.error(request, "Error Adding Product") context = {"form":form, "title":title} return render(request, "core/addproduct.html", context) addproduct.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} … -
MultipleChoiceFilter to Checkboxes
I have a ModelMultipleChoiceFilter working, however I cant find a way to adjust it from a input multiple choice to a checkbox list. This is what I currently have: This is what I want to convert it to: My current code: class GameFilter(django_filters.FilterSet): gamemodes = django_filters.ModelMultipleChoiceFilter( queryset=GameMode.objects.all(), label='Game modes (or)', ) -
how to create urls/path in django restframework?
My project structure is like this: project |----app1 |--app1.1 |--app1.2 |--app1.3 so my question is how to add url/path? -
Django Many to Many Fields Not Saving Rest Framwork
Hi guys I'm trying to save many to many data from rest Post method when I post it give me blank none items added to many to many fields. Please check and help me how I can fix this issue Views.py @api_view(['POST', 'GET']) def AddDisco(request, *args, **kwargs): if request.method == 'POST': data=request.data serializer = serializers.DiscoSerializer(data=data) if serializer.is_valid(): print('it is valid') serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) if request.method == 'GET': qs = Disco.objects.all() serailzer = serializers.DiscoSerializer(qs, many=True) return Response(serailzer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK) Models.py class MusicGenre(models.Model): title = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=100) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Disco(models.Model): title = models.CharField(max_length=100) genre = models.ManyToManyField(MusicGenre, blank=True) Serializer.py class DiscoSerializer(serializers.ModelSerializer): class Meta: model = models.Disco fields = '__all__' depth = 1 when I try to post from api it wont add the items in genre it gives me blank Please help me to solve this issue -
How to get data correctly from a django model to Django REST framework
I'm working with Python 3.9 and Django 3.1.6. I have a quite long model in models.py. Short version is something like this: class Check (models.Model): @property def total_body_fat_percentage(self): if self.client_gender == "M": total_body_fat_percentage = (self.Yuhasz * 0.097) + 3.64 pass else: total_body_fat_percentage = total_body_fat_percentage = float((self.Yuhasz * 0.1429) + 4.56) return total_body_fat_percentage @property def muscle_weight_percentage(self): muscle_weight_percentage =self.muscle_weight*100/self.weight return muscle_weight_percentage These fields return a float number. Something like 14.407. Of course there are other fields in there such as Yuhasz, client_gender, etc. I need these values into JSON. I tried to use the following serializer on serializer.py: class PercentagesSerializer(ModelSerializer): class Meta: model = Check fields = ('total_body_fat_percentage', 'muscle_weight_percentage') And I have the following class on views.py: class PercentagesAPI(APIView): authentication_classes = [] permission_classes = [] serializer = PercentagesSerializer def get(self, request, format=None): lista = Check.objects.all() print(lista) response = self.serializer(lista) print(response) json_response= json.dumps(response.data) print(json_response) data = { 'percentages': json_response } return Response(response.data) But it returns no data. Shell console states that it gets the queryset, it gets the fields, but it doesn't seems to get the values: <QuerySet [<Check: Check object (1)>]> PercentagesSerializer(<QuerySet [<Check: Check object (1)>]>): total_body_fat_percentage = ReadOnlyField() muscle_weight_percentage = ReadOnlyField() {} Thank you in advance for your advices and help! -
Facing HTTPError 404
I am using Django as frontend and Firebase as backend. I am trying to render a html page after a post request. As I tried to run the program I am getting HTTPError 404 Here is my view.pyViews.p After I run the http://127.0.0.1:8000/post_create/ on Chrome I get the following error Error I am trying to solve this problem from 3-4 days but unable to get solution. I am not getting why this error is occuring. Your help would be appreciated Thank you. -
Display Multiple Chart.js Charts in Django Template Using Loop
I want to filter multiple charts using for loop in django template. The data displays correctly, and I can get it to display the first chart only. Guys, i am having trouble using for loop in django template i do not know how to use for loop to display multiple charts in django template i am unable to find solution of displaying multiple charts and django kindly help me please. Template {% for data in data_list %} <div class="box col-lg-3 pull-up"> <div class="box-footer p-0 no-border"> <div class="chart"> <canvas id="chartjs" class="h-80"></canvas> </div> </div> </div> {% endfor %} <script> $(function () { 'use strict'; //----chart var dasChartjs = document.getElementById("chartjs").getContext("2d"); var blue_trans_gradient = dasChartjs.createLinearGradient(0, 0, 0, 100); blue_trans_gradient.addColorStop(0, 'rgba(247, 147, 26,1)'); blue_trans_gradient.addColorStop(1, 'rgba(255,255,255,0)'); var DASStats = { responsive: true, maintainAspectRatio: false, datasetStrokeWidth : 3, pointDotStrokeWidth : 4, tooltipFillColor: "rgba(247, 147, 26,0.8)", legend: { display: false, }, hover: { mode: 'label' }, scales: { xAxes: [{ display: false, }], yAxes: [{ display: false, ticks: { min: 0, max: 85 }, }] }, title: { display: false, fontColor: "#FFF", fullWidth: false, fontSize: 30, text: '52%' } }; // Chart Data var DASMonthData = { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"], datasets: [{ label: … -
ValueError: Field 'id' expected a number but got 'example@example.com'
I'm trying to create a superuser but it's giving the above error. And I can't exactly find at which line I'm getting the error. views.py from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from .models import * from django.http import HttpResponseRedirect from django.urls import reverse from .form import * from django.db import IntegrityError # Create your views here. def index(request): if not myUser.is_authenticated: message = "signed in as {Customer.first_name}" else : message = "please sign in" return render(request, "auctions/index.html",{ "listings": Listings.objects.all(), "message":message }) def login_view(request): if request.method == "POST": form = loginForm() email = request.POST["email"] password = request.POST["password"] user = authenticate(request,username=email,password=password) if user is not None: login(request,email,password) return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html",{ "form": form , "message": "username/password not valid" }) return render(request, "auctions/login.html",{ "form": loginForm() }) def logout_view(request): logout(request) return render(request, "auctions/login.html") def register(request): if request.POST == "POST": form = registerForm() email = request.POST["email"] # check passwords are same password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render (request, "auctions/register.html",{ "form": form, "message": "Passwords does not match" }) # Attempt to create new user try: user = myUser.objects.create_user(email,password) user.save() except IntegrityError: return render(request, "auctions/register.html", { "form":form, "message": "Username is already taken" }) login(request,user) return HttpResponseRedirect(reverse('index')) return … -
Django deployment on web host
For past three days/nights i have been trying to deploy a django app on bluehost hosting, the trouble is bluehost do not provide builtin python application installer like others rather we have to register application once deployed, i would really appreciate if anyone could point me to right direction. So far I have installed python 3.6 and pip Installed django uploaded django project files to server i run python manage.py runserver It runs on local host fine I have multiple domains on my hosting plan but I don’t understand how to deploy django to one of my domains.. PS I am absolute beginner to django framework so any help Is appreciated Thanks -
Docker-compose is not reading env variable COMPOSE_FILE
I am using django cookiecutter configuration with Docker and I can not make docker-compose read $COMPOSE_FILE env variable. I did this export COMPOSE_FILE=local.yml And this is the outcome when a I run either docker-compose up or build: Can't find a suitable configuration file in this directory or any parent. Are you in the right directory? Supported filenames: docker-compose.yml, docker-compose.yaml -
Welcome to CentOS - Django, Nginx & uwsgi
Installed and configured nginx/uwsgi for django application. Both services are running fine no errors. But facing Welcome to CentOS when loading application in browser. nginx.conf --- content server { listen 80; server_name ##.com www.###.com; # location = favicon.ico { access_log off; log_not_found off; } location /media/ { alias /home/crmuser/crmsourcedirect/media/; } location /static/ { alias /home/crmuser/crmsourcedirect/static/; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass unix:/run/uwsgi/crmsourcedirect.sock; # uwsgi_pass 127.0.0.1:8000; } } crmsourcedirect.ini -- content [uwsgi] project = crmsourcedirect username = crmuser base = /home/%(username) logto = /var/log/uwsgi/uwsgi.log chdir = %(base)/%(project) home = %(base)/venv module = cmo.wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true ''' -
django rest nested serializer object setting nested object in post method
hi guys i hope you be healthy :) okay i have an image model and a category model which have a foreignkey to image model like below: image model: class Image(models.Model): image = models.ImageField(upload_to="%Y/%m/%d") alt = models.CharField(max_length=25) name = models.CharField(max_length=25, unique=True) def __str__(self): return self.name category model: class Category(models.Model): image = models.ForeignKey(Image, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=25, unique=True) slug = models.SlugField(max_length=25, unique=True) okay now i want to when i call a category get somting like this: { "image":{ "image":"https://example.com/media/image.png", "name":"image name", "alt":"image alternative" }, "name":"category name", "slug":"category slug" } i write my serializer and views like below and getting a god json object like above image serializer: class ImageSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) image = serializers.ImageField() alt = serializers.CharField(max_length=25) name = serializers.CharField(max_length=25, validators=[UniqueValidator(queryset=Image.objects.all(), message="there is another image with same name.")]) category serializer: class CategorySerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) image = ImageSerializer() name = serializers.CharField(max_length=25,validators=[UniqueValidator(queryset=Category.objects.all()),]) slug = serializers.SlugField(max_length=25,validators=[UniqueValidator(queryset=Category.objects.all(),]) def validate_image(self, value): return get_object_or_404(Image, name=value['name']) def create(self, validated_data): return Category.objects.create(**validated_data) def update(self, instance, validated_data): instance.image = validated_data.get('image', instance.image) instance.name = validated_data.get("name", instance.name) instance.slug = validated_data.get("slug", instane.slug) instance.save() return instance and here is category view: class CategoriesView(APIView, PaginationMixin): pagination_class = PageNumberPagination() permission_classes = (AllowAny,) def get(self, request): cats = Category.objects.all() serializer = CategorySerializer(cats, many=True, context={"request":request}) …