Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Thansmit article to tags rendered as string
Django 3.2.6 View: class Single(DetailView): template_name = _get_template_name() model = Article Mixin: class TextMixin(models.Model): txt = models.TextField(blank=False, null=False, default="", verbose_name=gettext_lazy(f"Text ({OmnibusNames.RENDER.value})"), ) class Meta: abstract = True Model: class Article(SlugMixin, ... TextMixin, Templatetag: @register.inclusion_tag('widgets/toc.html', takes_context=True) def toc(context)->str: """ Usage example: {% toc %} """ i = 0 Now I take this txt and render: def render_template_from_string(a_string: str, a_context: dict = {}) -> SafeString: template = Template(a_string) context = Context(a_context) result = template.render(context) return mark_safe(result) In practice it looks like this: In other words I want users to be able to use template tags in articles. The problem is that I can't catch which article these widgets refer to. Could you help template tags get to know inside which article they are rendered. Transmit the article to the context or something. -
When I change the HTML website to Django redirects app, I how do I do a 301 redirection automatically for diverting traffic from an old to a new link?
Django redirects app I added this in my installed app section 'django.contrib.redirects', MIDDLEWARE = [ 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ] I added the sites in the admin panel domain name : http://127.0.0.1:8000/ I added redirects in the admin panel. old link : redirect from : /index/ & new link : redirect to: /index.html I didn't mention this URL link in my urls.py like below path('index.html/', views.index, name='index'), I check the invalid URL as new URL. I run the local server. its not working -
how to resolve django make migrations error
I get the following error each time I'm running "python manage.py makemigrations" This error started when I had issues with git so I had to revert and overwrite some commits. Someone should help please, because its not allowing me migrate new module, although the server is running currently. 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/ulaitor/miniconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ulaitor/miniconda3/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/ulaitor/miniconda3/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 141, in handle loader.project_state(), File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 324, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/db/migrations/graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/db/migrations/migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/ulaitor/miniconda3/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 172, in state_forwards delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' -
how will i show multiple apps urlpatterns in swagger-ui django
path('auth/', include('auth_api.urls')), path('activity/', include('todo_api.urls')), path('openapi', get_schema_view( title="", description="API for all things …", version="1.0.0" ), name='openapi-schema'), # Route TemplateView to serve Swagger UI template. # * Provide `extra_context` with view name of `SchemaView`. path('', TemplateView.as_view( template_name='swag.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui'), ] swagger ui is only showing the auth_api apps url not the todo_api! how can i show them too in ui! -
How to filter models in django database
Hello i created movies website , this is my models.py CATEGORY_CHOICES = ( ("A","ACTION"), ("D","DRAMA"), ("C","COMEDY"), ("R",'ROMANCE'), class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=1) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=2) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) and this is my views.py def home(request): user = request.user Movies_obj = models.Movie.objects.all().order_by('-id')[:10] return render(request,'index.html',{'user':user,'movies':Movies_obj}) in views.py i order last 10 movies , now i want to show only this movies which is DRAMA or Comedy how to filter it ? -
How would I sort data accordence month and year using django queryset and serializer
I am new to Django serializers. I have model Order and I want to have some kind of response that is shown below in JSON format from Order Model using serializer (Django REST framework). Example: Order Model class Order(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE) buyer = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Required Response { "order_by_month_year":[ { "month": "January 2021", "order_list": [ { "id":12, }, { "id":23 }, { "id":34 } ] }, { "month": "Febuary 2021", "order_list": [ { "id":123 }, { "id":233 }, { "id":334 } ] } ] } -
How to loop the query in djagno?
In my views.py file i am saving the form date having different last digit so how to loop them if request.method == "POST" : staff_id = request.POST.get('staff_id1', None) attendances = request.POST.get('attendance1', None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() staff_id = request.POST.get('staff_id2', None) attendances = request.POST.get('attendance2', None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() staff_id = request.POST.get('staff_id3', None) attendances = request.POST.get('attendance3', None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() you can see that the last digit of staff_id and attendance is different and rest is similar. I want to loop it as per date in table. -
Import a local json file and print it's values using views and templates in Django
I have downloaded a .json file and I want to show it's values in a table using Django view and templates. How should I do it? N.B: I do not want to populate any model(table). And one more thing is that pycharm and my laptop gets hung since the json file is large. -
Django - Query for Posts belonging to Goals by Categories?
So I have some models where each Category is comprised of Goals. For example, "Health" is a category and "lose 10lbs by my wedding" is a goal in that category. Then I have posts for that goal. So like post 1 could be about day 1 of the weight loss journey and so on and so forth. I need to be able to query for all posts by category and the response should be a list of dict where it contains: the post body, goal title, create date. How can I query for this quickly? The current method I have I think is less than ideal. I was going to query goals by category than query posts by goal, but then I'd had to iteratively append the goal description to every post then return it. This could be very slow. I think ideally I'd want to filter categories by the category I want then join on goals with that type then join on posts and return the relevant columns. class Goal(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_id") end_date = models.DateField( 'End date', null=True, default=None, blank=True) category = models.ForeignKey(GoalCategory, on_delete=models.CASCADE) description = models.CharField( max_length=255, validators=[MinLengthValidator(5)]) class Post(AbstractBaseModel): creator_id = models.ForeignKey( … -
cannot access file from its url in views django
I cannot access file from its URL in views Django but I can access it from templates in html files I tried a lot of things but it did not work for me code in the views.py error that appears -
Django ckeditor thumbnails are not generating after change the actual image
I'm working on a project using Python(3.9), Django(3) which is deployed on Heroku. My site is images intensive, so I decided to use django-imagekit to generate thumbnail for home page (because we are loading few articles on home page and each article has an image). When I setup imagekit it generate all the thumbnails and load correctly, then I make a change in the site and push new changes to Heroku, after that imagekit thumbnails stop working. I tried to re-upload images but it still doesn't work, even I tried removing the media/CACHE directory but it still not generating thumbnail when update an image. Here's what I tried: From settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'imagekit', 'django.contrib.sites', 'crispy_forms', 'avinit', 'ckeditor', 'ckeditor_uploader', 'storages', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ] MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' From models.py: class PostModel(models.Model): photo = ProcessedImageField(upload_to='blog_images', format='JPEG', options={'quality': 70}) # in your template thumbnails, use this image instead featured_thumbnail = ImageSpecField(source='photo', processors=[ResizeToFit(160, 160)], format='JPEG', options={'quality': 70}) -
Efficiently update same field multiple objects django
I have a model and I want to send increment a field value by 1 for multiple records. I searched for efficient update answers like Efficient way to update multiple fields of Django model object but they assume I have the value whereas I want to increment so the value might be different for different records. My Model looks something like this: class Signal(models.Model): name = models.CharField(max_length=80) version = models.IntegerField() In my view, I want to send a list of names and then update all of their versions by 1. My current method is to look through the names, create objects, update versions, and save manually so like this: signals = Signal.objects.filter(name__in=signal_names) for signal in signals: signal.pk=None signal.version = signal.version+1 signal.save() This results in way too many queries and is very slow because I'll be sending 100s of names at once. Is there a better way to do this? NOTE: This might seem similar to bulk update questions but in this case I want to increment 1 so I dont have the value to update with. That was my struggle with existing answers. Example: signal table name | version n1 | 1 n2 | 2 I send ["n1", "n2"] in … -
post_delete gets a different path than pre_save
I have a post_delete function that deletes an image after a user is deleted @receiver(pre_save, sender=User) def delete_file(sender, instance, *args, **kwargs): """ Deletes image files on `post_delete` """ if instance.image: path = instance.image.path if os.path.isfile(path): os.remove(path) When I change pre_save to post_delete It gets the right path which is /media/images/image.png but in pre_save it gets /media/image.png which is incorrect. -
How to copy android partition and recover deleted data?
I used this command to copy entire internal storage partition sda as sda.img (24.6 GB). adb pull /dev/block/sda sda.img Then I used OSFMount on Windows and mounted as read-only drive, but it shows Location is not available E:\ is not accessible. The parameter is incorrect. I opened it with 7-Zip and Winrar, but it shows that it can't be opened as archive. These are the partitions located on my phone, I assumed sda is internal storage and the size of the img is around the same size of what I see in file managers (23.84 internal, 3.94 GB root). 0 lrwxrwxrwx 1 root root 36 1970-01-06 10:24 bootdevice -> /dev/block/platform/soc/624000.ufshc 0 drwxr-xr-x 2 root root 1420 1970-01-06 10:24 by-name 0 brw------- 1 root root 7, 0 1970-01-06 10:24 loop0 0 brw------- 1 root root 7, 8 1970-01-06 10:24 loop1 0 brw------- 1 root root 7, 16 1970-01-06 10:24 loop2 0 brw------- 1 root root 7, 24 1970-01-06 10:24 loop3 0 brw------- 1 root root 7, 32 1970-01-06 10:24 loop4 0 brw------- 1 root root 7, 40 1970-01-06 10:24 loop5 0 brw------- 1 root root 7, 48 1970-01-06 10:24 loop6 0 brw------- 1 root root 7, 56 1970-01-06 10:24 loop7 0 … -
How to make filter Using multiple data value using Django Rest Framework and Angular 11
I am facing problem with searching and filtering in my project. I am using Django rest framework and PostgreSQL for backend and Angular 11 for frontend. my model class is class Project(models.Model): title = models.CharField(max_length=200) domain = models.ManyToManyField(Domain) environment = models.ManyToManyField(Environment) tools_and_technology = models.ManyToManyField(ToolsAndTechnology) user = models.ManyToManyField(User) photo = models.ImageField(blank=True, null=True,upload_to=uploadPath) def __str__(self): return self.title if a user select tools and technology for a project like C# or Java the result should be filtured and display. A user can filter by tools and technology, domain, environment. Each field can be multiple value. How can I solve this?? TIA -
How to export attendance login-logout data with login Image and logout image in Excel sheet using python django
I am using the python Django framework. I have to export filtered data in an excel sheet, but in that, I have modified some of the fields. Also, have to export login-logout images in that, I have already done it with CSV. but in csv can not format data as well as can not show images. it is showing me only URL strings. I am showing the code to export CSV: def ReportsDowbload(request): employees_attendance = EmployeeAttendance.objects.none() employee = Employee.objects.none() TotalHours=0 if request.GET: EmpId= request.GET["EmployeeId"] start_date= request.GET["start_date"] end_date= request.GET["end_date"] try: employee = Employee.objects.get(EmployeeId=EmpId) except Employee.DoesNotExist: employee = None else: e_id=employee.id employees_attendance = EmployeeAttendance.objects.filter(EmployeeId=e_id, Attendance_Date__range=(start_date,end_date)) mylist = [] for emp in employees_attendance: Logintime=emp.InTime Logouttime=emp.OutTime Date=emp.Attendance_Date InTime = datetime.datetime.fromtimestamp(Logintime) t1 = dt.strptime(str(InTime), '%Y-%m-%d %H:%M:%S') emp.InTime=t1.strftime('%I:%M %p') if Logouttime!=0: OutTime = datetime.datetime.fromtimestamp(Logouttime) t2 = dt.strptime(str(OutTime), '%Y-%m-%d %H:%M:%S') emp.OutTime=t2.strftime('%I:%M %p') WorkHours=t2-t1 emp.WorkHours=WorkHours dailyhours=int(WorkHours.total_seconds()) mylist.append(dailyhours) else: WorkHours=0 emp.WorkHours=0 dailyhours=0 emp.OutTime hours=sum(mylist)/3600 TotalHours=round(hours,2) file_name = "EmployeeReport"+str(date.today())+".csv" response = HttpResponse(content_type = 'text/csv') writer = csv.writer(response) if employee: writer.writerow(['Employee Id', employee.EmployeeId]) writer.writerow(['Employee Name', employee.EmployeeName]) writer.writerow(['Division', employee.Division.DivisionName]) writer.writerow(['Department', employee.Department.DepartmentName]) writer.writerow(['Total WorkHours',TotalHours]) writer.writerow([]) writer.writerow(['Attendance Date','In Time', 'Out Time', 'Daily WorkHours']) for item in employees_attendance: writer.writerow([item.Attendance_Date, item.InTime, item.OutTime,item.WorkHours]) response['Content-Disposition'] = 'attachment; filename = "'+ file_name +'"' return response else: writer.writerow(['Employee does not … -
django-tenants TypeError: argument of type 'TenantQueryset' is not iterable
i've made a system for hotels , i want to give it to several hotels with the same base code , i have used django-tenant-schemas and this is my SHARED_APP and TENANT_APP but when i try python manage.py migrate_schemas --shared it only creates my shared apps list and when i try either manage.py migrate_schemas --tenant or manage.py migrate_schemas it raise this error if public_schema_name in tenants: TypeError: argument of type 'TenantQueryset' is not iterable this is my settings.py SHARED_APPS = [ 'tenant_schemas', 'users', 'rosetta', 'widget_tweaks', 'import_export', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TENANT_APPS = [ 'rooms', 'vistors', 'booking', 'costs', 'payments', 'cancel', ] INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL= "rooms.Hotel" #db engine 'ENGINE': 'tenant_schemas.postgresql_backend', my models.py class Hotel(TenantMixin): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name class Room(models.Model): room_no = models.IntegerField(unique=True) #others and i have more models but all of them inherited from models.Model ,in the public schema it only created tables for SHARED_APP apps , TENANT_APP not created django version 2.2 db : postgresql is there something else i have to change or is'nt there another way to achieve that please -
The carousel cannot slide to the next image when I use forloop in Django
views.py def index(request): books = Book.objects.all()[:4] print(books) context = {'books':books} return render(request,'index.html',context) index.html <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for book in books%} {% if forloop.first %} <li data-target="#myCarousel" data-slide-to="{{forloop.counter0}}" class="active"></li> {% else %} <li data-target="#myCarousel" data-slide-to="{{forloop.counter0}}"></li> {% endif %} {%endfor%} </ol> <div class="carousel-inner"> {% for book in books %} {% if forloop.first %} <div class="carousel-item active"> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ book.image.url}}" alt="{{book.title}}"> <div style="font-size:50px;color:red;" class="carousel-caption">{{ book.title }}</div> </div> {% else %} <div class="carousel-item "> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ book.image.url}}" alt="{{book.title}}"> <div style="font-size:25px;" class="carousel-caption">{{ book.title }}</div> </div> {% endif %} {% endfor %} </div> <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> I am going to create an image carousel slider for the Book first four model objects. However when I put previous and next icons and after clicking the button it only staying at the first image instead of sliding to the next image. May I ask where is the problem that the image carousel could not slide? -
how to automatically rerun your page when you have urlopen error getaddrinfo failed
I would like to know how to automatically refresh or rerun a django view when I have this "urlopen error getaddrinfo failed" error, sometimes suddenly the view works and sometimes we have to update the html page. sometimes it comes from the long loading of the view i want to fix this problem but i dont know how, my code is working fine, everything is normal thank you -
Trouble with using ngix and uwsgi
I am trying to connect django uwsgi and nginx however, I have encountered some problems as below. when I start nginx, I got an error as below nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied) whenever I access 127.0.0.1:8080 which is configured in nginx conf file, I got 504 Gateway Time-out. But I can access 127.0.0.1:80 and can see Welcome to nginx! html page. I share my nginx conf file and please help me to connect uwsgi(127.0.0.1:8000) and nginx(127.0.0.1:8080) upstream django{ server 127.0.0.1:8000; } server{ listen 8080 default_server; server_name 127.0.0.1 default; charset utf-8; location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; root /home/bigdata/Django_Web; } location =/favicon.ico { return 204; access_log off; log_not_found off; } location /static { alias /home/bigdata/Django_Web/staticfiles; } } Appreciate in advance! -
Python Django converting media file
How can I convert video file from .mp4 to other formats (mpg,mpeg,3gp and mp3) with a Django or python libraries? -
Add a custom button/ tag and control its function using a python script in Django web application
I am quite new to web application development (Django). However, I have a bit of experience in working with html, css, and python. I am developing an application where the user will upload documents as input and change the available parameters values and the application will produce a document in excel format. (Text editor: VS Code) (To get an intuition, consider the online pdf resizing applications as an example). I am building the application from scratch. The major issue is modifying the inputs and producing desired output. My approach towards it is: Create python scripts for the different major actions( As per our example, create py scripts for pdf compression, merging two pdfs and so on). Ask the user to upload the required documents. Store the docs uploaded (only temporarily) and use them for further operations (with assumption that default sqlite3 will be sufficient). In the webpage, add a button or a link (e.g. "Compress", "Merge") and embed the python script (paste the script or add a link to its location) created in step1. That will perform the specific task when the button is pressed. I have achieved till the step 2 in my task but am lost on how … -
django-mailbox is not working for outlook
I am using django-mailbox for getting inbox emails From This package, HERE This is working fine for pop3 mailbox type for Gmail account but not working outlook account I am getting following error code b'-ERR Logon failure: unknown user name or bad password.' but when I am using imap mailbox type then I am able to get emails from Gmail and outlook but when I am using imap mailbox type my emails are deleted from my Gmail and outlook servers Here is my URI setting for outlook and gmails POP3 Gmail: pop3+ssl://username:password@imap.gmail.com Outlook: pop3+ssl://username:password@imap.outlook.com IMAP Gmail: imap+ssl://username:password@imap.gmail.com Outlook: imap+ssl://username:password@imap.outlook.com Let me know if someone has any solutions Thanks in advance -
How to access Django app in docker container from another machine?
I am pretty new to Docker and Django. So what i did was, putty to a linux server and created a folder in the root directory and then using django-admin startproject I started a new project. Now, since I am using putty for ssh terminal access, I will not be able to access a browser in the linux machine and then ping 127.0.0.1:8000 to see whether "congratulations!" screen by Django is visible or not. So I assumed that the server might be running after runserver command. Then using docker I prepared a container in the linux machine where I have exposed port 9000. Also I cannot access this container since I cannot access the browser in the linux machine. Now, I have three questions below: 1.) How to access this docker container (inside the linux machine) using my windows machine? By this I mean, if I open up lets say google chrome browser in the windows machine, and enter some url:port, will I be able to see the "congratulations!" screen on my browser on windows? 2.) I am pretty confused with how this container network port and ip works (I mean how does host or any other pc access this … -
DRF with MongoDB getting the object data
I am using DRF with MongoDB. I am inserting the JSON object in MongoDB in the external source. This is my schema _id : ObjectID("") feed: Object sensor_type: Int received_at: datetime.now() My question is how I can get this data using DRF using the serializer. I have one doubt is there any way I can this feed object?