Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
An Unexpected Error while trying to delete data
I am doing CRUD using serializers and foreign key as tasked,the problem is that when I am trying to delete a data,an error which is completely unexpected has come. this error should not be coming as I am not missing the id in the below functions and html code NOTE : I am doing soft delete hence the parameter 'isactive' is there delete function def delete(request,id): deleteclothes = Products.objects.all(id=id) delclothes = {} delclothes['isactive']=False form = POLLSerializer(deleteclothes,data=delclothes) if form.is_valid(): print("error of form when valid:",form.errors) form.save() return redirect('polls:show') else: print("error of form when not valid:",form.errors) return redirect('polls:show') html code of product_list <td> <a href="/delete/{{result.id}}/" onclick="return confirm('Are You Sure you want to delete?')"> <button class="btn btn-danger"> Delete </button> </a> </td> where am I going wrong in the code? -
Updating id of models without deleting objects in it in Django
I am studiying the bases of django by watching courses of "Tech with Tim" https://www.youtube.com/watch?v=sm1mokevMWk&t=2912s I deleted objects in models and my id always incremented instead of making reset. How can I reset my id? enter image description here from typing import Text from django.db import models class ToDoList (models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete = models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text -
Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
get the following error when adding a go back link in my comment_delete.html: Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] Everything works without the go back link (deleting a comment). Would like to know what I'm doing wrong in my comment_delete (href="{% url 'post_detail' post.slug %}") Go back Thank you :) models.py: class Post(models.Model): title = models.CharField( max_length=200, unique=True, default=str(f'Fishing {datetime.today()}')[:24] ) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts' ) featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) likes = models.ManyToManyField( User, related_name='blogpost_like', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.title) return super().save(*args, **kwargs) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_comments') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=True) class Meta: ordering = ['created_on'] def __str__(self): return f'Comment {self.body} by {self.author}' views.py class CommentDelete(LoginRequiredMixin, SuccessMessageMixin, UserPassesTestMixin, generic.DeleteView): model = Comment template_name = 'comment_delete.html' success_message = "Comment Deleted" def get_success_url(self): slug = self.kwargs['slug'] return reverse_lazy('post_detail', kwargs={'slug': slug}) def delete(self, request, *args, **kwargs): messages.success(self.request, self.success_message) return super(CommentDelete, … -
Where shall I put sub-domain routing? Front-end (React) or Back-end (Django+zappa) in a Serverless multi-tenant application?
So, we have a multi-tenant application in which sub-domain routing is handled by backend (django+zappa) and now we're moving to Serverless for back-end. Hence, we need to seperate our React and Django code. So, my question is where shall I put the subdomain routing on react side or on django side. -
Where should I store the Django media files so that I can have the same functionality as the Lynda site?
I built a Django website that works like Lynda's tutorial. Now my question is, where should I save my video files so that they are only accessible to users who are allowed to download them? Does saving files on object space give me such a feature? Or where should I live my website to have such a feature? Or if I save on vps servers where my Django app is live, will it affect the speed of my app? Please guide. -
Accessing reverse relation in django, Django restframework
I want to get all the students/learners that are enrolled in a course, This is my course model, this is my courseenrollement model -
How do I change dynamically one form value based-on other form value on Django?
I am trying set dynamically a value from form value A to the form value B (his default) Value on form A: A = models.IntegerField(XXX) Value on form B: ### if A is 1900, B default value is years ago B = models.IntegerField(XXX, default=value_from_A_+_1000) what is the best way to manage it? Thank you -
I am trying to create a review form. but I am having difficulties with the submit_review form. Many errors due to Service ID
I believe my issue is stemming from the views.py file. I dont believe I have it correctly laid out. The idea is for the user to review a service that has been purchased only. The link to the review form is in the purchase order history view so when they click on review service that service description would automatically transfer to the submit_review form. Model: class ReviewRating(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, null=True, blank=True) review = models.TextField(max_length=500, null=True, blank=True) rating = models.FloatField() status = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.subject I believe the problem to be here in the view Views: def submit_review(request, service_id): service = get_object_or_404(Service, pk=service_id) if request.method == 'POST': form = ReviewRatingForm(request.POST) if form.is_valid(): review_form = form.save(commit=False) review_form.service = service_id form.save() messages.success(request, 'Review submitted succeffully!') return redirect(reverse('useraccount')) else: messages.error(request, 'Failed to submit review. Please ensure the form is valid.') else: form = ReviewRatingForm() template = 'useraccount/submit_review.html' context = { 'form': form, 'service': service, } return render(request, template, context) URLs: from django.urls import path from . import views urlpatterns = [ path('', views.useraccount, name='useraccount'), path('purchase_history/<order_number>', views.purchase_history, name='purchase_history'), path('submit_review/<service_id>', views.submit_review, name='submit_review'), ] template form: <form class="reviews-form" method="POST" action=""> … -
Make a relative url go one step back
I have a url: http://test.com/test1/test2/ Is there a way to make a relative url from test2 to test1? Like just one step back? Without Javascript. The /test1/ part may change, that's why I need to go from /test/2 just one step back to /test1/ (or changed url) -
Not able to save and retain the selected option in dropdown
I am performing CRUD using foreign keys and serializers,and I am having difficulty in doing the update operation. the problem is that I am unable to retain the selected option in dropdown. for example in categories column,I have selected 'Bridal wear' and then when I try to edit it,in the edit page the value saved appears as '9-6wear' instead as shown below in below images the selected categories is 9-6wear below are the models and serializers class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class ColorsSerializer(serializers.ModelSerializer): class Meta: model = Colors fields = "__all__" class POLLSerializer(serializers.ModelSerializer): # categories = serializers.StringRelatedField(many=False) # sub_categories = serializers.StringRelatedField(many=False) # color = serializers.StringRelatedField(many=False) # size = serializers.StringRelatedField(many=False) class Meta: model = Products fields = "__all__" class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = "__all__" class SUBCategoriesSerializer(serializers.ModelSerializer): class Meta: model = SUBCategories fields = "__all__" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=20) category_description … -
404 (Not Found) error on ajax post request
Good morning Sirs, this code is meant to get data from a form and request a Django view to create an account in a database and respond with an instant of the account created, back to the template.html which made the previous request. The form is created using django-crispy-forms form.html -
Set personalized body for sending mail in django
I want to send a message with personalized SMTP mail-in Django. Where I want to send Name, email, and contact information with the dynamic text input value. Here is my code if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') contact = request.POST.get('contactnum') textmess = request.POST.get('textarea') allinfo = "Name : " + name, "E-Mail" + email, "Contact:" + contact, textmess print (allinfo) subject = 'From MBS Project(Contact Us)' email_from = settings.EMAIL_HOST_USER mailto:recipents_list=['abc@gmail.com'] if allinfo: sendMail = send_mail(subject, allinfo, email_from, recipents_list) messages.success(request, 'Message Send Successfully...') return HttpResponseRedirect('contactus', {'sendMail': sendMail}) else: messages.error(request, 'error during send!!, Please Try Again..') return render(request, 'contactus.html', {}) else: return render(request, 'contactus.html', {}) -
Display popup information beside map in a table when I click a marker with leaflet/django
I am using Leaflet JS and Django to create a map website. I have markers on the map showing correctly and I'm trying to display a table in a seperate div beside the map displaying information that would be in the popup. I am also using a Django REST api to store marker data such as lat & long, names etc. My api returns this: [ { "id": 2, "cube": "Industrial Cube North", "cubeurl": "https://dcwppntise010.edc.nam.gm.com/admin/login.jsp", "hostname": "acrptisepsn01", "domain": "nam", "personas": "Policy Service", "ip": "10.36.139.120", "structurename": "Rochester COMP", "streetaddress": "1000 Lexington Ave", "latitude": 43.18226, "longitude": -77.65599 }, I fetch data from my API like: {% for item in data %} var marker = L.marker([{{item.latitude}},{{item.longitude}}]).bindPopup("<strong>{{item.hostname}}</strong><br/>{{item.personas}}").addTo(map).on('popupopen', function (e) { console.log(e.popup.getContent()) });; {% endfor %} It logs the content in the console but don't know how to dynamically change info in the table for each marker (they have different info & locations) I have seen examples such as: http://www.gistechsolutions.com/leaflet/DEMO/baseball/BaseballPanel.html That uses GeoJson and I'm not sure how to apply the same logic to my setup. Thank you! I need a table like this: -
Django rest framework sql raw query from another host
I have two database with different connection, 1st is the default database and 2nd is for data only. 1st DB: Host:0.0.0.0 port:5822 dbname:DBone user:postgres password:user:postgres 2nd DB: Host:0.0.0.0 port:5842 dbname:DBtwo user:postgres password:user:postgres 1st database the main database, I want to query data from 2nd database under views.py (request) Im using Django RestFrameworks now. I want to raw query from another host connection, how to do that? @api_view(['GET']) def get_data(request): data = DBtwo.objects.raw(SELECT current from DBtwo WHERE name ='Test' AND gender ='M' AND age ='20') -
serve static and media files in django when debug=False
I want to publish my django project but when is change my settings.py "debug = False" static files are not loaded ! here is my settings.py MEDIA_URL = '/media_files/' STATIC_URL = '/static_files/' MEDIA_ROOT = '/home/domain/public_html/static_cdn/media_root' STATIC_ROOT = '/home/domain/public_html/static_cdn/static_root' also I used "python manage.py collectstatic" command and it created folder for example when I put "https://domain/static_cdn/static_root/admin/css/base.css" I can see the files without error -
How shall I make this form automatically identify the user who is logged in as author
class ArticleCreateView(CreateView): model=Post form_class=PostForm template_name='add_post.html' from operator import mod from turtle import title from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model=Post fields=['title','body','author','category'] -
return qs._result_cache[0] IndexError: list index out of range [12/Jul/2022 14:43:28] "GET /shop/products/15 HTTP/1.1" 500 68001
return qs._result_cache[0] IndexError: list index out of range [12/Jul/2022 14:43:28] "GET /shop/products/15 HTTP/1.1" 500 68001 -
Why two ViewSets have identical url in DRF?
Why two different viewsets have identical url? How can I change it? router = routers.DefaultRouter() router.register(r'general-worker', GeneralWorkerViewSet) router.register(r'full-info-worker', FullInfoWorkerViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(router.urls)), path('api/v1/drf-auth/', include('rest_framework.urls')), ] json from http://127.0.0.1:8000/api/v1/ { "general-worker": "http://127.0.0.1:8000/api/v1/full-info-worker/", "full-info-worker": "http://127.0.0.1:8000/api/v1/full-info-worker/" } -
Update Database Column and Tables with Django
I've encounter into a situation where i try to update mysql database using django. here is the schema of it: the original schema class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) class Groups(models.Model): GroupId = models.AutoField(primary_key=True) GroupName = models.CharField(max_length=100) class Employees(models.Model): EmployeeID = models.AutoField(primary_key=True) EmployeeName = models.CharField(max_length=100) Departments = models.CharField(max_length=100) Groups = models.CharField(max_length=100) DateOfRecruitment = models.DateField() Position = models.CharField(max_length=100) PhotoFileName = models.CharField(max_length=100) the new schema class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) class Groups(models.Model): GroupId = models.AutoField(primary_key=True) GroupName = models.CharField(max_length=100) class Positions(models.Model): PositionId = models.AutoField(primary_key=True) PositionName = models.CharField(max_length=100) class Employees(models.Model): EmployeeID = models.AutoField(primary_key=True) EmployeeName = models.CharField(max_length=100) Departments = models.CharField(max_length=100) Groups = models.CharField(max_length=100) DateOfRecruitment = models.DateField() DateOfResignation = models.DateField() Position = models.CharField(max_length=100) Blacklist = models.BooleanField() BlacklistDate = models.DateField() PhotoFileName = models.CharField(max_length=100) I've tried to use the following command python manage.py makemigrations someapp python manage.py migrate However it doesn't update within the mysql system itself. The only solution that i came out of is dropping the entire database and make the migration again. I hope that there is a better solution than my method as i couldn't just use the same method for data migration or another table update. Thank you. -
How to get difference between two dates as a integer inside Django templates
I have list of two dates: ['2022-07-11', '2022-07-19'] and have to calculate difference between them as a int value: 8 inside Django templates. I tried with: {% with value1=date.value.1 value0=date.value.0 %} <h3>{{ value1-value0 }}</h3> {% endwith %} Error: Could not parse the remainder: '-value0' from 'value1-value0' I also tried with timesince and timeuntilstill no result Any way to get just get difference between as a int -
Every log file capturing all the apps logs, irrespective of which app is running
I was trying to create a separate log file for every app . But my every log file is capturing all the log data irrespective of which app is running. I tried like below, In my setting.py file i have the below code INSTALLED_APPS = [ 'src.admin_management', 'src.change_management', ] LOG_DIR = BASE_DIR + '/application_logs/' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.NullHandler', }, 'src.admin_management': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + "/admin_management.log", 'maxBytes': 1024 * 1024 * 10, #Max 10MB 'backupCount': 3, 'formatter': 'standard', }, 'src.change_management': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + "/change_management.log", 'maxBytes': 1024 * 1024 * 10, #Max 10MB 'backupCount': 3, 'formatter': 'standard', }, # 'console':{ # 'level':'INFO', # 'class':'logging.StreamHandler', # 'formatter': 'standard' # }, }, 'loggers': { 'django': { # 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { # 'handlers': ['console'], 'level': 'DEBUG' if DEBUG else 'WARNING', 'propagate': False, }, '': { 'handlers': [ 'src.admin_management', 'src.change_management', ], 'level': 'DEBUG', }, } } I have the below code in my views.py file in the admin_management app import … -
Setting django to server media files from google cloud
I'm trying to deploy my project in Heroku but the media files (images) are deleted , so someone told me that i need to use a service called "Google cloud", my question is, how to configure my prject to use that service. Can somebody help me? -
"(1452, Cannot add a foreign key constraint fails( CONSTRAINT `FK_STG_TRN_DATA_LOCATION` FOREIGN KEY (`LOCATION`) REFERENCES `location` (`LOCATION`))
@csrf_exempt def stg_trn(request): if request.method == 'POST': try: json_object = json.loads(request.body) current_user = request.user D_keys=[] data_list=[] l_counter=0 for row in json_object: for key in row: if row[key]=="" or row[key]=="NULL": D_keys.append(key) for key in D_keys: row.pop(key) D_keys.clear() l_counter=l_counter+1 d= str(datetime.now()).replace('-',"").replace(':',"").replace(' ',"").replace('.',"") unique_id=d+str(l_counter)+'STG' row["TRAN_SEQ_NO"]=unique_id row["PROCESS_IND"]='N' row["CREATE_DATETIME"]=str(datetime.now()) row["CREATE_ID"]=str(current_user) row["REV_NO"]=1 json_object=json_object[0] mycursor = connection.cursor() #Comparing and assign values to the Foreign key values based on input parameters. res1=mycursor.execute("SELECT LOCATION FROM LOCATION WHERE LOCATION="+'"'+(str(json_object["LOCATION"]))+'"') res1=mycursor.fetchall()[0][0] row["LOCATION"]=res1 print(res1) res2=mycursor.execute("SELECT ITEM FROM ITEM_DTL WHERE ITEM="+'"'+(str(json_object["ITEM"]))+'"') res2=mycursor.fetchall()[0][0] row["ITEM"]=res2 res3=mycursor.execute("SELECT CURRENCY FROM CURRENCY WHERE CURRENCY="+'"'+(str(json_object["CURRENCY"]))+'"') res3=mycursor.fetchall()[0][0] row["CURRENCY"]=res3 cols=",".join(map(str, row.keys())) v_list=[] val=') VALUES(' for v in row.values(): if v== None: val=val+'NULL,' else: v_list.append(v) val=val+'%s,' val=val[:-1]+')' query="insert into stg_trn_data(" +cols + val mycursor.execute(query,v_list) connection.commit() return JsonResponse({"status": 201, "message": "Data Inserted"}) -
Get field is_active from model User
I have the model User with one of the fields is_active: class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() is_active = models.BooleanField( _('active'), default=True, ) And I have the model Player with one of the fields user: class Player(models.Model): user = models.OneToOneField( 'users.User', null=True, on_delete=models.PROTECT, related_name='player', ) How can i get field is_active in PlayerAdmin model? user__is_active doesn't work -
TypeError: unsupported operand type(s) for -: 'IntegerField' and 'int'
I am struggling trying to sum/rest/multiply numbers on forms.py when they are different type, how to manage it? Thanks in advance MODELS.py myyear= models.IntegerField( db_column='XXX', choices=mychoices, default=str(year-1) ) period_from = dateitstart(myyear) UTILITIES.PY def dateitstart(myyear): return datetime.date(myyear -1, 10, 1)