Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration Re-order column
I've been confused,if there's any way how to order column when migrate in Django, In the first place In my case I don't have is_person in my models then eventually I want to add is_person after paid in my models like the example below in models.py, then the problem is even I correctly ordered the value in my models when migrate the is_person always goes to the last. Is there any trick how to add column after paid without deleting your whole database? Models.py class Person(models.Model): covid_id = models.CharField(max_length=50,blank=True, null=True) is_person = models.CharField(max_length=50,blank=True, null=True) // I want to add this paid_by = models.CharField(max_length=50,blank=True, null=True) date_receive = models.DateField(null=True, blank=True) remarks = models.CharField(max_length=1500,blank=True, null=True) eligible = models.CharField(max_length=50,blank=True, null=True) amount_paid = models.CharField(max_length=60,blank=True, null=True) -
Why does going to my profile, directs me to an Attribute Error?
Hello I am in a process of making a music website for a class project that's due in a few days, and the problem is that whenever I click on my channel's tab to go to my profile it always gives the error AttributeError at /musicbeats/c/abangurah 'NoneType' object has no attribute 'music'. and it's always directed in a line of code in my views class. Is there anything I am doing wrong, I would really appreciate a solution soon as my project is due in a couple of days. When trying to access my channel Where the error happens Error says it happens on line 138The model class where the line is refrencesing -
Profile Name link is not showing of user , which is commented on Post
show_more.html ( This is the template of the Post and see comments and add comments ) <hr> {% for comment in comments %} <div class="comment"> <p class="info"> {{ comment.created_at|naturaltime }} Commented by :- <a href="{% url 'mains:show_profile' comment.commented_by.id %}"></a> # I think the problem is in this line. BUT i've tried everything. {{ topic.post_owner }} </p> {{ comment.comment_body|linebreaks }} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} <h2>Add a new comment</h2> <form method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> views.py def detail_view(request,id): data = get_object_or_404(Post,pk=id) comments = data.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'mains/show_more.html', context ) models.py class Comment(models.Model): post_by = models.ForeignKey(Post, on_delete=models.CASCADE,related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE,default='') comment_body = models.TextField() Name of the User, who commented is showing but i want to redirect the profile of user ( commented_by ) who commented on post. I've tried everything but nothing works, Please help me in this. I will really appreciate your Help. -
Manage object with given ID or specific field with DRF
I have a model that contains two unique fields: class Instance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=64, unique=True) In views.py: class InstanceDetail(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated, ] queryset = Instance.objects.all() serializer_class = InstanceSerializer In urls.py: path('<uuid:pk>/', InstanceDetail.as_view()), Now, everything is working as expected and I can use the API with the instance ID's. But what if I want to do the same using name instead of id ? So the API would work providing the id or the name to the same url? Is there an easy way to do this without duplicating any code ? -
Saving form data to Database in react-js with Django Back-end
I need to Submit my Form data using after Validation to the database using react and Django API as back-end. Here is my Code const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i); const validateForm = (errors) => { let valid = true; Object.values(errors).forEach( (val) => val.length > 0 && (valid = false) ); return valid; } function myFunction() { alert("Please Check All the details Again !!"); } class ApplicationForm1 extends React.Component { constructor(props) { super(props); this.state = { step: 0, sex: '', permanent_address: '', permanent_city:'', permanent_state:'', temporary_city:'', temporary_state:'', temporary_address: '', adhar_card_number: '', current_standard: '', school_name: '', school_address: '', school_email: '', school_enrollment_no: '', admission_category: '', bank_name: '', bank_account_number: '', ifsc_code: '', last_year_of_passing:'', last_year_school_name: '', last_year_school_board: '', last_year_division: '', unit_test_year_of_passing:'', last_year_percentage: '', unit_test_school_name: '', unit_test_school_board: '', unit_test_school_division: '', unit_test_school_percentage: '', permanent_pin_code:'', temporary_pin_code:'', form1: false, formFillComplete: false, photo_url:'', is_loading:false, errors: { adhar_card_number:'', }, errormsg:'' } } handleImageChange = (e) => { this.setState({ photo: e.target.files[0] }); this.setState({ photo_url: URL.createObjectURL(e.target.files[0])}) } handleChange = (event) => { event.preventDefault(); console.log(event.target); let { name, value } = event.target; let error = this.state.errors; switch (name) { case 'permanent_pin_code': error.name = value.length !== 6 || isNaN(value) ? 'Pin must be 6 characters long And Numeric' : value break; case 'temporary_pin_code': error.name = value.length !== … -
How to Remove Duplicates Values after Merging Different Model Querysets in Django
how to remove duplicate after merge two different models like this import intertools events_list = list(itertools.chain(events_list, speakers_list)) I am getting duplicate values in Django REst serializer -
Django Problem with date format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
dateformated have the problem of format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] y tried so many things an i dont know what to do def export_csv(request, date1 , fechafinal): response = HttpResponse(content_type='text/csv') date1 = fechainicio fechafinal1 = fechafinal dateaux= str(date1)+' 00:00:00.000000' print(dateaux) dateformated= datetime.datetime.strptime(dateaux, "%Y-%m-%d %H:%M:%S.%f") print(dateformated) writer = csv.writer(response) writer.writerow(['id_medico','id_boxes','id_paciente','created_date']) for horasmedicas in Horas_medica.objects.filter(created_date='dateformated').order_by('id_medico').values_list('id_medico','id_boxes','id_paciente','created_date'): #writer.writerow(horasmedicas) #print(horasmedicas) #ID MEDICO if horasmedicas[0] != None: idmedico = horasmedicas[0] nombredoctor = Medico.objects.filter(pk=idmedico).values_list('nombre','apellidos') print(nombredoctor) #ID PACIENTE if horasmedicas[2] != None: print(horasmedicas[2]) response['Content-Disposition'] = 'attachment; filename="medicos.csv"' return response The data of dateformated is 2020-11-25 00:00:00 and in that moment trigger the error -
Django : indirect referencing dict objects
I want to create a table where the columns are products, and the rows represent actions. (the cell value will be the status of an action for a specific product). The products dictionary contains some products, and the action_data contains actions, with a status per product [{'Product': 'Car'}, {'Product': 'Bike'}, {'Product': 'Plane'}] [{'Action': 'design', 'Car': 'done', 'Bike': 'done', 'Plane': 'done'}, {'Action': 'build', 'Car': 'done', 'Bike': 'planned', 'Plane': 'canceled'}, {'Action': 'paint', 'Car': 'done', 'Bike': '???', 'Plane': '???'}, {'Action': 'cell', 'Car': '???', 'Bike': '???', 'Plane': '???'}] Displaying the header columns is easy, loop over the products entry. Displaying the actions in the first column is also simple. But how can one show the status per product? Loop over all products and use the product name as key in the act variable <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>Product Name</th> {% for prd in products %} <th>{{prd.Product}}</th> {% endfor %} </tr> </thead> <tbody> {% for act in action_data %} <tr> <td>{{act.Action}}</td> <!-- How to loop over products and tke the value to look into act --> {% for prd in products %} <td>indirect {{prd.Product}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> I hope someone can help me.... Rgds Luc -
Error('QuerySet' object has no attribute 'reserve_by') while loading Django site
from django import template from django.utils.safestring import mark_safe from core.models import Category register = template.Library() @register.simple_tag def categories(): items = Category.objects.filter(is_active=True).reserve_by('title') items_li = "" for i in items: items_li += """<li><a href="/category/{}">{}</a></li>""".format(i.slug, i.title) return mark_safe(items_li) @register.simple_tag def categories_mobile(): items = Category.objects.filter(is_active=True).reserve_by('title') items_li = "" for i in items: items_li += """<li class="item-menu-mobile"><a href="/category/{}">{}</a></li>""".format(i.slug, i.title) return mark_safe(items_li) @register.simple_tag def categories_li_a(): items = Category.objects.filter(is_active=True).reserve_by('title') items_li_a = "" for i in items: items_li_a += """<li class="p-t-4"><a href="/category/{}" class="s-text13">{}</a></li>""".format(i.slug, i.title) return mark_safe(items_li_a) @register.simple_tag def categories_div(): """ section banner :return: """ items = Category.objects.filter(is_active=True).reserve_by('title') items_div = "" item_div_list = "" for i, j in enumerate(items): if not i % 2: items_div += """<div class="block1 hov-img-zoom pos-relative m-b-30"><img src="/media/{}" alt="IMG-BENNER"><div class="block1-wrapbtn w-size2"><a href="/category/{}" class="flex-c-m size2 m-text2 bg3 hov1 trans-0-4">{}</a></div></div>""".format( j.image, j.slug, j.title) else: items_div_ = """<div class="block1 hov-img-zoom pos-relative m-b-30"><img src="/media/{}" alt="IMG-BENNER"><div class="block1-wrapbtn w-size2"><a href="/category/{}" class="flex-c-m size2 m-text2 bg3 hov1 trans-0-4">{}</a></div></div>""".format( j.image, j.slug, j.title) item_div_list += """<div class="col-sm-10 col-md-8 col-lg-4 m-l-r-auto">""" + items_div + items_div_ + """</div>""" items_div = "" return mark_safe(item_div_list) This is a category_template code to my django website when i run the django site i am getting this error('QuerySet' object has no attribute 'reserve_by'), I cant sort out what is the problem. So … -
Mask URL in Django + React webApp
I want to share a page with clients over mail which is something like this: https://blabla.com/docket/2443 but if I do so they can access all other pages by just changing the docket no. i.e. 2443 in this case. I tried to use tiny-url but it's of no use. Is there any way to mask the URL to solve the above problem? -
type object 'Review' has no attribute 'object'
class Review(models.Model): def __str__(self): return self.reviewText item = models.ForeignKey(Item, on_delete=models.CASCADE) reviewText = models.CharField(max_length=50) votes = models.CharField(max_length=100) This is my models.py file. And Bellow is my views.py file. def order(request, item_id): item = get_object_or_404(Item, pk=item_id) if request.method == "POST": username = None username = request.user.username userInfo = username + '/' + request.POST["nameNum"] userAddr = request.POST["address"] new_order = Review.object.create( reviewText = userInfo, votes = userAddr ) return HttpResponse("<script>alert('" + userInfo + '/ ' + userAddr + "');</script> 등록 완료") return render(request, 'order.html', {'item': item}) And when I run this part on my local server, type object 'Review' has no attribute 'object' << this errors occurs. How can I solve this problem? -
Accessing dynamically created django models
I'm creating a Django model/Postgres table dynamically, every time an entry is made in a Customer database. The idea is to create the model dynamically when saving an entry in the Customer class, like so: class Customer: ... def save(self, ...): ... CreateModel(customer_uuid, columns) AlterModelTable(customer_uuid, customer_uuid) And I would like to access this table somewhere else: data_set=data_set, data_type=<customer_uuid model>.DATETIME ).order_by('order')[0].name + '.desc' This creates a table called customer_uuid. Now I would like to access arbitrary customer_uuid tables later in a different view -- how can I do this? And yes, I realize Django cannot is not designed to handle this scenario, but I'm asking anyway. I suspect there is a way to leverage the migrations API so I don't have to write pages of SQL with psycopg2. Assume that putting all of the customer_uuid data in a single table is not an option. -
drf not creating profile without profile key
i'm trying to create userprofile while creating user. i'm getting this error: profile_data = validated_data.pop('profile') KeyError: 'profile' when i don't pass profile key while user creation but i have mentioned not required userprofileserialzer in customuserSerializers. i just want to save null if i don't pass profile key. models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_("last name"), max_length=50) email = models.EmailField(_('email address'), unique=True) mobile_number = PhoneNumberField() is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) user_type = models.IntegerField(_("user_type")) otp = models.CharField(_("otp"), max_length=10, default="0") is_varified = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'users'), (2, 'courier'), (3, 'admin'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserMananager() def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField( CustomUser, primary_key=True, related_name='userProfile', on_delete=models.CASCADE,) gender = models.CharField(max_length=10, blank=True, null=True) age = models.IntegerField(blank=True, null=True) image = models.ImageField( upload_to='api/user_profile/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __unicode__(self): return self.user.first_name serializers.py: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile read_only_fields = ('created_at', 'updated_at',) exclude = ('user',) class CustomUserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(required=False) password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = … -
Cannot Send Django Password Reset Email :: socket.gaierror: [Errno -2] Name or service not known
I am trying to handle password reset functionality in django but for some reason anytime i try to send the email to the user i get the following error gaierror at /password_reset/ [Errno -2] Name or service not known Settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'stmp.gmail.com' EMAIL_HOST_USER = '*******@gmail.com' EMAIL_HOST_PASSWORD = '*********' EMAIL_PORT = 587 urls.py path('password_reset/',PasswordResetView.as_view(template_name='passwordreset.html'),name='password_reset'), path('password_reset_done/',PasswordResetDoneView.as_view(template_name='passwordresetdone.html'),name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',PasswordResetConfirmView.as_view(template_name='passwordresetconfirm.html'),name='password_reset_confirm'), path('password_reset_complete/',PasswordResetCompleteView.as_view(template_name='passwordresetcomplete.html')) Also in my gmail account i have allow less secure apps turned on. Below Is A Full Traceback Internal Server Error: /password_reset/ Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/lib/python3/dist-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/lib/python3/dist-packages/django/contrib/auth/views.py", line 220, in dispatch return super().dispatch(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/usr/lib/python3/dist-packages/django/views/generic/edit.py", line 142, in post return self.form_valid(form) File "/usr/lib/python3/dist-packages/django/contrib/auth/views.py", line 233, in form_valid form.save(**opts) File "/usr/lib/python3/dist-packages/django/contrib/auth/forms.py", line 309, in save self.send_mail( File "/usr/lib/python3/dist-packages/django/contrib/auth/forms.py", line 259, in send_mail email_message.send() File "/usr/lib/python3/dist-packages/django/core/mail/message.py", line 291, in … -
How to set BASE_DIR for the Production Settings in Django 3.1.4?
This is my folder structure. I want to set BASE_DIR in production.py file. In older version of Django this is how we used to set the BASE_DIR: From: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) To: BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) But in latest version of Django we "Path" to set BASE_DIR From: BASE_DIR = Path(__file__).resolve().parent.parent To: ??? So how to set BASE_DIR for above folder structure -
Python Django deployment to Heroku H10 error
I am trying to deploy API made in Python to to Heroku. I am getting this errors and I do not know how to fix them. at=error code=H10 desc="App crashed" method=GET path="/" host=pythonapisfind.herokuapp.com request_id=a0e39942-e0d5-4159-87fa-b06e997122b6 fwd="217.97.50.218" dyno= connect= service= status=503 bytes= protocol=https 2020-12-09T09:06:17.055412+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=pythonapisfind.herokuapp.com request_id=b76f9c8c-a187-4516-9338-f01bca9eb726 fwd="217.97.50.218" dyno= connect= service= status=503 bytes= protocol=https web: gunicorn offers.wsgi --log-file - asgiref==3.3.1 certifi==2020.12.5 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 Django==3.1.4 django-cors-headers==3.5.0 django-environ==0.4.5 djangorestframework==3.12.2 drf-yasg==1.20.0 idna==2.10 inflection==0.5.1 itypes==1.2.0 Jinja2==2.11.2 MarkupSafe==1.1.1 packaging==20.7 postgres==3.0.0 psycopg2-binary==2.8.6 psycopg2-pool==1.1 pyparsing==2.4.7 pytz==2020.4 requests==2.25.0 ruamel.yaml==0.16.12 ruamel.yaml.clib==0.2.2 sqlparse==0.4.1 uritemplate==3.0.1 urllib3==1.26.2 gunicorn ==20.0.4 -
how to update the value of a variable in django template
I have a variable called status in my models.py as following: class message(models.Model): class Choices_status(models.TextChoices): unread = 'Unread', "Unread" processing = 'Processing', "Processing" obsolete = 'Obsolete', "Obsolete" status = models.CharField(max_length=25, choices=Choices_status.choices, default=Choices_status.unread, blank=True) It indicates the status of a message. I want to change the value of it to other choices of the Choices_status. i.e. inside of a template that I am showing a list of messages, I want to change this variable's value to other choices if a message is selected and showed on a new page. All I could find was working with {% with %} tag that is not suitable for my case. Any ideas? -
Object is not being created
I am trying to save two forms simultaneously and enter the data in another table. if request.method == "POST": u_form = UserForm(request.POST) r_form = RestaurantForm(request.POST, request.FILES) if u_form.is_valid() and r_form.is_valid(): user = u_form.save() manager = Manager.objects.create(user=user) manager.save() r_form.save() messages.success(request, f'Registration complete! You may login!') return redirect('../login') else: messages.info(request, 'Invalid.') return redirect('staff_registration') else: u_form = UserForm(request.POST) r_form = RestaurantForm(request.POST, request.FILES) return render(request, "insert_restaurant.html", {'u_form': u_form, 'r_form': r_form}) My manager class is : class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) When I fill-up the form, and submit, there is no error, my user is created successfully. But, in my 'Restaurant' and 'Manager' table, no object is created. Please help me in this. I need immediate help. -
How to style a Django editable form in bootstrap
I have a form that returns the following fields: fields = ['username', 'first_name', 'last_name', 'email'] So in my profile/edit view(I mean an HTML page) I have this code: <div class="col-xl-9"> <div class="widget has-shadow" style="height:100%"> <div class="widget-header bordered no-actions d-flex align-items-center"> <h4>edit profile</h4> </div> <div class="widget-body"> <form method="POST"> {% csrf_token %} <div class="form-group row d-flex align-items-center mb-5"> <label class="col-lg-2 form-control-label d-flex justify-content-lg-end">username</label> <div class="col-lg-6"> <input type="text" name="username" class="form-control" placeholder="{{update_profile_form.username}}"> </div> </div> <div class="em-separator separator-dashed"></div> <div class="text-right"> <button class="btn btn-gradient-01" type="submit">Save</button> <button class="btn btn-shadow" type="reset">Cancel</button> </div> </form> </div> </div> </div> And you see I want to show username field from update_profile_form form. But when I reload the page I have an extra "> below of my username field. I don't know how to get rid of these characters in my page. -
Error in Python's Django run-server command?
Why I am getting the following error please solve.2nd Image of problem,,1st image of problem Thanks for helping. -
Django Channel Update with Sending Messages
I have been trying to update the chat room whenever a specific model gets updated. The websocket connections work well and the Django signals work well also. However, when I try to send a specific message to the group, it would not work. I made sure the function (in this case, "schedule_update") gets activated by putting a debugger and sure enough, it gets activated. Below is the channels function in question: class GroupShareDataApi(WebsocketConsumer): # permission_classes = (IsAuthenticated,) def connect(self): self.channel_id = self.scope['url_route']['kwargs']['channelId'] self.room_group_name = self.channel_id # Join channel group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_id ) print(self.room_group_name) self.accept() return self.send(json.dumps({"message": "CONNECTED!"})) . . . . . . @receiver(post_save, sender=VacationData) def schedule_update(instance, sender, **kwargs): group_name = "5fcf479d889fa60001000201" channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( group_name, { "type": "send_message", "text": "what's up?" }, ) And this is the Web Socket Testing... which shows nothing other than the message it shows when connected: By the way, the channel_id (or channelId) is "5fcf479d889fa60001000201". Since the group name is also the channel id, there is no way I mispointed the group. How do I properly send messages and update the group chat? -
how can i display an image in pdf using xhtml2pdf?
i have tried the Code for link callback and to render the pdf i used my function print_issue_vouchers. i am using xhtml2pdf to render the pdf. def print_issue_vouchers(request): data = {} template = get_template("print_issue_vouchers.html") data_p = template.render(data) response = BytesIO() pdfPage = pisa.pisaDocument(BytesIO(data_p.encode("UTF-8")), response,link_callback=link_callback) if not pdfPage.err: return HttpResponse(response.getvalue(), content_type="application/pdf") else: return HttpResponse("Error") -
AssertionError in Postman
Am very new to Django and rest, trying to learn it. I want to perform get and post operations in the Postman. Unfortunately, I get an assertion error. Can someone help me? Following is the error and code. Thanks in advance. http://localhost:8000/api/lead/ Error I am getting is: AssertionError at /api/lead/ 'LeadViewSet' should either include a serializer_class attribute, or override the get_serializer_class() method. Request Method: GET Request URL: http://127.0.0.1:8000/api/lead/ Django Version: 3.1.4 Exception Type: AssertionError Exception Value: 'LeadViewSet' should either include a serializer_class attribute, or override the get_serializer_class() method. Here is the code. api.py from lead.models import Lead from rest_framework import viewsets, permissions from .serializers import LeadSerializer #Lead Viewset class LeadViewSet(viewsets.ModelViewSet): queryset = Lead.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = LeadSerializer serializers.py from rest_framework import serializers from lead.models import Lead #Lead Serializer class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' urls.py from rest_framework import routers from .api import LeadViewSet router = routers.DefaultRouter() router.register('api/lead', LeadViewSet, 'lead') urlpatterns = router.urls -
I'm getting multiple buttons instead of 1
<h4>Posts By You</h4> {% for i in posts %} {% for j in i %} <pre id="posts">{{ j }}</pre> {% endfor %} <div id="delBtnDiv"> {% for l in postID %} {% for k in l %} <button class="btn btn-primary btn-sm" id="delBtn">Delete Post {{ k }}</button> {% endfor %} {% endfor %} </div> <hr> {% endfor %} sql = "SELECT postID FROM posts WHERE relUser=%s ORDER BY postID DESC" vals = (li) cur.execute(sql, vals) idResults = cur.fetchall() id = [] id.clear() id.append(idResults) for idsIndex in range(len(id)): for result in results: for index in range(len(results)): params = {'name': log_userName, 'noOfPosts': len(result), 'posts': results[index], 'followers': 36, 'pass': log_userPassword, 'postID': id[idsIndex]} return render(request, 'myAccount.html', params) The first code snippet is HTML and the second is Django As seen in the picture I'm getting multiple delete buttons instead of only one, I've used for loops -
Get current id on model save Django
I my Django app contains a model for saving pictures, I would like Django to create a folder for the pictures based on the id of the record. I am trying to set the upload_to attribute to /bilder/1/ for the first picture i upload and to /bilder/2/ for the second and so on. I have tried multiple methods but cant get it to work. my model: class bilder(models.Model): dato_opplasting = models.DateField(default=None, blank=True, null=True) dato_tatt = models.DateField(default=None, blank=True, null=True) tittel = models.CharField(max_length=100, default=None, blank=True, null=True) photo = models.ImageField(upload_to='bilder/%s/' % (id), max_length=255, blank=True, null=True) created_on = models.DateTimeField(default=datetime.datetime.now)