Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku release section overrides release process
I have the following heroku.yml file for containers deployment: build: docker: release: dockerfile: Dockerfile target: release_image web: Dockerfile config: PROD: "True" release: image: web command: - python manage.py collectstatic --noinput && python manage.py migrate users && python manage.py migrate run: # web: python manage.py runserver 0.0.0.0:$PORT web: daphne config.asgi:application --port $PORT --bind 0.0.0.0 -v2 celery: command: - celery --app=my_app worker --pool=prefork --concurrency=4 --statedb=celery/worker.state -l info image: web celery_beat: command: - celery --app=my_app beat -l info image: web When I deploy I get the following warning, which does not make any sense to me: Warning: You have declared both a release process type and a release section. Your release process type will be overridden. My Dockerfile is composed of two stages and I want to keep only the release_image stage: FROM python:3.8 as builder ... FROM python:3.8-slim as release_image ... According to the docs the proper way to choose release_image is to use the target section within build step. But it also mentions that I can run my migrations within a release section. So what am I supposed to do to get rid of this warning? I could only live with it if it was clear that both my migrations and … -
Large file upload problem with Azure file storage and Django
I use Azure file storage for media files in my django app. When I upload small data or images it works fine. But when I upload large dataset about 300 MB of size then request take 2 minutes and then I see an error like that in browser azure.core.exceptions.HttpResponseError azure.core.exceptions.HttpResponseError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer')) When I look at inside of the container in storage account in Azure I see uploaded files. But I never get a response back it just terminate the connection. I am using version of django 3.2.11, django-storages[azure] 1.12.3 and Azure file storage StorageV2. Ps: Please consider that I am not allowed to use another file storage like AWS S3, and etc. -
type object 'Post' has no attribute 'published' django by exapmle book
I'm following Django by example book first chapter and when I'm trying to access http://127.0.0.1:8000/blog/ i got this error type object 'Post' has no attribute 'published' and in the terminal it says this is the error File "/Users/ziad/Documents/code/blog/mysite/blog/views.py", line 6, in post_list posts = Post.published.all() but i can't figure out what is the issue i double checked the code and everything is fine this is my views.py def post_list(request): posts = Post.published.all() return render(request,'blog/post/list.html',{'posts': posts}) models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') ` class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. ` -
Django save user IP each new Sign In
Each time the user logs in, I want to store the IP address in a list of the respective user, so that each user has a list with all IP addresses used during login. How could I do this? Custom User Model class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('E-Mail'), unique=True) username = models.CharField(max_length=150, unique=True) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(default=timezone.now) code = models.ImageField(blank=True, upload_to='code') objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] Views SingIn def signin_view(request): if request.user.is_authenticated: return HttpResponseRedirect('/') form = SigninForm(request.POST or None) if form.is_valid(): time.sleep(2) email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, email=email, password=password) if user != None: login(request, user) return redirect("/dashboard/") else: request.session['invalid_user'] = 1 return render(request, "signin.html", {'form': form}) -
Getting - Can't install traversal 'has' exists on NodeSet, error when matching Node
I'm using Django with Neomodel and django_neomodel to connect to AuraDB and fetch data. In my views I'm doing: def homePage(request): name = request.user.last_name + ', ' + request.user.first_name my_person_node = Person.nodes.get(person_name=name) ... My Person model: class Person(DjangoNode): id = UniqueIdProperty(primary_key=True) person_id = StringProperty(unique_index=True) person_name = StringProperty(unique_index=False) service_position = StringProperty(unique_index=False) has = Relationship('Research_Topic', 'has', model=Person_has_Research_Topic) is_teaching = RelationshipTo('Course', 'is_teaching') class Meta: app_label = 'profiles' def __str__(self): return self.person_name and 'has' relation model: class Person_has_Research_Topic(StructuredRel): type = StringProperty() This throws an error: ValueError: Can't install traversal 'has' exists on NodeSet -
'JobSerializer' object has no attribute 'email' what i am missing?
serializers.py class JobSerializer(serializers.ModelSerializer): # image = Base64ImageField(max_length=None, # use_url=True) # applicant = serializers.ForeignKe applicant = serializers.StringRelatedField(many=True) email = serializers.SerializerMethodField("get_username_from_user") company_name = serializers.SerializerMethodField("get_company_name_from_user") class Meta: model = Jobs fields = ['company_name', 'email', 'title', 'desc', 'image', 'price', 'category', 'applicant'] # extra_kwargs = {"email": {"required": False}} def get_username_from_user(self, jobs): email = jobs.user.email return email def get_company_name_from_user(self, jobs): company_name = jobs.user.company_name return company_name views.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def api_detail_jobs_view(request, id): try: jobs = Jobs.objects.get(id=id) except Jobs.DoesNotExist: data = {} data['response'] = "Job does not exist" return Response(data, status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = JobSerializer(jobs) user = request.user if user == serializer.email: data = {} auth_show = serializer data['title'] = auth_show.title data['desc'] = auth_show.applicant return Response(data) else: no_auth_show = serializer data = {} data['title'] = no_auth_show.title return Response(data) here is serializers.py in which 'email' is included. i know i am missing something very clear but it took hours to realise :) so any help will be appriciated i am trying to show 'applicants' only to users who owns the 'job' but i can't pass 'email' from serializer in to the view. I can't pass any attribute from serializer in to data dict. -
Run script python in web browser
I have a script python for Reading biometric identity card with a card reader this script use this https://github.com/roeften/pypassport, i want to creat a web app with django and use this script and run it on client machine (on web browser) , each user can read his card with a card reader on this web application. how can i do that ? any idea can be useful looked at this part of script that I want to run on the client browser: from pypassport.reader import ReaderManager from pypassport.reader import ReaderManager from pypassport.epassport import EPassport, mrz r = ReaderManager() reader = r.waitForCard() p = EPassport(reader,"YOURMRZINFO") p.register(print) p.setCSCADirectory("C:\\TEMP") p.doBasicAccessControl() p.doActiveAuthentication() p['DG2'] -
"The specified alg value is not allowed" error raises when launching django using gunicorn
I have a database web application running on nginx (front-end) + django + postgresql and I am trying to use gunicorn to manage communications between nginx and django. I use JWT to manage authentication on the application. When I launch the service using django directly, I get "alg": "HS512" token but for some reason I don´t understand, when I launch the same django application using gunicorn, the token generated corresponds to "alg": "HS256" and I get the following error: File "/srv/gather-api/env/lib/python3.9/site-packages/jwt/api_jws.py", line 232, in _verify_signature raise InvalidAlgorithmError("The specified alg value is not allowed") I tried changing my settings.py file from: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=ACCESS_TOKEN_LIFETIME), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=REFRESH_TOKEN_LIFETIME), 'ALGORITHM': 'HS512', 'SIGNING_KEY': SECRET_KEY } to: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=ACCESS_TOKEN_LIFETIME), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=REFRESH_TOKEN_LIFETIME), 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY } but still get the same error. Questions: Why the algorithm generating the token changes when I launch the application using gunicorn? Is there anyway to indicate my django application to allow this algorithm and therefore get a valid token? Thanks in advance. Let me know if more information is required. -
django: how to simultaneously render and redirect to the desired page
I need to render and redirect the page CreateOrder.html at path: "/order/", after click the form submit button. is there a way to do the rendering and redirecting at the same time? (i.e. update the CreateOrder.html and redirect to this page) def CreateOrder(request): navi_load = request.session['navi_load'] navi_unload = request.session['navi_unload'] dist = request.session['dist'] charge = request.session['charge'] return render(request, 'OnlinePricing/CreateOrder.html', {'pickup_address': navi_load, 'delivery_address': navi_unload, 'distance': dist, 'charge': charge}) -
Django - Creating a new user model extending an already extended user model
I am starting a new project and I created my user model extending the AbstractBaseUser, like below: class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True) user_name = models.CharField(max_length=150, unique=True) ... I am wondering whether it is possible and makes sense to create my user (e.g. Teacher) by extending NewUser, and adding all of the Teacher profile info. That would be something like: class Teacher(NewUser): role = models.CharField(max_length=150) title = models.CharField(max_length=150) date_of_birth = models.CharField(max_length=150) ... Would this be good practice and would it allow me to use the built-in authentication methods with DRS? And would this give more flexibility if then I want to enable other users (e.g. Students) to also register an account and log-in? Or would it make more sense to just use NewUser directly? Would Really appreciate some advice/ insight! -
DoesNotExist at /accounValid OAuth Redirect URIs, Deauthorize callback URL, Data Deletion Request URLts/linkedin_oauth2/login/
I am login with Instagram on our website but cannot save changes. show issue the URL not valid please give me any suggestion whose URL use in these three options our Django website original URL localhost. -
Is there any other way to implement RichTextField in a django blog
I'm working on my blog web using django. In my models.py I implemented RichtextField instead of the normal CharField or Textfield or others. I already imported it like this from ckeditor.fields import RichTextField after installing 'ckeditor' in 'INSTALLED_APPS in my projects settings.py. Everything is working just Fine! But there is problem! The problem i'm facing is, I don't get to see the result of whatever I type in in my Django admin site using the RichTextField except plain text and some HTML tags in my localhost page. What I mean is: Supposing in my text-typing, I have something like this 'This is a bright new day...', and I want to bold 'bright' like this- 'bright'. I get to see it working perfectly in my django admin site. But when I refresh to my localhost page to where the text-typing is displayed, I get to see some weird HTML tag like this <b 'bright' /b> instead of 'bright'. And it did the same thing when I used summernotes. So, please I will like to know why it's going that direction instead of the direction I want. Secondly, the possibly solution to help me make move in the direction I want. This … -
Can we get number of chromeosdevices using google API
I'm wondering is there an option to get exact number of devices from googleAPI like a parameter or something, because currently only we can only filter and search for a device and get max 200 devices per page, and if I would like to know how many devices there are how I can do that? I need this for my pagination, I cannot go through every single page and make 100 requests because it would be too much time consuming, for example if you have 10k devices, you can only get 200 per page(request) that's like calling API 500 times. Thanks in advance. -
Is possible to show subapps at the main admin panel in Django?
Recently, one of my apps if getting a lot of new models and growing faster than I would like. The result is a lot of new elements in my app's main admin panel. So I want to create subapps. Something like this example: Literature Genre (startapp name) - Ficcion (subapp1 name) - Realistic Fiction (subapp model) - Science Fiction (subapp model) - Historical Ficction (subapp model) - Mistery (subapp2 name) - Detective (subapp model) - Paranormal (subapp model) (and so) So I created the subapp in my folder with cd startapp python ../manage.py startapp subapp1 Moved the code to the new files and folders, registered nested apps as: INSTALLED_APPS = [ ... 'startapp', 'startapp.subapp1', 'startapp.subapp2', ... ] But my main admin panel looks like this: startapp - model1 - model2 subapp1 - submodel1 - submodel2 Like they were different apps instead of being related and grouped. I really don't know if what I'm asking for is possible to do (I'm more a backend developer, so I have little experience with Django forms). Thanks in advance. -
Let users create their own database datable with Python Django
So, As the title describe I would like to have an authenticated user be able to create tables in the database (for instance, by filling a text field in a form and clicking a button). Basically, my idea is to create a to-do-list manager where, a user can create its own to-do list, or more, (tables in the database) and add things to it (row inside the table). I can't understand how to attach more tables to a single authenticated user. Because the structure of the table must be fixed, the idea was to create the model of this table in models.py inside my app, and use the Django signal listening to the POST action on the button to create a new object (so a new table) from the class defined on models.py. The "fixed table" should be: class base_table(models.Model): link = models.CharField(max_length=30) def __str__(self): return self.link Now my doubt is how do I link every table to a specific user? Is it possible to check the name of the table, let's say something like user1_1, user1_2 user1_3 or is there a cleaver way I'm missing in Django to do that? -
Django: If objects queryset is empty write zero instead. I solve this with numpy but I want a direct solution in the queryset
I think there should be an easier and more elegant solution but I cannot find it. I have the following in views.py. As you can see I achieve want I want with numpy but I want a direct solution: myarray = np.asarray(MyDatabase.objects.filter( status='user').values_list('name','age').order_by('age')) if myarray.size==0: myarray=np.zeros((1,2)) What I want is to set zeros when the object queryset is empty. I just dislike using the extra lines. I wonder if there is a way to directly ouput zeros when the objects filter is empty. In the documentation it says that django 4.0 comes with default() option in the queryset to do precisely what I'm asking but no example is given. I would appreciate it if you share your solution Thanks -
How to update graphene-django to latest version
I am facing difficulties to update the graphene-django to the latest version. while I am trying pip install "graphene-django>=3", it shows the error given below: ERROR: Could not find a version that satisfies the requirement graphene-django>=3 (from versions: 1.0.dev20160909000001, 1.0.dev20160910000001, 1.0.dev20160917000001, 1.0.dev20160919000001, 1.0.dev20160919000002, 1.0.dev20160919000003, 1.0.dev20160919000004, 1.0.dev20160920000001, 1.0.dev20160922000001, 1.0, 1.1.0, 1.2.0, 1.2.1, 1.3, 2.0.dev2017072501, 2.0.dev2017072601, 2.0.dev2017073101, 2.0.dev2017083101, 2.0.0, 2.1rc0, 2.1rc1, 2.1.0, 2.2.0, 2.3.0, 2.3.2, 2.4.0, 2.5.0, 2.6.0, 2.7.0, 2.7.1, 2.8.0, 2.8.1, 2.8.2, 2.9.0, 2.9.1, 2.10.0, 2.10.1, 2.11.0, 2.11.1, 2.12.0, 2.12.1, 2.13.0, 2.14.0, 2.15.0, 3.0.0b1, 3.0.0b2, 3.0.0b3, 3.0.0b4, 3.0.0b5, 3.0.0b6, 3.0.0b7) ERROR: No matching distribution found for graphene-django>=3 Does anybody have a solution? -
bootstrap JavaScript not working as in when the screen size is decreased the menu bar wont work
so I'm working with Django for the first time and I am following a tutorial, bootstrap is used for the navbar so I added the CSS from bootstrap it worked but the JavaScript from bootstrap is not working, I know that because when the screen size is reduced, a menu bar appears instead of the navbar items but it doesn't work when clicked. How can I fix this? <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRMain</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> {% include "accounts/navbar.html"%} {% block content %} {% endblock %} <hr> <h5>footer</h5> </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </html> 2 screenshots of the before and after:- https://i.stack.imgur.com/7I5he.png https://i.stack.imgur.com/JteLC.png -
Encode ImageField in base64 and store it in DB instead of path of the image
settings.py STATIC_URL = '/static/' STATICFILES_DIRS= [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = BASE_DIR.joinpath('staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR.joinpath('media')) config/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('proj.urls')), ] += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Book(models.Model): image = models.ImageField(upload_to='upload/', blank=True, default=None, null=True) views.py class BookCreateView(CreateView): model = Book template_name = "book_new.html" fields = "__all__" book_new.html {% extends 'base.html' %} {% block content %} <h1>New Book</h1> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock content %} proj/urls.py urlpatterns = [ path("", home_view, name="home"), path("book/new/", BookCreateView.as_view(), name="book_new"), ] I have written this code which will upload the image to /media/upload/ and the path of the file will be saved on the database like upload/image_file.png. I don't want to store the file path in the database, I want to read the file, convert it to base64 and store the encoded string in the database. How can I do that? I've searched a lot and tried to figure this out on my own as I usually do, but this one's a little hard for me, here's what I've read so far: Binary image display in Django template Save base64 image in django file field Saving a decoded temporary image to Django Imagefield a … -
django-admin startproject gives SyntaxError
I tried to start a new project with Django 4.0. After installing Django in environment folder (Anaconda/envs/taskman/) I created a new folder somewhere in my E: drive and by using Windows command line created a new folder Django_site/. Then from this folder I typed in command line prompt: django-admin startproject lifetool and got the following: (taskman) E:\Projects\Django_site>django-admin startproject lifetool Traceback (most recent call last): File "E:\Programs\Anaconda\envs\taskman\Scripts\django-admin-script.py", line 5, in <module> from django.core.management import execute_from_command_line File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\management\__init__.py", line 16, in <module> from django.core.management.base import ( File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\management\base.py", line 13, in <module> from django.core import checks File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\checks\__init__.py", line 18, in <module> import django.core.checks.translation # NOQA isort:skip File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\checks\translation.py", line 3, in <module> from django.utils.translation.trans_real import language_code_re File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\utils\translation\trans_real.py", line 485 while (i := lang_code.rfind('-', 0, i)) > -1: ^ SyntaxError: invalid syntax What is wrong? Do I need to correct invalid syntax in installed Django package? Help me to clarify the issue -
How to pass a query parameter to SerializerMethodField in django rest framework?
I want to filter out some instance based on the query parameter I get in the GET call. class RevisionSerializer(serializers.ModelSerializer): slot_info = serializers.SerializerMethodField(required=False, read_only=True) batch_config = serializers.SerializerMethodField(required=False, read_only=True) class Meta: model = Revision fields = ['id', 'status', 'revision_id', 'instructor', 'number_of_classes', 'start_date', 'slot', 'slot_info', 'tinyurl', 'zoom_link', 'batch_config'] read_only_fields = ['revision_id'] def get_batch_config(self, obj): # filter this on the incoming data from the GET call related_batches = CompensationClass.objects.select_related('style', 'instructor').filter( compensation_class_id=obj.revision_id) batch_config_values = related_batches.values('batch_id', 'age_group', 'level', 'course_version', 'style__name', 'class_number') return batch_config_values This is my serializer and I will be passing one date and based on that date I want to filter my serializermethodfield. How can I achieve this? -
Using AJAX to test for readiness of data through polling
I have a Django application and am attempting to utilize Ajax and Redis to poll for the completion of a long calculation. The difficulty I am having is that my Ajax is "recalling itself" after the timeout period. My intended action is for Ajax to test for the completion of a process (indicated by a Redis channel). The difficulty I am having is that the Ajax is called once upon page load, again upon page click (which is intended), but does not "re-poll" at the regular 3 second intervals to test my retrieval view for my result. Here is the view.py: @login_required() def retrieveAsync(request): if is_ajax(request=request) and request.method == "GET": show_df = request.session['win_deep_show_df'] df = [] msg = ['you have called retrieveAsync'] if show_df == False: ret_val = { 'do_what': 'nothing', 'msg': msg, 'df': df, } # user has not requested the dataframe info yet...do nothing return JsonResponse(ret_val, status=200) elif show_df == True: redisChannel = request.session['win_deep_redis_channel'] data_ready = (REDIS_INSTANCE.get(redisChannel + 'reco_data_ready').decode('utf-8') == 'yes') if data_ready is False: msg = "Loading data..." ret_val = { 'do_what': 'wait', 'msg': msg, 'df': df, } return JsonResponse(ret_val, status=200) elif data_ready is True: ret_dict = pickle.loads(REDIS_INSTANCE.get(redisChannel + 'ret_dict')) msg = "Your data is ready now..." … -
Need to get specific field value from one model to another
model 1 class Users(models.Model): JOINING_ROLES_CHOICES= ( ('sde-intern','SDE Intern'), ('sde-trainee','SDE Trainee'), ('sde_1','SDE I'), ('ui/ux','UI/UX Designer'), ('quality-engineer-trainee','Quality Engineer Trainee'), ('quality-engineer','Quality Engineer'), ('product-manager','Product Manager'), ('technical-manager','Technical Manager'), ('technical-architect','Technical Architect'), ('technical-lead','Technical Lead') ) BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) billable_and_non_billable=models.CharField(max_length=250,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') def__str__(self): return self.employee_name model 2 class Consolidated(models.Model): emp_name=models.OneToOneField(Users, on_delete=CASCADE, null=True,related_name="user") proj_name=models.OneToOneField(Project,on_delete=CASCADE, null=True) custom_name=models.OneToOneField(Client,on_delete=CASCADE, null=True) Cons_date=models.OneToOneField(Add_Timelog,on_delete=CASCADE, null=True) bill_no_bill=models.ManyToManyField(Users,related_name="bill") hours_spent = models.OneToOneField(Add_Timelog,on_delete=CASCADE, null=True,related_name="hours") def __str__(self): return str(self.emp_name) I need to get the employee_name and billable_and_non_billable values from the Users model to Consolidated model fields(emp_name and bill_no_bill). I tried using the above code but it is returning the employee name value to the bill_no_bill field also. Kindly help me to get the value from billable_and_non_billable field for bill_no_bill field. -
Replace chars in substring of a string
I'm working on a blog with Django, however my question is Python related not really Django related. To write my blog posts I use Quill which generate the post in HTML. I save this HTML in the database than display the post using the filter |safe. Until now everything worked well until ... I want to display HTML code as examples which is obviously considered as safe because of the filter and is interpreted by the browser. As a workaround I try to create a function able to escape HTML code as soon as they are between the tags but not escape the HTML out of this tag. For example if quill return this: <p> This is the code you need: <pre class="myclass"> <div> The code </div> </pre> </p> I would like to save in database something like this: <p> This is the code you need: <pre class="myclass"> &lt;div&gt; The code &lt;/div&gt; </pre> </p> That way the safe tag will make the HTML code interpreted and display the HTML code inside the tag. My problem is I don't find a way to make a replacement for each character only between the tags and keep everything as it is. Basically I … -
Django api backend filter table
The goal is to get the photos associated with a listing id. I have the bellow structure in django rest framework Model.py class Pictures(models.Model): index = models.BigIntegerField(blank=True, null=True) listing_id = models.ForeignKey( Listings, models.DO_NOTHING, blank=True, null=True) post_title = models.TextField(blank=True, null=True) guid = models.TextField(blank=True, null=True) post_mime_type = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'pictures' Serializer.py class PicturesSerializer(serializers.ModelSerializer): class Meta: model = Pictures fields = ('index', 'listing_id', 'guid') Views.py class PicturesListViewAlt(generics.ListAPIView): serializer_class = PicturesSerializer def get_queryset(self): if self.request is None: return Pictures.objects.none() id_of_listing = self.kwargs['listing_id'] return Pictures.objects.filter(listing_id=id_of_listing) urls.py app_name = 'pics' urlpatterns = [ re_path('^pictures/(?P<listing_id>.+)/$', views.PicturesListViewAlt.as_view()), ] I keep getting the bellow errors. django.db.utils.ProgrammingError: column pictures.listing_id_id does not exist LINE 1: ...ELECT COUNT(*) AS "__count" FROM "pictures" WHERE "pictures"... ^ HINT: Perhaps you meant to reference the column "pictures.listing_id". [03/Feb/2022 11:58:17] "GET /api/pictures/123/ HTTP/1.1" 500 24360 Although I have never initiated a column listing_id_id And ProgrammingError at /api/pictures/123/ column pictures.listing_id_id does not exist LINE 1: ...ELECT COUNT(*) AS "__count" FROM "pictures" WHERE "pictures"... ^ HINT: Perhaps you meant to reference the column "pictures.listing_id". Which when I change my filter to pictures__listing_id I get django.core.exceptions.FieldError: Cannot resolve keyword 'pictures' into field. Choices are: guid, id, index, listing_id, listing_id_id, post_mime_type, post_title [03/Feb/2022 …