Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL to Template View Preventing Media Folder from Displaying
I have been working on a Django DRF/Vue project and ran into issues with being able to download or view files from the media folder. I have this set up as a media root and directory in the settings and included the following in my url.py file: if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root = settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) The issue is happening from my path to the template views. re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point") If I comment this line out, the media directory works as I want but this causes my application to no longer direct users to my frontend and Django template files. I am fairly new to Django and am not sure exactly how to resolve this, or if it is possible to create a condition within the path to exclude /media from being triggered? I would appreciate any advice you can give. Cheers! -
TypeError: main() missing required positional argument request, while I have the argument request in the main function
I am new to Stack Overflow and I am learning Django from youtube. I am following tech with Tim's tutorial for Django and React JS. So in the first tutorial, I got an error while performing the migrations for manage.py where it gave me an error that there is am argument missing om the main function that returns the HttpResponse and that argument is request I have already included the request parameter in my main() function. If you guys wanna see the code just go to tech with Tim's channel and tutorial 1 for Django and react js that's all that I did. -
How do you get the "user_id" of the token payload into the JSON POST form?Django REST, simpleJWT, Vue3
So i have access and refresh tokens in my local storage. The decoded access token has "user_id" in the payload. I have a problem understanding how do you make a POST request to the REST API, where the JSON form includes the "user_id" of the currently logged in user. Do i get it from the stored JWT or is there another way? For a valid POST request i need 3 fields: { "post_author": "field, which needs the currently logged in user, aka user_id from the token " "post_body": "some text" "post_title": "some text" } Simplified question, how do you get the "user_id" of the decoded token into the JSON form? createPost.vue <template> <div id="authenticationDiv"> <div> <input type="text" v-model="postTitle" placeholder="post_title" /> <input type="text" v-model="postBody" placeholder="post_body" /> </div> <br /> <button @click="createPost">Submit Post</button> </div> </template> <script> import { getPosts } from "./importable_functions"; import { ref } from "vue" export default { setup() { const ACCESS_TOKEN = "access_token"; const postTitle = ref(""); const postBody = ref(""); async function createPost() { // var csrftoken = getCookie("csrftoken"); fetch("http://127.0.0.1:8000/api/create_post/", { method: "POST", headers: { "Content-type": "application/json", // "X-CSRFToken": csrftoken, Authorization: `Bearer ${window.localStorage.getItem(ACCESS_TOKEN)}`, }, body: JSON.stringify({ post_body: postBody.value, post_title: postTitle.value, // post_author: }), }).then((response) => { getPosts(); … -
Custom Permissions on a DRF Generic View
I have two models: class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models. Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service= models.ForeignKey(Service, on_delete=models.CASCADE) I have a view that returns the orders for a specific listing: class ServiceOrdersView(generics.ListAPIView): serializer_class = OrderSerializer def get_queryset(self): service = Service.objects.get(id=self.kwargs['service_id']) return Order.objects.filter(service=service) It works fine and the expected results are returned, but how do I make it so that only the owner of the listing can call the view and get the results? -
How to set the default url when i run server in Django
In Django, When I run server, default url always come out with http://127.0.0.1:8000/blog/ But i want justin http://127.0.0.1:8000 url for start. How can i change the default of url? In urls.py, there are no redirectview function. -
Resolution and customization of Django REST Framework permissions
I have a given url defined that's being managed by a single view. re_path(r'^something(?P<path>(/[^/]+)*)$', SomethingView.as_view(), name='something'), So, the view handles a matrix of ['POST','GET','PATCH','DELETE'] but it also has another matrix which is determined by the url path following the /something. examples: /something/color /something/shape so, the permission for POST /something/color can differ from POST /something/shape. I do have a custom permission set for the entire SomethingView but the has_permission is called before the view processes the full path of the URL and is completely in the dark if /color or /shape is part of the path, which defeats my purpose of having custom permissions for all combinations of METHOD + what's coming after /something My options: not using DJango REST permission classes and implementing permissions myself on the actual get/post/... methods Finding a way to customize Django REST permission classes to get real-time information from the actual pre-processing of the path + method used in the request. Any ideas on #2? -
Django REST framework .annotate(Count()) appears to return incorrect count
I have three models that look approximately like this: class Utterance(models.Model): id = models.SlugField(max_length=20, primary_key=True) class TransformationWav(models.Model): utt = models.ForeignKey(Utterance, on_delete=models.CASCADE, blank=True, null=True) parent_wav = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) trimmed = models.BooleanField(default=False) class TransformationMFBs(models.Model): utt = models.ForeignKey(Utterance, on_delete=models.CASCADE, blank=True, null=True) wav = models.ForeignKey('TransformationWav', on_delete=models.CASCADE) And I have a QuerySet generated with these filters that returns two Utterance objects with the same ID: >>> filters = {'transformationwav__trimmed': False, 'transformationwav__utt__id': "m00_00_040", 'transformationmfbs__wav__trimmed': False, 'transformationmfbs__utt__id': "m00_00_040"} >>> utterances = Utterance.objects.filter(**filters) >>> utterances <QuerySet [<Utterance: m00_00_040>, <Utterance: m00_00_040>]> I can successfully remove the duplicate utterance by using .distinct(), leaving only one utterance in the queryset: >>> utterances = utterances.distinct() >>> utterances <QuerySet [<Utterance: m00_00_040>]> >>> len(utterances) 1 >>> utterances.count() 1 However, when I then try to annotate the utterances with their counts by utterance ID, Count() finds two objects in the QuerySet: >>> utterances = utterances.annotate(count=Count('id')) >>> for utt in utterances: ... print(utt.id, utt.count) ... m00_00_040 2 So my question is, why does .annotate(Count()) find two objects here instead of one? Note: Though I can use .annotate(count=Count('id', distinct=True)) to get only one result, I feel like I shouldn't have to use distinct twice, because I already used it on the QuerySet. I have also … -
Trouble with ProxyPass of REMOTE_USER from nginx to Django
I have an nginx web server that's configured with client certificate authentication. Once authenticated, I proxy requests to a uWSGI Django application server. I've set-up my Django application to perform authentication using REMOTE_USER (https://docs.djangoproject.com/en/3.1/howto/auth-remote-user/), however it doesn't seem to be working as I receive the "'AnonymousUser' object is not iterable" error from Django. I'm assuming that I'm missing something in my nginx configuration: server { listen 80; server_name my.website.net; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/my.website.net/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my.website.net/privkey.pem; ssl_verify_client on; ssl_verify_depth 2; ssl_client_certificate /etc/nginx/ssl/cas.pem; proxy_set_header X-SSL-Client-Serial $ssl_client_serial; proxy_set_header X-SSL-Client-Verify $ssl_client_verify; proxy_set_header X-SSL-Client-S-DN $ssl_client_s_dn; proxy_set_header X-Remote-User $remote_user; proxy_set_header REMOTE_USER $remote_user; location / { root /var/www/my.website.net; index index.html index.htm; } location /django { proxy_set_header Host 10.101.10.228; proxy_http_version 1.1; proxy_set_header Connection "Keep-Alive"; proxy_set_header Proxy-Connection "Keep-Alive"; proxy_pass http://10.101.10.228:8000/webapp; proxy_redirect http://10.101.10.228/django/ https://my.website.net/django/; } } I've also tried utilizing the nginx uwsgi_* directives with no luck: upstream django { server 10.101.10.228:8000; } location /django { include uwsgi_params; uwsgi_pass django; uwsgi_param SCRIPT_NAME /webapp; uwsgi_param REMOTE_USER $remote_user; uwsgi_param X-REMOTE-USER $remote_user; } Is there something that appears to be missing? -
Automatically adding inline formsets in django create view
I'm creating a questionnaire site with django, whereby a user can select a questionnaire to answer. There are two models - questionnaire and response - for storing the completed questionnaires. There are another two models - template and questions - which store details such as the questions contained in each questionnaire. I've got everything to work. When a user selects the questionnaire they want to complete, a function based view runs that fetches the necessary info from the template and questions model, saves those into the questionnaire and response models before returning an update view where the user can then answer the questions. This is done via an inline formset. My question is whether this can be replicated without having to save the questionnaire and response models first. This is so that if a user decides not to complete the questionnaire, it won't have been needlessly saved. How would I go about automatically adding inline formsets in the create view. I haven't added any of my code here as I'm only looking for some high-level guidance so I can then research further. -
Testing Ajax on Django
I'm trying to write a test for an Ajax get a request in Django. Here's how I tried. from django.test import TestCase from django.urls import reverse from .models import ResourcePost, User from register.models import DonorProfile from django.utils import timezone class getResourcePostTests(TestCase): def setUp(self): ResourcePost.objects.create( title="test1", description="test", quantity=10, dropoff_time_1=timezone.now(), dropoff_time_2=timezone.now(), dropoff_time_3=timezone.now(), date_created=timezone.now(), donor=createdonor_1(), resource_category="FOOD", status="AVAILABLE", ) ... def test_getResourcePost(self): rescource_post_1 = ResourcePost.objects.get(title="test1") rescource_post_2 = ResourcePost.objects.get(title="test2") rescource_post_3 = ResourcePost.objects.get(title="test3") response = self.client.get(reverse('donation:getResourcePosts')) self.assertEqual(response.status_code, 200) Here is my view: @login_required def getResourcePost(request): user = request.user curr_user_rc_1 = user.helpseekerprofile.rc_1 curr_user_rc_2 = user.helpseekerprofile.rc_2 curr_user_rc_3 = user.helpseekerprofile.rc_3 posts = ResourcePost.objects.all() passingList = [] for post in posts: if post.date_created >= user.helpseekerprofile.message_timer_before and ( post.resource_category == curr_user_rc_1 or post.resource_category == curr_user_rc_2 or post.resource_category == curr_user_rc_3 ): notiPost = { "id": post.id, "title": post.title, "description": post.description, } passingList.append(notiPost) context = {"resource_posts": passingList} return JsonResponse(context) This is my ajax code: $(document).ready(function () { setInterval(() => { $.ajax({ type: 'GET', url: "{% url 'donation:getResourcePosts' %}", success: function (response) { $("#display").html('<i class="fas fa-bell"></i>') let postCounter = 0 for (i = 0; i < response.resource_posts.length; i++) { postCounter += 1 } if (postCounter > 0) { $("#display").append('<span class="message-number">' + postCounter + '</span>') } }, error: function (response) { console.log("No DATA FOUND") } … -
Deduced attributes of a LazyAttribute using Factory Boy
Using Factory Boy and Faker in a Django project, i would like to create deduced attributes, meaning a method from Faker returns a set of values that are dependent of each other. These values will be utilized for the other attributes of the Factory Class. Example: The location_on_land method from faker.providers.geo returns a tuple of latitude, longitude, place name, two-letter country code and timezone (e.g. ('38.70734', '-77.02303', 'Fort Washington', 'US', 'America/New_York'). All values depend on each other, since the coordinates define the place, country, timezone, etc. Therefor i cannot use separated functions for the (lazy) attributes like faker.providers.latitude, faker.providers.longitude for my attributes. Is it possible to somehow access the return values from the lazy attribute to use them for other deduced attributes? Is there a better way to access the return values from location_on_land to use them on the other depending attributes My Factory-Class looks like this: # factory_models.py class OriginFactory(factory.django.DjangoModelFactory): """Factory for Origin.""" class Meta: model = models.Origin exclude = [ "geo_data", ] # not working since not a lazy attribute # lat, lon, place, iso_3166_alpha_2, _ = fake.location_on_land() # desired outcome (not working) geo_data = factory.Faker("location_on_land") # attributes using the return values of `location_on_land` from lazy attribute (pseudo-code, … -
OnetoMany relationship models: limiting the number of instances of a model that have the same foreign key in django
I am working on a Django project where a user is able to create instances of a model Route and can create instances of a model Address. I have related those 2 models by adding the rout_name from the route model as a foreign key in the address model. I want to limit the number of instances that belong to a certain route_name strictly in the range up 50 addresses. This means that the user can only add 50 addresses that belong to a specific route_name. SO if the user successfully adds 50 and then wants to add another address to the same route name, I want the app to give them a message saying " Sorry, Cannot add more addresses to this route". Any idea where I can put this condition so that the addresses added can only be 50 or less than 50 that belong to the same foreign key(which is route_name in my case)? Here is the models.py for both of my models: class Route(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) number_of_locations = IntegerRangeField(min_value=2, max_value=50, default=None) def __str__(self): return self.title def get_absolute_url(self): return reverse('route-detail', kwargs={'pk': self.pk}) class Address(models.Model): route_name = models.ForeignKey(Route, on_delete=models.CASCADE) … -
How to setup Virtual Environment for Django development without internet?
Every time I create a Virtual Environment for Django, from inside the virtual environment, I need to run pip install django which requires internet access. Can I somehow install django globally on my machine and "pull" it from inside the Virtual Environment? I am running Zorion OS(Ubuntu-ish). -
Using Django on google colab
I am trying to start a new project on djago in google colab. In order to create a new one, I need to use cmd command line - $ django-admin startproject Project name. Is there another way to do it? Thank you -
Get max value from a set of rows
This question is in relation to project 2 of the cs50 course which can be found here I have looked at the following documentation: Django queryset API ref Django making queries Plus, I have also taken a look at the aggregate and annotate things. I've created the table in the template file, which is pretty straight forward I think. The missing column is what I'm trying to fill. Image below These are the models that I have created class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Listing(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() initial_bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) date_created = models.DateField(auto_now=True) def __str__(self): return self.title class Bid(models.Model): whoDidBid = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) list_item = models.ForeignKey(Listing, default=0, on_delete=models.CASCADE) bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) def __str__(self): return_string = '{0.whoDidBid} {0.list_item} {0.bid}' return return_string.format(self) This is the closest I could come to after a very long time. But the result I get is just the number 2. Ref image below Listing.objects.filter(title='Cabinet').aggregate(Max('bid')) Where 'Cabinet' is a Listing object that I have created. And placed two bids on them. So the question is, how do I get the Maximum bid … -
Unknown issue in Django machine learning app
I loaded a basic machine learning model using joblib in my django app and there is no error but predict method is showing same value even for different user inputs views.py def myapp(request): if(request.method =='POST'): mylis=[] test=joblib.load('/mltestapp/test.sav') mylis.append(request.POST.get('day')) obj= test.predict([mylis]) return render(request,'mltestapp/myapp.html',{'obj':obj[0][2]}) return render(request,'mltestapp/myapp.html') -
ValueError at /accounts/profile/edit/,,,,, Field 'id' expected a number but got 'edit'
models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from phonenumber_field.modelfields import PhoneNumberField class UserprofileCity(models.manager): def get_queryset(self): return super(UserprofileCity,self).get_queryset().filter(city='surat') class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE) # you an add extra fields as per requirements after city = models.CharField(max_length=100,default='') description = models.CharField(max_length= 500,default='') phone_number = PhoneNumberField(default='+91',max_length=13,help_text='enter mobile number with country code') age = models.IntegerField(default=18) image = models.ImageField(upload_to='profile_image',blank=True) def __str__(self): return self.user.username def create_profile(sender,**kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile,sender=User) views.py: from django.shortcuts import render,redirect from django.urls import reverse from .forms import RegistrationForm,EditProfileForm,ProfileForm from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('accounts:login')) else: form = RegistrationForm() args = {'form':form} return render(request,'accounts/reg_form.html',args) def profile_view(request,pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user':user} return render(request,'accounts/profile.html',args) def profile_edit(request): if request.method =='POST': form = EditProfileForm(request.POST,instance=request.user) profile_form = ProfileForm(request.Post,request.FILES,instance=request.user.userprofile) if form.is_valid() and profile_form.is_valid(): user_form = form.save() custom_form = profile_form.save(False) custom_form.user = user_form custom_form.save() return redirect(reverse('accounts:profile_view')) else: form = EditProfileForm(instance=request.user) profile_form = ProfileForm(instance=request.user.userprofile) args = { 'form':form, 'profile_form':profile_form } return render(request,'accounts/profile_edit.html',args) def password_change(request): if request.method=='POST': form = PasswordChangeForm(data = request.POST,user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request,form.user) return redirect(reverse('accounts:profile_view')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user = request.user) args … -
How to generate a new record based on the current new one and another one in the model in Django?
I need to create one record when user pass one and there is another one already in the model with same or suitable data. For example: models.py class Generated(models.Model): stage = models.PositiveSmallIntegerField() group = models.PositiveSmallIntegerField() and we already have a record Generated(stage=1, group=1) then we pass another one Generated(stage=1, group=2) and we need to generate one more record like Generated(stage=2, group=1) I just need to know how to get/find records in model when we check current passed record and then create one. -
Access to XMLHttpRequest at 'api url'' from origin 'client url'' has been blocked by CORS policy
i am working on full stack web and mobile projects with Django as backend and react/react-native as frontend. i am trying to post a form, it works great on react but it shows error in my react-native app. how can i post this form successfully? error screenshot below users.js export const CreateMerchantDetails = (formValues) => async (dispatch) => { console.log(formValues); const token = await AsyncStorage.getItem("token"); console.log(token); const config = { headers: { Authorization: "Token ".concat(token), }, }; axios .post(`${ROOT_URL}api/merchant/create`, formValues, { headers: config, }) .then((res) => { dispatch({ type: actionTypes.CREATE_MERCHANT_DETAILS, payload: res.data, }); }) .catch((err) => { console.log(err); const error = { msg: err.response, // status: err.response.status, }; dispatch({ type: actionTypes.CREATE_MERCHANT_DETAILS_ERROR, payload: error.response, }); }); }; screenshots settings.js import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secret_key_here' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth', 'rest_auth.registration', 'rest_framework.authtoken', 'phonenumber_field', 'merchant', 'orders', 'notifications' ] 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 = 'romex.urls' AUTH_USER_MODEL = 'merchant.MerchantDetails' REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "merchant.api.serializers.CustomRegisterSerializer", } REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Secure file sharing
I'm doing a project on secure file sharing using django framework. Can anyone answer my questions?? where should I upload my file's After uploading a file it must encrypt in aes format. 3)the uploaded files could only be retrieved when 2nd user having the key whic was generated during encryption. Now can anyone answer how to do these tasks using django. -
Django Deployment on CPanel Error "Apache doesn't have read permissions to that file. Please fix the relevant file permissions."
I am trying to deploy a django application on cpanel. I cloned my github repository and all dependencies have been installed and everything is complete but when I try to open the website it gives me this page... What do I need to do in order to fix this? I don't have any knowledge about these file permissions and am just looking to host a small project. -
Django show name of reference not id
this simple database i created then this my code for showing the data in view.py ... def get (request, photo_id) tag = PhotoTag.objects \ .values('tag_id') \ .filter(photo_id = photo_id) \ .all() context = { ... 'my_tag': tag } and this is in my template {% for data in my_tag %} {{ my_tag.tag_id }} {% endfor %} the result is number, what I need is showing the data of another table (tag table) like my_tag => tag_id => name (of another table) when I do another way in view.py like tag = PhotoTag.objects \ .values('tag_id') \ .filter(photo_id = photo_id) \ .all() for data in tag: tag_name = Tag.objects \ .values('name') \ .filter(id=data.get('tag_id')) \ context = { ..., 'my_tag': tag_name, } then in template {% for data in my_tag %} {{ my_tag.name }} {% endfor %} the result is what I need (showing the text name of references table) but it's only 1 data, it's not perfectly loop So Can someone help me solve this problem, or have a magic trick for solve it? -
How to add a foreign key to the username. Django REST framework
During serialization, i noticed that the post_author Foreign Key of the Post model is referencing the id of the creator and thus, i can't display the username of the creator in the REST API, only the post_author id. How can i add the username of the post_creator, so that it is readable to other users, when i fetch the data on the frontend? models.py // CustomUser = the Creator of the post. class CustomUser(AbstractUser): fav_color = models.CharField(blank=True, max_length=120) class Post(models.Model): post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') post_title = models.CharField(max_length=200) post_body = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.post_title views.py @api_view(['GET']) def post_list(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) serializers.py user model and post model serialization class CustomUserSerializer(serializers.ModelSerializer): """ Currently unused in preference of the below. """ email = serializers.EmailField(required=True) username = serializers.CharField() password = serializers.CharField(min_length=8, write_only=True) class Meta: model = CustomUser fields = ('email', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) # as long as the fields are the same, we can just use this instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = … -
Presenting ForeignKey Field As Radio Choices
I have the following setup: MODELS.PY class MeatMenu(models.Model): MEAT_CHOICES = ( ('chicken', 'Chicken'), ('beef', 'Beef'), ) meat_type = models.CharField(max_length=20, choices=MEAT_CHOICES) meat_price = models.DecimalField(max_digits=10, decimal_places=2) In the same model file, I use the MeatMenu model as a fk to allow users to buy the meat they want (can calc total cost using price [hence the need for a fk as opposed to direct model choices]) class BuyMeat(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE) meat_needed = models.ForeignKey(MeatMenu, on_delete=models.SET_NULL, blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date_created',) def __str__(self): return str(self.meat_needed) FORMS.PY In my form, I'm trying to have a user execute an order for the meat they want as follows: class BuyMeatForm(forms.ModelForm): meat_needed = forms.ModelChoiceField(queryset=None, to_field_name='service_name', widget=forms.RadioSelect, empty_label=None) class Meta: model = BuyMeat fields = '__all__' exclude = ('client', 'date_created') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['service_needed'].queryset = MeatMenu.objects.all() VIEWS.PY def buy_meat(request): if request.method == 'POST': form = BuyMeatForm(request.POST) if form.is_valid(): new_purchase = form.save(commit=False) new_purchase.client = request.user new_purchase.date_created = timezone.now() new_purchase.save() else: form = BuyMeatForm() context = {'buy_form': form} .................... PROBLEM The problem comes in customizing my "meat_needed" field in the form. As you can see in my forms.py file, I would like to customize the foreignkey dropdown-select into radio buttons whereby … -
Django static files not served with Docker
please find below my app architecture. static files are located at /my_project/app/static/ when i 'jump' into my web container docker exec -it my_project sh /usr/src/app/static folder do not contain static files I guess problem is path to serve static files but what is wrong with my configuration? - my_project |_app |_core |_wsqi.py |_settings |_base.py |_dev.py |_prod.py |_urls.py |_requirements |_static |_base.txt |_dev.txt |_prod.txt |_Dockerfile.prod |_entrypoint.prod.sh |_manage.py |_.dockerignore |_nginx |_Dockerfile |_nginx.conf |_.env.prod |_.gitignore |_docker-compose.prod.yml prod.py SITE_ID = 1 STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") docker-compose.prod.yml version: '3.7' services: web: restart: always build: context: ./app dockerfile: Dockerfile.prod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.prod extra_hosts: - "db:192........" nginx: build: ./nginx restart: always volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1338:80 depends_on: - web volumes: static_volume: media_volume: nginx.conf upstream app { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } location /media/ { alias /usr/src/app/media/; } }