Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL pattern to manage creation and update in the same view - NoReverseMatch error
I'm facing a 'NeReverseMatch' error that I'm not able to solve, even if I'm quite convinced it's probably a stupid error, something I missed... as I reproduce a pattern I implemented earlier in the same app. The context is the following: I have the same view for creating and updating an object. The difference is that in the second case, I have the id. Thus, related urls look like this (I put the whole file to ensure there is no mismatch with other urls): app_name = "polls" urlpatterns = [ path("", views.index, name="index"), path("get_chart_data/", views.get_chart_data, name="chart_data"), path("set_proxy/", views.set_proxy, name="set_proxy"), path("accept_proxy/", views.accept_proxy, name="accept_proxy"), path("cancel_proxy/", views.cancel_proxy, name="cancel_proxy"), path("sign_up/", views.new_user, name="sign_up"), path("login/", views.login_user, name="login"), path("logout/", views.logout_user, name="logout"), path("<slug:comp_slug>/", views.company_home, name="company_home"), path("<slug:comp_slug>/admin_users/", views.adm_users, name="adm_users"), path("<slug:comp_slug>/admin_load_users/", views.adm_load_users, name="adm_load_users"), path("<slug:comp_slug>/admin_profile/", views.adm_user_profile, name="adm_create_user"), path("<slug:comp_slug>/admin_profile/<int:usr_id>", views.adm_user_profile, name="adm_user_profile"), path("<slug:comp_slug>/change_password/", views.change_password, name="change_password"), path("<slug:comp_slug>/admin_delete_user/<int:usr_id>", views.adm_delete_user, name="adm_delete_user"), path("<slug:comp_slug>/admin_events/", views.adm_events, name="adm_events"), path("<slug:comp_slug>/admin_create_event/", views.adm_event_detail, name="adm_create_event"), path("<slug:comp_slug>/admin_update_event/<int:evt_id>/", views.adm_event_detail, name="adm_event_detail"), path("<slug:comp_slug>/admin_delete_event/<int:evt_id>", views.adm_delete_event, name="adm_delete_event"), path("<slug:comp_slug>/admin_groups/", views.adm_groups, name="adm_groups"), # ===== THE 2 FOLLOWING LINES ARE THE ISSUE ===== path("<slug:comp_slug>/admin_group_detail/", views.adm_group_detail, name="adm_create_group"), path("<slug:comp_slug>/admin_group_detail/<int:grp_id>/", views.adm_group_detail, name="adm_group_detail"), path("<slug:comp_slug>/admin_delete_group/<int:grp_id>", views.adm_delete_group, name="adm_delete_group"), path("<slug:comp_slug>/admin_options/", views.adm_options, name="adm_options"), path("<slug:comp_slug>/<slug:event_slug>/", views.event, name="event"), path("<slug:comp_slug>/<slug:event_slug>/<int:question_no>", views.question, name="question"), path("<slug:comp_slug>/<slug:event_slug>/<int:question_no>/vote", views.vote, name="vote"), path("<slug:comp_slug>/<slug:event_slug>/results", views.results, name="results"), ] The pattern is the same for users management (adm_user_profile view) with no issue. Here is … -
Override a model's DELETE method from real delete to setting a property in Django RESTful framework
We are using a django-rest-framework as our backend. I have a model Product which is the Foreign Key of another Order model, which acts as both a order and an audit log. Now suppose we are not going to sell this Product anymore. We need to apply DELETE method on the Product; and we still want to preserve everything in Order. However, if the Product is really deleted and the on_delete method on it is SET_NULL, then all info that is related to Product is lost. Which is not what I wanted. class Order(models.Model): product = models.ForeignKey(Product, blank=True, null=True, on_delete=models.SET_NULL) So my question is: A common practice in other framework is using soft-delete, i.e. adding a "delete=0" property on Product. And the DELETE method only change the property to "delete=1" rather than real delete. Is it do-able when using django-rest-framework? And how? Is there any other good practices to realize this requirement, i.e. to delete the foreign key while perserving the foreign key's metadata? -
Django Form retrieve data from database
I have a form in Django that enables me to post data to the database. I'd like to create a dropdown button that shows me the previous entries from the database, which I can select re-render the data in the original form, allowing me to update and post back to the database. I'm just starting out with Python, which I think is amazing, but I've not really grasped it yet. So I'm probably doing it completely wrong but here goes. I'm starting with just populating the dropdown. So within my models.py, I have. class Investor(models.Model): investor_name = models.CharField(max_length=255, blank=False) investor_website = models.URLField(max_length=255, blank=False) investor_portfolio = models.URLField(max_length=255, blank=False) investor_comment = models.TextField() def __str__(self): return str(self.investor_name) class showInvestor(models.Model): investorName=models.CharField(max_length=100) class Meta: db_table="apps_investor" Then within my views.py def showInvestor(request): results=showInvestor.objects.all() return render(request,"add_investor.html",{"showInvestor":results}) And then within my HTML template, i have: <div class="col-lg-2"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">Update Existing Investor <i class="mdi mdi-chevron-down"></i></button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for results in showInvestor %} <option> {{results.investor_name}} </option> {% endfor %} </div> </div> </div><!-- end col --> but when I click the drop-down I don't get any entries. What am I doing wrong here? Thanks -
Object doesn't exist in DB after consequential calls
I have the following flow for object creation: A user wants to create an object on a webservice. In order to do it - I check if the user is eligible to pay a fee for it. We make a request to know how much the user should pay. If 0 - user will see the regular Create button, if >0 he will see the PayPal button. User fills in data and in the second case presses the PayPal button. We make 2 consequential API requests: Create an object with the parameter is_draft=True. Return its id. Create an order object and use the id from the previous step. Sometimes we cannot create an order, because the object doesn't exist in DB yet. Django setting: DATABASES["default"]["ATOMIC_REQUESTS"] = True Django models: class Object1(models.Model): name = models.CharField() ... class Object2(models.Model): name = models.CharField() ... class Order(models.Model): user = models.ForeignKey(User) amount = models.DecimalField() #naive polymorphism object1 = models.ForeignKey(Object1) object2 = models.ForeignKey(Object2) # An object will be created after PayPal's call to the webhook endpoint class OrderPayment(models.Model): ... order = models.ForeignKey(Order) The problem is that I cannot call transaction.commit() after any object creation (Object1 or Object2) because I use atomic request and it leads to … -
Import ckeditor could not be resolved
I am trying to use RichTextFields through ckeditor in my django project. What I initially thought would be an easy task has caused me nightmares. I am able to pip install django-ckeditor easily. I have followed all the required steps as per https://pytutorial.com/django-ckeditor including adding to settings.py, adding MEDIA_ROOT etc etc. I have collected static and ran migrations and still nothing seems to be working. I get to the final step where I am importing in my models.py but I get a squiggly yellow underline that says "Import "ckeditor_uploader.fields" could not be resolved". settings.py file: INSTALLED_APPS = [ 'projects.apps.ProjectsConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = "uploads/" urls.py: from projects.views import projects from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include ('projects.urls')), path('users/', include ('users.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: from django.db import models import uuid from users.models import Profile from *ckeditor_uploader.fields* import RichTextUploadingField class Project (models.Model): owner = models.ForeignKey( Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) … -
get_queryset in ListAPIView retuns blank list
In my app I have two types of users i.e. company and employees. I am trying to filter the queryset based on this like the following: class ProductListAPIView(generics.ListAPIView): serializer_class = ProductSerializer # pagination_class = StandardResultsSetPagination permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): if self.request.user.is_company == 'True': user_company = self.request.user.id emp = list(Employee.objects.filter(company=user_company).values_list('pk', flat=True)) emp.append(user_company) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset elif self.request.user.is_employee == 'True': com = Company.objects.filter(pk=self.request.user.id).pk emp = list(Employee.objects.filter(company=com).values_list('pk', flat=True)) emp.append(com) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset I tried the URL with both employee and company credentials but it always return an empty list but when I use the company code independently it works perfectly. -
How to call file-send API which use FileUploadParser
I am using file upload API with this document https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser I made the class in view.py class FileUploadView(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) and then make url in urls.py urlpatterns += [ re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view()) ] Now I can access http://localhost:8008/upload/test.mp3 OK GET is not allowed , but there is not file upload form, how can I test this?? or is there any way to send post request with file by curl or something ?? -
What is best from creating API from mongoDb [closed]
So i have to create a Api from existing mongo Database where we send json request to it like {"dateFrom": "2021-10-01 00:00:00", "dateTo": "2021-10-15 23:59:59", "STATUS":"Pending","AMOUNT":"100"} and api should filter data from mongodb on base of request. and then respond with matching json data back sometime i have to send sum of all the AMOUNT and total results back too as json data. i was using django + pymongo. but i am having issue with speed. i am not sure that django + python + mymongo is right tools for it . i wanna know what else options do i have.i have make +50 api from more then hundred thousand entry's. someone told me express.js is also a good option. but i am confused. -
Error: redefinition of group name 'pk' as group 2; was group 1 at position 38
Using Django Rest Framework, I am creating endpoints for doctor model in my app app_api using ModelViewSet. I am encountering the following error on adding an extra action for updating the is_verified field with verify method having @action decorator. error at /app_api/viewset/doctor/6/ redefinition of group name 'pk' as group 2; was group 1 at position 38 Please find the code below. urls.py router = DefaultRouter() router.register('doctor', views.DoctorViewSet, basename='doctor') urlpatterns = [ path('viewset/', include(router.urls)), path('viewset/<int:pk>', include(router.urls)), ] model.py # Doctor Model class Doctor(models.Model): name = models.CharField(max_length=100) designation = models.CharField(max_length=100) description = models.TextField(blank=True, default='') is_verified = models.BooleanField(default=False, blank=True) serializer.py # Doctor Model Serializer class DoctorModelSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' read_only_fields = ('is_verified',) # Doctor Partial Update Model Serializer class DoctorUpdateVerifyModelSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ('id', 'name', 'is_verified') read_only_fields = ('name',) views.py class DoctorViewSet(viewsets.ModelViewSet): serializer_class = DoctorModelSerializer queryset = Doctor.objects.all() def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'PATCH' and self.action == 'verify': serializer_class = DoctorUpdateVerifyModelSerializer return serializer_class @action(methods=['patch'], detail=True) def verify(self, request, pk=None): serializer = self.get_serializer(self.get_object(), data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) Now when I am adding an extra action for routing the method verify with the @action decorator, I am getting the following error … -
Django ORM group by date and get total value
This is the model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=10, decimal_places=2) This is the query: end_date = timezone.now() start_date = end_date - timedelta(days=7) Transaction.objects.filter( date__range=[start_date, end_date], ) .values("date__date") .annotate(expenditure=Sum("amount")) .values("expenditure", date=F("date__date")) .order_by("date") This is the output: [ { "expenditure": 70.0, "date": "2021-10-28" }, { "expenditure": 20.0, "date": "2021-10-30" } ] But I want something like this as the output: [ { "expenditure": 0.0, "date": "2021-10-26" }, { "expenditure": 0.0, "date": "2021-10-27" } { "expenditure": 70.0, "date": "2021-10-28" }, { "expenditure": 0.0, "date": "2021-10-29" }, { "expenditure": 20.0, "date": "2021-10-30" }, { "expenditure": 0.0, "date": "2021-10-31" }, { "expenditure": 0.0, "date": "2021-11-01" }, ] I know I can process the data after the query but I wanted to know if it is possible to get this output using Django ORM? -
How to make uWSGI main thread not serve requests for the Django web application?
In my Django application, in the __init__.py, I have a class which spins up an event loop. class X: def __init__(self): self.__loop = asyncio.get_event_loop() async def foo(self): ... def do_stuff(self): # some logic here self.__loop.run_until_complete(foo()) In the __init__.py I just have x = X() In my Django views, I do from myapp import x def example_view(request): result = x.do_stuff() return JsonResponse({"result": result}) But the problem is that with uWSGI, if the thread that serves the request is same as that was used during initialization, I get the Django's SynchronousOnlyOperation exception as it detects a running event loop in that particular thread. So my question is, is there a way not to use that initializing thread for serving requests or some other alternative to fix this issue? uwSGI is configured to run multiple processes and multiple threads, with --enable-threads -
django registerForm.is_valid() Does not allow the rest of my code to work
My custom user uses the mobile number as username But when the user wants to get the verification code for his number again, he encounters an error I do not even know where this error came from because I did not write this error views def account_register(request): if request.user.is_authenticated: return redirect("store:home") registerForm = RegistrationForm(request.POST) if request.method == "POST": print(registerForm) if registerForm.is_valid(): registerForm.save(commit=False) username = registerForm.cleaned_data["user_name"] phone_number = registerForm.cleaned_data["phone_number"] password = registerForm.cleaned_data["password"] user = User.object.filter(phone_number=phone_number) if user.count() == 0: new_user = User(phone_number=phone_number) new_user.username = username new_user.phone_number = phone_number new_user.set_password(password) new_user.is_active = False new_user.save() otp_user = f"{new_user.otp}" print(otp_user) send_sms(otp_user, new_user.phone_number) elif not user.phone_number_verified: otp_user = f"{user.otp}" print(otp_user) send_sms(otp_user, user.phone_number) return render(request, "account/verificationpage.html", {"form": registerForm}) else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm}) forms class RegistrationForm(forms.ModelForm): user_name = forms.CharField( min_length=4, max_length=50, help_text='Required' ) phone_number = forms.CharField(max_length=11, help_text='Required', validators=[RegexValidator(regex=r'09(\d{9})$')], ) password = forms.CharField(widget=forms.PasswordInput) def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if User.objects.filter(phone_number=phone_number, is_active=False).exists(): raise forms.ValidationError( 'Please use another phone number, that is already taken') return phone_number error User with this Phone number already exists -
how to split a model field into two additional fields in django
I have a simple model like this: class Place(models.Model): location = LocationField( map_attrs={"style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72", "center": (17.031645, 51.106715)}) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) the location field gets a latitude,longitude of a selected loction using a mapbox api. when, submitted, it gets saved like this: location = (43.12,54,12) I want to split this output and save it into latitude and longitude field. how do I write a pre_save method in order to do this? -
Upload file on Django REST framework default view
I am using Django REST framework. It makes UI easily api_view like this @api_view(['POST', 'GET']) def uploadFile(request): data = {'meta':'upload','status':1} return Response(response) There appears form automatically. Is it possible to add file upload form on this?? I have found samples of Django REST framework and some frontend, however couldn't find the form using default view. -
DRF Serializer doesn't recieve value from request for ManyToMany field
My Model is class ChatRoom(models.Model): name = models.CharField(max_length=55, verbose_name='Имя чата', unique=True) users = models.ManyToManyField( CustomUser, verbose_name='Пользователи', related_name='user_chatrooms', null=True ) My Serializer for this model class ChatRoomSerializer(serializers.ModelSerializer): users = UserInfoSerializer(many=True, read_only=False) class Meta: model = ChatRoom fields = [ 'name', 'users' ] View looks @api_view(['POST']) @permission_classes([IsAuthenticated]) def api_create_chat(request): if request.method == 'POST': serializer = ChatRoomSerializer(data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I do request (here is body) <QueryDict: {'name': ['benny'], 'users': ['11,1']}> In this case I recieve Error {'users': [ErrorDetail(string='This field is required.', code='required')]} And I can't understand what is wrong here. When I change parameter to read_only=True in UserInfoSerializer it works, but it doesn't add user to new Chat object. { "name": "benny", "users": [] } -
Unable to execute .sh file from docker container in Windows
I am using Windows 10, and working on a Django Project with Docker. If I run a python command from inside docker container, it runs perfectly. E:\path>docker exec -it my_docker_container bash root@701z00f607ae:/app# python manage.py makemigrations authentication No changes detected in app 'authentication'enter code here But when I try to run same command using a .sh file, it gives different output. root@701z00f607ae:/app# cat ./migration_script.sh python manage.py makemigrations authentication root@701z00f607ae:/app# ./migration_script.sh '. installed app with label 'authentication Note: Executing ./migration_script.sh works perfectly on Linux based system. -
Django "NotImplementedError: `to_internal_value()` must be implemented" when sending a patch request
I'm trying to get an updated normalized resource when I update a resource using patch. (Using APIRequestFactory in my TestCase tests e.g self.factory.patch) LoadBaseSerializer inherits BaseSerializer and using to_representation. I'm doing this to return a customized serializer. However, I keep getting that annoying error. The patch request contains {'carrier' : 2 }. I expect to return the whole serialized resource, but I guess this only works for GET requests. How am I able to get this work for PATCH/POST methods? View: class LoadUDView(RetrieveUpdateDestroyAPIView): serializer_class = NormalizedLoadSerializer queryset = Load.objects.all() My serializer looks like this: # custom serializer class NormalizedLoadSerializer(LoadBaseSerializer): # not working, still get error def to_internal_value(self, data): load_data = data['carrier'] return super().to_internal_value(load_data) def to_representation(self, instance): # dict values serialized using ModelSerializer data = dict( contacts=self.get_driver_contacts(instance.carrier), drivers=self.get_drivers(instance.carrier), income = IncomeSerializer(instance.income, read_only=True).data, expense = ExpenseSerializer(instance.expense, read_only=True).data, stops = StopSerializer(instance.stops, many=True, read_only=True).data, load=LoadSerializer(instance, read_only=True).data, income_line_items= self.get_income_line_items(instance), expense_line_items= self.get_expense_line_items(instance), addresses=self.get_addresses(instance) ) return data LoadBaseSerializer: # inherit BaseSerializer and added helper functions class LoadBaseSerializer(serializers.BaseSerializer): def get_income_line_items(self, instance): income = instance.income.income_line_items.all() return IncomeLineItemSerializer(income, many=True).data def get_expense_line_items(self, instance): expense = instance.expense.expense_line_items.all() return ExpenseLineItemSerializer(expense, many=True).data def get_addresses(self, instance): data = [stop.address for stop in instance.stops.all()] return AddressSerializer(data, many=True).data def get_driver_contacts(self, carrier): data = [driver.contact for driver in … -
why isn't django creating my media directory through my update form ,but works fine when is use admin panel?
im trying to upload a profile picture and it works fine when using the admin panel but when is use my template form it give the wrong path(i know this because i displayed it to check the url) like so... <p>{{user.userprofile.profile_image.url}}</p> output on html page: /media/check.png when it should instead be: /media/images/check.png Note: everything else works fine on my form and it even shows that the image url was update in the admin panel but only shows the image name and not (images/img_name.png) as it should form: <form method="post" action="{%url 'profile-view' username=user.username%}" enctype="multipart/form-data" class="myOverlayForm"> {%csrf_token%} <label for="id_profile_image">Profile Image: <i class="fa fa-upload" style="font-size: 30px;"></i></label> <input type="file" name="profile_image" accept="image/*" id="id_profile_image"> <div class="form-group"> <label for="bioInput">Bio: </label> {%if form.errors%} <div class="alert alert-warning alert-dismissible fade show my_error" role="alert"> <strong>{{form.errors.bio}}</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {%endif%} <div class="form-group"> </div> <input type="text" class="form-control" name="bio" maxlength="150" minlength="25" id="id_bio"> <small id="bioHelp" class="form-text text-muted">Please avoid to putting out very personal information.</small> </div> <div class="form-group"> <label for="bioInput">Age:</label> <input type="number" class="form-control" name="age" placeholder="Enter Age"> <small id="ageHelp" class="form-text text-muted">Note that this has nothing to do with age restriction, CLASSY is available to everyone☺.</small> </div> <button type="submit" name="update_profile_details" class="btn btn-block btn_update">Update</button> </form> view function: views.py def profile_view(request,username): try: profileForm = … -
In a project in drf, I have endpoint "api/v1/invoice/#id/" so I want to give access to view to only author of this invoice
I have an endpoint /api/v1/invoice/#id/ I want that only author of this invoice should be able to view invoice Or staff should be able to view this invoice And superuser should be able to view, update, delete invoice I tried creating permissions.py file in my app: permissions.py from rest_framework.permissions import BasePermission class AuthorGetStaffGetAdminAll(BasePermission): edit_methods = ("PUT", "PATCH", "DELETE") def has_permission(self, request, view): if request.user.is_authenticated: return True return False def has_object_permission(self, request, view, obj): if request.user.is_superuser: return True if obj.author == request.user and request.method not in self.edit_methods: return True if request.user.is_staff and request.method not in self.edit_methods: return True return False -
Django: m2m's .count() and .order_by() with annotate values are very slow
The Video has about 300k data and there are about 2k Tags. If you do .annotate(count=Count('video')) and then do .order_by('-count') with that value as shown below, it will take It takes about 500ms. Also, since we are using DRF pagination, the .count() is being done behind the scenes, and the speed of the .count() is about 500ms. I have no idea what causes these things, even though I have researched them. How can I remedy this? # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) is_actress = models.BooleanField(default=False, db_index=True) created_at = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-is_actress"] def __str__(self): return self.name class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # serializers.py class TagSerializer(serializers.ModelSerializer): count = serializers.IntegerField() class Meta: model = Tag fields = ("pk", "name", "is_actress", "count") # views.py class TagListPagination(PageNumberPagination): page_size = 100 class TagListView(generics.ListAPIView): serializer_class = TagSerializer pagination_class = TagListPagination def get_queryset(self): return Tag.objects.annotate(count=Count("video")).order_by("-count") -
Django Custom SQL to Feed into a Model
I have done some Google search and find the following: Use custom query result as source for Django model (MySQL database) Also, I have found similar stuff in the Django document site. However, I am still struggling after doing some searching. Original Working Scripts cName = models.CharField(max_length=20, null=False) cSex = models.CharField(max_length=2, default='M', null=False) cBirthday = models.DateField(null=False) cEmail = models.EmailField(max_length=100, blank=True, default='') cPhone = models.CharField(max_length=50, blank=True, default='') cAddr = models.CharField(max_length=255,blank=True, default='') def __str__(self): return self.cName Then, I try to change the above to custom SQL. The following is not working. for p in student.objects.raw('SELECT cName, cSex, cBirthday, cEmail, cPhone, cAddr FROM TUTORIAL.STUDENTSAPP_STUDENT'): print(p.cName,p.cSex,p.cBirthday,p.cEmail,p.cPhone,p.cAddr ) it returns NameError: name 'student' is not defined Please suggest what is missing. Thanks in advance. -
How to create datefield in django models in the format (mm-dd-yyyy)
I am scraping the dates from different websites and it is in the format of mm-dd-yyyy ie. 10-28-2021 . Right now, I'm storing it as a string. In django models, I have created the field as: issued = models.CharField(max_length=16) This stores the data as string. But I want to convert into a datefield. When I tried, issued = models.DateField() I cannot store the data in this field. How to add the date in the particular format in the above field? -
How to create a relation to intermediate table using Model in Django?
Could anyone help me create this database using the ORM model in Django? I'm stuck at creating table CHITIETLOPHOC, DINHDANHKHUONMAT, DINHDANHTHUCONG ERD -
Get multipe images urls on Django RestFramework
I'm using Django RestFramework to create a simple eCommerce API where one product could have many images and I would like to get the URLs of all these images on a json field. For now, I got the first image url using "imagembicicleta_set.all.first.image.url" on the serializer, but I need all URLs list: { "count": 7, "next": null, "previous": null, "results": [ { "id": 1, "nome": "Specialized Roubaix", "marca__nome": "Specialized", "categoria": "Bicicletas de Estrada", "atividades": [ 1 ], "terrenos": [ "Asfalto" ], "preco": "16999.00", "ano": 1, "absolute_url": "/bicicletas/Specialized/specialized-roubaix-2020/", "img_url": "/media/images/bicicletas/roubaix1.jpeg" }, { "id": 2, "nome": "Specialized Roubaix Sport", "marca__nome": "Specialized", Following how is my setup: Models.py class Bicicleta(models.Model): id = models.AutoField(primary_key=True) nome = models.CharField(max_length=200, blank=False, null=False) slug = models.SlugField(unique=True) status = models.IntegerField(choices=STATUS_CHOICES, default=1, blank=False, null=False) descricao = RichTextField(blank=True, null=True) marca = models.ForeignKey(MarcaBicicleta, blank=True, null=True, on_delete=models.SET_NULL) ... class ImagemBicicleta (models.Model): bicicleta = models.ForeignKey(Bicicleta, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/bicicletas') Serializer.py class BicicletasSerializer(serializers.ModelSerializer): marca__nome = serializers.CharField(source='marca.nome') categoria = serializers.CharField(source='categoria.nome') terrenos = serializers.StringRelatedField(many=True) absolute_url = serializers.URLField(source='get_absolute_url', read_only=True) img_url = serializers.URLField(source='imagembicicleta_set.all.first.image.url', read_only=True) #I could get the first image using this class Meta: model = Bicicleta fields = ['id', 'nome', 'marca__nome', 'categoria', 'atividades', 'terrenos', 'preco', 'ano', 'absolute_url', 'img_url'] views.py class BicicletasView(generics.ListAPIView): serializer_class = BicicletasSerializer queryset = Bicicleta.objects.all() … -
Why my button doesn't return "POST" django?
When I click the button I always get the method GET instead of post: Any Ideas? Thanks! <body> <form action="/reset" type="POST"> {% csrf_token %} <h3>Random Word (attempt # {{request.session.counter}})</h3> <div> <h1>{{request.session.rword}}</h1> </div> <label for="title">Title</label> <input type="text" name="title" id=""> <button type="submit">Generate</button> </form>