Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: metaclass conflict: the metaclass of a derived class
from rest_framework import serializers from rest_framework.serializers import ModelSerializer from .models import Product class ProductSerializer(serializers, ModelSerializer): class Meta: model = Product fields = '__all__' -
How can I get django to work on https using elastic beanstalk and apache?
I have my .config files set up using the information available on aws and I have my load balancer listening on 443. My website is being served correctly via https when I connect using my elastic beanstalk url. Of course that url is not what my ssl certificate lists so there's an error but none the less, it is displaying all the html and static files. Https seems to be working there. When I attempt to visit my custom domain using http everything also displays correctly so my application seems fine, but when I attempt https using my custom domain nothing is loaded from my server. I just get the "Index of /" page. This is what I receive when my ALLOWED_HOSTS is incorrect so I assume it's something super simple in my settings file that is blocking django from allowing apache to serve the content over https to my custom domain. Or else theres one other place I'm missing that needs me to register my domain with my load balancer? Is that a thing? I feel like I've been scouring the internet for help here so any suggestions are very much appreciated. One other note is that I have … -
How to add Dyanmic Numpy Array field in Django Models
I wanted to add the numpy array as a field of my Django models using Django's default db.sqlite database. The "ArrayField" is not available with db.sqlite. Is there any option . Please Answer! -
Does queryset.values_list makes another call to db?
Let's say I have an already evaluated queryset. # queryset is evaluated here queryset = MyModel.objects.filter(name="blabla") for obj in queryset: # do some stuff if I call .values_list on this queryset later on, does it make an extra call to the database or fetch the response from the queryset object cache? obj_map = {k: v in queryset.values_list("id", "name")} # <- does it make a call? -
Django: Ajax Call Returning Expected Values, Not Entering Success
I have three ajax calls in an input form. All three operate in the same way. User clicks submit button, and URL params are passed to a function in views.py. The function is executing as expected and returning the values to the route in the Ajax call. When I visit the specific route with params route/cust-search?name=example&filter_by=example, I can see my data. The last stage uses the success function to grab the data from the route and load it into the pages' layout. My other two calls work and are set up in the exact same way. Why is this call not entering success? <script> $(document).on('submit','#cust_search',function(e){ e.preventDefault(); e.stopPropagation(); $.ajax({ type:'GET', url:'cust-search/', data:{name:$('#gc-input_name_search').val(), filter_by:$('#gc-input_filter_by').val(),}, success:function update_items(){ $('.search-results_table_body').html('').load( "{% url 'CustSearch' %}?name=" + $('#gc-input_name_search').val() + "&filter_by=" + $('#gc-input_filter_by').val()); }, error: function(){} }); e.stopImmediatePropagation(); return false; }) </script> -
Django: how to do unit test in updating views and models for web functionality
I am a testing learner and I have been learning to do unit test for a web project with django views and models. I am taking one of the perspect I want to test on as a learning example, which is a updating functionality of the website. class Tradie(models.Model): myUser = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True) joinDate = models.DateField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField( null=False, max_length=10, choices=[(_type.name, _type.value) for _type in GenderChoice], default='Male', blank=True ) description = models.CharField(max_length=200, blank=True) phone = models.CharField(max_length=10, blank=True) address1 = models.CharField(max_length=100, blank=True) address2 = models.CharField(max_length=100, blank=True, null=True) suburb = models.CharField(max_length=30, blank=True) state = models.CharField( null=False, max_length=10, choices=[(_type.name, _type.value) for _type in States], default='ACT', blank=False ) postcode = models.CharField(max_length=5, blank=True) and the corresponding tradie profile based on the class is as seen. def tradie_profile(request): if request.user.is_authenticated: try: tradie = Tradie.objects.get(myUser=request.user) except Tradie.DoesNotExist: raise Http404("Tradie does not exist") context = { "login_status": json.dumps(True), "description": tradie.description, "fullname": tradie.first_name + " " + tradie.last_name, "address": str(tradie.address1 + " " + tradie.suburb + " " + tradie.state + " " + tradie.postcode), "phone": tradie.phone, } return render(request, "Tradie/tradie_profile.html", context) else: raise Http404("Haven't logged in") and the corresponding update function for updating the profile is as seen. def update_tradie_profile(request): … -
GET http://localhost:8000/manifest.json 404 (Not Found) ERROR on django with react
I am currently learning React.js and started to combine it with django. I tried to build a simple homepage that will display Hello World! import logo from './logo.svg'; import './App.css'; import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ render(){ return ( <h1>Hello World!</h1> ) } } export default App; It works fine on the browser, but when I checked the console, there is an error GET http://localhost:8000/manifest.json 404 (Not Found). What is this manifest.json file that I am missing? This is how I set up my django project settings: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/build/static')] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontend/build')], ... ... ], }, }, ] My project tree looks like this: And the error looks like this: Any idea on what to do with this error? -
How to Update Multiple Image using generic view (UpdateView)
VIEWS.PY This is UpdateView where should I put the exact but maybe I'm wrong. The Image.objects.create is a model connected to Post Model. And the image is located to forms.py but I can't get all save files when i'm trying to click update for this multiple images. class UpdatePostView(LoginRequiredMixin,UserPassesTestMixin, UpdateView): model = Post form_class = PostForm template_name = "Dashboard/edit-post.html" def form_valid(self, form): form.instance.author = self.request.user p = form.save() images = self.request.FILES.getlist("image") for i in images: Image.objects.create(post=p, image=i) return super().form_valid(form) FORMS.PY -This is the forms where I put multiple Image "Image" for posting more images class PostForm(forms.ModelForm): image = forms.FileField(required=False, widget=forms.FileInput(attrs={ "class":"form-control", "multiple":True })) class Meta: model = Post fields = ('title','featured_image','content', 'category','tag','previous_post','next_post' ) -
Django can't display data from two models
I am trying to display data from two different models. The two models have a one-to-many relationship but I am not sure why it is not displaying the data from the MembersPresent model. Here are my models and view class fly_minute(models.Model): mode = ( ('Email', 'Email'), ('Zoom', 'Zoom'), ('Alternative', 'Alternative'), ) mode_of_meeting = models.CharField(max_length=100, choices=mode, blank=False, ) date = models.DateField() Time = models.TimeField() minute_prepared_by = models.CharField(max_length=25) location = models.CharField(max_length=25) authorize_by = models.CharField(max_length=25) item = models.TextField() owner = models.CharField(max_length=25) def __str__(self): return self.mode_of_meeting class MembersPresent(models.Model): flyminute = models.ForeignKey(fly_minute, on_delete=models.CASCADE) name = models.CharField(max_length=25) status = models.CharField(max_length=25) email = models.EmailField(max_length=25) phone = models.IntegerField() def __str__(self): return self.name @login_required(login_url='login_page') def MinutesReport(request, minute_id): report = fly_minute.objects.filter(id=minute_id) return render(request, 'minute_report.html', locals()) {%for rpt in report%} <tbody> <tr class="table-active"> <td>{{rpt.flyminute.name}}</td> <td>{{rpt.flyminute.status}}</td> <td>{{rpt.flyminute.email}}</td> <td>{{rpt.flyminute.phone}}</td> </tbody> {%endfor%} -
Django DefaultRouter and ViewSets question
I've this route: router.register(r'posts/(?P<post_id>\d+)/comments', views.CommentViewSet) How do i get post_id in CommentViewSet class? -
user_passes_test for models other than User in Django
I want to allow a user to edit a project page if ifAdmin (an object in uProject model) == True. I am currently trying to use @user_passes_test to render a view to update the project, but am having difficulties. Here's my code. def admin_check(uProjects): return uProjects.ifAdmin = True @user_passes_test(admin_check) def update(request): etc, etc, etc Please let me know what I can do instead. Thanks in advance@ -
(Django) Making Custom on_delete & CASCADE functions
There is a legacy codebase and its deletion system has to be changed to soft-deletion. I made an additional field in each model like so: is_deleted = models.BooleanField(default=False) and in the utils.py file, I have defined some functions to utilize the is_deleted field . . . def card_related_objs_soft_cascade(instance): print("initiating 'card_related_objs_soft_cascade'...") with transaction.atomic(): with suppress(ObjectDoesNotExist): instance.order.soft_delete() instance.invoices.all().qs_soft_delete() instance.payments.all().qs_soft_delete() def account_related_objs_soft_cascade(instance): print("initiating 'account_related_objs_soft_cascade'...") with transaction.atomic(): instance.contacts.all().qs_soft_delete() instance.meeting_notes.all().qs_soft_delete() instance.attachment.all().qs_soft_delete() class ReusableModelMethods: def soft_delete(self): with transaction.atomic(): print(f"initiating 'soft_delete' on {self.__class__.__name__} instance") ops = { "Board": board_related_objs_soft_cascade, "CardList": cardlist_related_objs_soft_cascade, "Card": card_related_objs_soft_cascade, "Customer": account_related_objs_soft_cascade, "Supplier": account_related_objs_soft_cascade, } self.is_deleted = True self.save() ops.get(self.__class__.__name__, lambda *args: None)(self) class ReusableQuerySetMethods(models.query.QuerySet): @classmethod def as_manager(cls): manager = SoftDeleteManager.from_queryset(cls)() manager._built_with_as_manager = True return manager def qs_soft_delete(self, *args, **kwargs): print("initiating 'qs_soft_delete'...") for instance in self: instance.soft_delete() self._result_cache = None qs_soft_delete.alters_data = True However, when you look at this, there is a lot to maintain as the codebase expands. For instance, in def account_related_objs_soft_cascade(instance), there are three models (contacts, meeting_notes, attachment) related to this account model. As we add more models, I must add more of instance.some_model_set.all().qs_soft_delete() and the chance is, I would forget to do this... And thus, I would like to implement something that does this automatically, hence I looked at CASCADE … -
Modifing one off many post with JS and Django?
so I am currently working on CS50 network project for and I am stuck in to edit a post upon many post that are displayed. I have a view that displays all the post done by a user. def profile(request, username): if request.method == "GET": user = User.objects.filter(username=username) profile = Profile.objects.filter(user=user[0]).get() posts = Post.objects.filter(user=user[0]).order_by('-publish_date') return render( request, 'network/profile.html', { 'posts': page, 'profile': profile, } ) And it is displayed in and html template. {% for post in posts %} <div class="card text-center"> <div class="card-header"> <a href="{% url 'profile' post.user %}"> {{ post.user }} </a> </div> <div class="card-body"> <h5 class="card-title">{{ post.content }}</h5> <p class="card-text">{{ post.num_likes }}</p> <a href="#" class="btn btn-primary" onclick="editpost()"> Edit </a> </div> <div class="card-footer text-muted"> {{ post.publish_date }} </div> </div> <br> {% endfor %} I understand that I need to have a function that with JS changes the tag and tag from with in that specific form but I know how to get it form only that one post and not from all of the post that are being produced by Djangos templating engine. Once I can select them I will copy there information into a var and change the style so the display in non as well as … -
Django Channel stuck for a while
currently I am having some problems with the Django channel. I have been developed a web application to receive data from GNSS and display its position as a machine in the frontend. So I have used the Django channel to connect and received data from GNSS. After we connected to GNSS, around 15 to 17 seconds, we can process data inside the Django channel and return its position into the frontend but after the next 17 seconds, data are still receiving in the Django channel but it stops return data to the frontend to display and when I disconnected real GNSS from the system, those data after 17 seconds are starting processing again. Does anyone know how to solve this? Thank you -
Django django.db.utils.OperationalError in test after adding signals
My test files works perfectly fine but after adding signal getting django.db.utils.OperationalError: no such table: contacts_modellog What acctually happened my signal is not using migarations or other? Here is the signal code. IGNORE_LIST = ['ModelLog'] @receiver(post_save) def post_save_signal(sender, created, **kwargs): if created and sender.__name__ not in IGNORE_LIST: ModelLog.objects.create(model_name=sender.__name__, action='Created') elif sender.__name__ not in IGNORE_LIST: ModelLog.objects.create(model_name=sender.__name__, action='Edited') full traceback Creating test database for alias 'default'... Traceback (most recent call last): File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: contacts_modellog The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/test/runner.py", line 684, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/test/runner.py", line 604, in setup_databases return _setup_databases( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/test/utils.py", line 169, in setup_databases connection.creation.create_test_db( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/base/creation.py", line 67, in … -
LDAPInvalidServerError at /login/ No exception message supplied
I used Python3 in windows 10 to write a django2 web app. I tried to configure the LDAP login, but failed. When I test using postman to test, it could get the reply successfully. That is, I send a request to https://example.com/staff, with some authentication code and payload containing username and password, and it reply me with the LDAP reply. However, when I tried to using ldap3 in Django, seems like Django ldap3 requires a ldap server address and port, a web address containing LDAP API could not work. class LDAPBackend: def authenticate(self, request, username=None, password=None, **kwargs): now = datetime.datetime.now() text = str(now.day) + 'ls@bBk3y' def computeMD5hash(my_string): m = hashlib.md5() m.update(my_string.encode('utf-8')) return m.hexdigest() # set username to lowercase for consistency username = username.lower() # get the bind client to resolve DN logger.info('authenticating %s' % username) # set your server server = Server("https://example.com/staff") try: print("begin connect!") conn = Connection(server, user=username, password=password, auto_bind=True,) conn.open() conn.bind() print("connected") except LDAPBindError as e: logger.info('LDAP authentication failed') logger.info(e) return None user = UserModel.objects.update_or_create(username=username) return user def get_user(self, user_id): try: return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None always show this: LDAPInvalidServerError at /login/ No exception message supplied -
Django Rest Framework custom permission not working
I want users to have access only to the records that belong to them, not to any other users' records so I've created the following view: class AddressViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = [IsAuthenticated, IsOwner] queryset = Address.objects.all() def retrieve(self, request, pk): address = self.address_service.get_by_id(pk) serializer = AddressSerializer(address) return Response(serializer.data, status=status.HTTP_200_OK) I want only the owner of the records to have access to all the methods in this view ie retrieve, list, etc (I'll implement the remaining methods later) so I created the following permissions.py file in my core app: class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): print('here in has_object_permission...') return obj.user == request.user this wasn't working, so after going through stackoverflow answers I found this one Django Rest Framework owner permissions where it indicates that has_permission method must be implemented. But as you can see in that answer, it's trying to get the id from the view.kwargs but my view.kwargs contains only the pk and not the user. How can I fix this? Do I need to implicitly pass the user id in the request url? that doesn't sound right. Here's the test I'm using to verify a user cannot access other user's records: def test_when_a_user_tries_to_access_another_users_address_then_an_error_is_returned(self): user2 = UserFactory.create() … -
How to set up different weekday/weekend schedules for celery beat in Django?
How do I go about scheduling my tasks differently for weekdays and weekends in celery beat? The schedule is set as follows in my settings.py file { "task_weekday": { "task": "tasks.my_regular_task", "schedule": crontab(minute="0-30", hour="4,5", day_of_week="mon-fri"), "options": {"queue": "queue_name"}, }, "task_weekend": { "task": "tasks.my_regular_task", "schedule": crontab(minute="0-5", hour="10,12", day_of_week="sat,sun"), "options": {"queue": "queue_name"}, }, } However when I set it up, it ran the weekday schedule today (3/21/2021 Sunday) instead of picking up the weekend schedule. I have the app timezone set to 'US/Pacific' and the CELERY_ENABLE_UTC is set to False. After setting it up I see the following log entry but it runs the weekday tasks schedule. [2021-03-21 17:57:50,082: DEBUG/MainProcess] Current schedule: <ScheduleEntry: task_weekday tasks.my_regular_task() <crontab: 0-30 4,5 mon-fri * * (m/h/d/dM/MY)> <ScheduleEntry: task_weekend tasks.my_regular_task() <crontab: 0-5 10,12 sat,sun * * (m/h/d/dM/MY)> <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)> I have tried running the tasks every few minutes as well to test which schedule it picks up and picks up the weekend schedule: { "task_weekday": { "task": "tasks.my_regular_task", "schedule": crontab(minute="*/2", hour="*", day_of_week="mon-fri"), "options": {"queue": "queue_name"}, }, "task_weekend": { "task": "tasks.my_regular_task", "schedule": crontab(minute="*/3", hour="*", day_of_week="sat,sun"), "options": {"queue": "queue_name"}, }, } [2021-03-21 18:03:27,075: DEBUG/MainProcess] Current schedule: <ScheduleEntry: task_weekend tasks.my_regular_task() <crontab: */3 … -
Django serilizator object updating problem
I would like to ask where it could be a problem with my serializer or using it. I want to update serialized data inside object personal info but it keeps throwing me an error: Traceback (most recent call last): File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django\core\handlers\exception.py", line 47, i n inner response = get_response(request) File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django\core\handlers\base.py", line 181, in _g et_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django \views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\rest_framework\serializers.py", line 200, in s ave self.instance = self.update(self.instance, validated_data) File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\serializers.py", line 48, in update instance.user = attrs.get('user', instance.user) AttributeError: 'PersonalInfoSerializer' object has no attribute 'user' Here's my model PersonalInfo: class PersonalInfo(models.Model): user = models.ForeignKey('User', models.DO_NOTHING, db_column='user', blank=True, null=True) firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) card_id = models.CharField(unique=True, max_length=255) street = models.CharField(max_length=255) postal_code = models.IntegerField() city = models.CharField(max_length=255) photo = models.BinaryField(blank=True, null=True) debet_card_number = models.CharField(max_length=16) created_at = models.DateTimeField() last_update = models.DateTimeField() class Meta: managed = False db_table = 'Personal_info' Here's my serializer class: class PersonalInfoSerializer(serializers.Serializer): user = serializers.IntegerField(required=False) firstname = … -
Is it a good practice to customize ListCreateAPIView in Django rest framework?
I tried to use ListCreateAPIView with has_object_permission function and it didn't work. So i customized ListCreateAPIView instead. I want to know if it is a good practice or not? Here is my code: from rest_framework.response import Response from .models import Post from .serializers import PostSerializer from rest_framework.generics import ListCreateAPIView class MyList(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer def post(self, request, *args, **kwargs): author = request.data.get('author') if int(author) == request.user.pk: return self.create(request, *args, **kwargs) return Response('Bad request') -
how to get data from an api ... is it used flask or django?
How are you? I hope you are well ........... I have studied python and I have used your flask and django framework and I have been learning on my own I am starting in programming and a friend tells me to obtain the data from an api to keep learning .... but he told me only that..... to get the data from an api ... in which I have to solve incomplete methods ... and that's fine ... but I can do it, no problem. .. but it asks me to get the data from an api https://dogs.magnet.cl/ .... and .... there is the problem, I have never interacted with an api ... is flask used? or django ??? I really don't know ... pls any documentation or video is well received -
Create a database record with a new data instance in same view
I have two models i. AppUserModel class AppUserModel(AbstractUser): email = models.EmailField(_('email address'), unique=True,) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True) user_type = models.ForeignKey(UserType, on_delete=models.CASCADE,null=True, blank=True) joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email ii. Company Model class Company(models.Model): company_name = models.CharField(max_length=100) company_slug = models.SlugField(null=True, blank=True) company_address = models.TextField(blank=True,null=True) company_email = models.EmailField(blank=True,null=True) company_email_cc = models.EmailField(blank=True, null=True) company_phone = models.CharField(max_length=30,blank=True,null=True) company_RC = models.CharField(max_length=20,blank=True,null=True) company_registered_on = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.company_slug = slugify(self.company_name) super(Company, self).save(*args, **kwargs) def __str__(self): return self.company_name What I want to do i. Allow user to register with email, password and company name ii. Create a Company instance with the company name provided iii. Create a database instance of the user using the company instance created earlier. this is my view def post(self, request): register_form = RegisterUserForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data['email'] user_company = register_form.cleaned_data['company'] password1 = register_form.cleaned_data['password1'] password2 = register_form.cleaned_data['password2'] new_company = Company.objects.create( company_name=user_company, user_type='Admin') new_user = AppUserModel( email=email, password=password1, user_type='Admin', company=new_company ) new_user.save() context = { } return render(request, 'account/register.html', context=context) -
Django os.getenv('SECRET_KEY') throwing "The SECRET_KEY setting must not be empty."
I'm setting up Django using os.getenv to prepare it for deploying using Docker but it seems it is not reading the .env file. Any idea why is not reading it? Here is the setup: .env SECRET_KEY=foo DEBUG=True ALLOWED_HOSTS=localhost,127.0.0.1 settings.py abstraction import os from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS') -
How to access other model fields from new View
I'm trying to build a Wish list, I have a model for the listings, and a model for the wish list, I have succeeded in making it work but.. I have to loop over all the listings first and match with the product id in my wish list so i can access the fields such as title and image.. is there any easier way to do this than looping over all the listings until finding the matched ones ? views.py def add_to_wishlist(request, product_id): product = WishList.objects.filter(listing_id=product_id, user=request.user.username) if product: product.delete() else: product = WishList() product.listing_id = product_id product.user = request.user.username product.save() return HttpResponseRedirect(request.META['HTTP_REFERER']) def wishlist(request): product = WishList.objects.filter(user=request.user) all_listings = AuctionListing.objects.all() return render(request, "auctions/wishlist.html", { 'wishlist': product, 'all_listings': all_listings }) models.py class AuctionListing(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_bid = models.IntegerField(null=True) image = models.CharField(max_length=1000, blank=True) category = models.CharField(max_length=100) seller = models.CharField(max_length=100, default="Default_Value") class WishList(models.Model): user = models.CharField(max_length=64) listing_id = models.IntegerField() wishlist.html {% extends "auctions/layout.html" %} {% block title %}Users Wishlist {% endblock %} {% block body %} <div class="col-12 mx-auto"> <h1 class="h3">My Wishlist</h1> <div>Manage your wishlist</div> {% if wishlist %} {% for listing in all_listings %} {% for product in wishlist %} {% if listing.id == product.listing_id%} <div class="card-mb-3"> … -
How to solve Method "POST" not allowed 405
I'm using Django Rest Framework for API and I faced this problem. In views.py my class inherits from ModelViewSet, but for some reason it doesn't allow making a POST request. For frontend I'm using React JS and I make a POST request from there. And in the end I'm getting an error like this: POST http://127.0.0.1:8000/api/software/3/ 405 (Method Not Allowed). Here's views.py: from rest_framework.viewsets import ModelViewSet from .serializers import ( CategorySerializer, SoftwareSerializer, SoftwareListRetrieveSerializer, CategoryDetailSerializer, CustomPaginatorSerializer ) from ..models import Category, Software class CategoryViewSet(ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer pagination_class = None action_to_serializer = { "retrieve": CategoryDetailSerializer, } def get_serializer_class(self): return self.action_to_serializer.get( self.action, self.serializer_class ) class SoftwareViewSet(ModelViewSet): queryset = Software.objects.all() serializer_class = SoftwareSerializer pagination_class = CustomPaginatorSerializer action_to_serializer = { "list": SoftwareListRetrieveSerializer, "retrieve": SoftwareListRetrieveSerializer } def get_serializer_class(self): return self.action_to_serializer.get( self.action, self.serializer_class ) Here's urls.py: from rest_framework import routers from .views import CategoryViewSet, SoftwareViewSet router = routers.SimpleRouter() router.register('category', CategoryViewSet, basename='category') router.register('software', SoftwareViewSet, basename='software') urlpatterns = [] urlpatterns += router.urls